/*!
 * jQuery JavaScript Library v3.5.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2020-05-04T22:49Z
 */
( function( global, factory ) {

	"use strict";

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

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

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

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

var arr = [];

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

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


var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var fnToString = hasOwn.toString;

var ObjectFunctionString = fnToString.call( Object );

var support = {};

var isFunction = function isFunction( obj ) {

      // Support: Chrome <=57, Firefox <=52
      // In some browsers, typeof returns "function" for HTML <object> elements
      // (i.e., `typeof document.createElement( "object" ) === "function"`).
      // We don't want to classify *any* DOM node as a function.
      return typeof obj === "function" && typeof obj.nodeType !== "number";
  };


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


var document = window.document;



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

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

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

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

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


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

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



var
	version = "3.5.1",

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

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

jQuery.fn = jQuery.prototype = {

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

	constructor: jQuery,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// Return the modified object
	return target;
};

jQuery.extend( {

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

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

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

	noop: function() {},

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

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

		proto = getProto( obj );

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

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

	isEmptyObject: function( obj ) {
		var name;

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

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

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

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

		return obj;
	},

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

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

		return ret;
	},

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

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

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

		first.length = i;

		return first;
	},

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

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

		return matches;
	},

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

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

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

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

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

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

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

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

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

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

function isArrayLike( obj ) {

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

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

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

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

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

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

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

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

	// Regular expressions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	rsibling = /[+~]/,

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

		return nonHex ?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	results = results || [];

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

		return results;
	}

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

		if ( documentIsHTML ) {

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

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

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

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

					// Element context
					} else {

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

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

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

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

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

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

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

				newSelector = selector;
				newContext = context;

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

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

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

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

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

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

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

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

	function cache( key, value ) {

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

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

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

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

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

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

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

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

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

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

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

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

	return a ? 1 : -1;
}

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

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

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

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

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

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

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

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

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

			return elem.disabled === disabled;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				if ( elem ) {

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

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

				return [];
			}
		};
	}

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

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

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

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

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

				return tmp;
			}
			return results;
		};

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

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

	// QSA and matchesSelector support

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

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

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

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

			var input;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		assert( function( el ) {

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

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

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

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

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

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

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

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

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

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

			// Otherwise we know they are disconnected
			1;

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

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

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

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

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

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

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

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

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

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

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

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

		return i ?

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

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

	return document;
};

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

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

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

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

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

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

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

Sizzle.contains = function( context, elem ) {

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

Sizzle.attr = function( elem, name ) {

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

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

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

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

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

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

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

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

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

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

	return results;
};

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

	if ( !nodeType ) {

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

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

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

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

	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

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

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

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

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

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

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

		"CHILD": function( match ) {

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

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

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

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

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

			return match;
		},

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

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

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

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

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

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

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

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

	filter: {

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

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

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

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

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

				result += "";

				/* eslint-disable max-len */

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

			};
		},

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

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

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

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

					if ( parent ) {

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

										return false;
									}
								}

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

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

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

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

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

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

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

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

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

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

						} else {

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

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

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

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

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

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

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

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

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

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

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

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

		"PSEUDO": function( pseudo, argument ) {

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

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

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

			return fn;
		}
	},

	pseudos: {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		"checked": function( elem ) {

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

		"selected": function( elem ) {

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

			return elem.selected === true;
		},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	while ( soFar ) {

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

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

		matched = false;

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

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

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

		if ( !matched ) {
			break;
		}
	}

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

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

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

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

	return combinator.first ?

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

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

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

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

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

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

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

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

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

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

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

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

	return newUnmatched;
}

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

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

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

			matcherOut = matcher ?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return elementMatcher( matchers );
}

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

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

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

			if ( outermost ) {

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

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

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

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

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

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

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

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

				if ( seed ) {

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

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

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

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

					Sizzle.uniqueSort( results );
				}
			}

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

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

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

	if ( !cached ) {

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

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

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

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

	results = results || [];

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

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

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

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

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

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

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

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

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

					break;
				}
			}
		}
	}

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

// One-time assignments

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

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

// Initialize against the default document
setDocument();

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

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

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

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

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

return Sizzle;

} )( window );



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

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




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

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


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

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

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;



function nodeName( elem, name ) {

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

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



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

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

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

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

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

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

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

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

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

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

		ret = this.pushStack( [] );

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

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

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


// Initialize a jQuery object


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

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

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

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

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

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "<" &&
				selector[ selector.length - 1 ] === ">" &&
				selector.length >= 3 ) {

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

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

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

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

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

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

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

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

					return this;

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

					if ( elem ) {

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			return elem.contentDocument;
		}

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

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

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

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

		if ( this.length > 1 ) {

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

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

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



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

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

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

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

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

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

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

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

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

		// Fire callbacks
		fire = function() {

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

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

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

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

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

			firing = false;

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

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

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

		// Actual Callbacks object
		self = {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return self;
};


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

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

	try {

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

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

		// Other non-thenables
		} else {

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

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

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

jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

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

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

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

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

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

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

									returned = handler.apply( that, args );

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

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

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

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

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

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

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

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

									// Handle all other returned values
									} else {

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

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

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

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

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

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

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

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

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

					return jQuery.Deferred( function( newDefer ) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// All done!
		return deferred;
	},

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

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

			// count of unprocessed arguments
			i = remaining,

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

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

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

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

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

				return master.then();
			}
		}

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

		return master.promise();
	}
} );


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

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

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




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




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

jQuery.fn.ready = function( fn ) {

	readyList
		.then( fn )

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

	return this;
};

jQuery.extend( {

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

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

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

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

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

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

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

jQuery.ready.then = readyList.then;

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

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

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

} else {

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

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




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

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

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

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

		if ( bulk ) {

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

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

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

	if ( chainable ) {
		return elems;
	}

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

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


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

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

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

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




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

Data.uid = 1;

Data.prototype = {

	cache: function( owner ) {

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

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

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

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

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

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

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

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

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

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

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

			return this.get( owner, key );
		}

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

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

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

		if ( key !== undefined ) {

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

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

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

			i = key.length;

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

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

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

var dataUser = new Data();



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

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

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

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

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

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

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

	return data;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

			return data;
		}

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

		if ( fn ) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

var documentElement = document.documentElement;



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

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

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

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

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

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



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

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

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

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

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

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

		while ( maxIterations-- ) {

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

		}

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

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

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

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


var defaultDisplayMap = {};

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

	if ( display ) {
		return display;
	}

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

	temp.parentNode.removeChild( temp );

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

	return display;
}

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

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

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

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

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

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

	return elements;
}

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

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

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

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



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

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

	div.appendChild( input );

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

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

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


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

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

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

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

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


function getAll( context, tag ) {

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

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

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

	} else {
		ret = [];
	}

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

	return ret;
}


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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		attached = isAttached( elem );

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

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

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

	return fragment;
}


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

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	global: {},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	},

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

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

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

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

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

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

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

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

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( nativeEvent ) {

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),

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

			handlers = (
					dataPriv.get( this, "events" ) || Object.create( null )
				)[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;

		for ( i = 1; i < arguments.length; i++ ) {
			args[ i ] = arguments[ i ];
		}

		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

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

				// If the event is namespaced, then each handler is only invoked if it is
				// specially universal or its namespaces are a superset of the event's.
				if ( !event.rnamespace || handleObj.namespace === false ||
					event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, handleObj, sel, matchedHandlers, matchedSelectors,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		if ( delegateCount &&

			// Support: IE <=9
			// Black-hole SVG <use> instance trees (trac-13180)
			cur.nodeType &&

			// Support: Firefox <=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!( event.type === "click" && event.button >= 1 ) ) {

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

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

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matchedSelectors[ sel ] === undefined ) {
							matchedSelectors[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matchedSelectors[ sel ] ) {
							matchedHandlers.push( handleObj );
						}
					}
					if ( matchedHandlers.length ) {
						handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		cur = this;
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	addProp: function( name, hook ) {
		Object.defineProperty( jQuery.Event.prototype, name, {
			enumerable: true,
			configurable: true,

			get: isFunction( hook ) ?
				function() {
					if ( this.originalEvent ) {
							return hook( this.originalEvent );
					}
				} :
				function() {
					if ( this.originalEvent ) {
							return this.originalEvent[ name ];
					}
				},

			set: function( value ) {
				Object.defineProperty( this, name, {
					enumerable: true,
					configurable: true,
					writable: true,
					value: value
				} );
			}
		} );
	},

	fix: function( originalEvent ) {
		return originalEvent[ jQuery.expando ] ?
			originalEvent :
			new jQuery.Event( originalEvent );
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		click: {

			// Utilize native event to ensure correct state for checkable inputs
			setup: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Claim the first handler
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					// dataPriv.set( el, "click", ... )
					leverageNative( el, "click", returnTrue );
				}

				// Return false to allow normal processing in the caller
				return false;
			},
			trigger: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Force setup before triggering a click
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					leverageNative( el, "click" );
				}

				// Return non-false to allow normal event-path propagation
				return true;
			},

			// For cross-browser consistency, suppress native .click() on links
			// Also prevent it if we're currently inside a leveraged native-event stack
			_default: function( event ) {
				var target = event.target;
				return rcheckableType.test( target.type ) &&
					target.click && nodeName( target, "input" ) &&
					dataPriv.get( target, "click" ) ||
					nodeName( target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

// Ensure the presence of an event listener that handles manually-triggered
// synthetic events by interrupting progress until reinvoked in response to
// *native* events that it fires directly, ensuring that state changes have
// already occurred before other listeners are invoked.
function leverageNative( el, type, expectSync ) {

	// Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
	if ( !expectSync ) {
		if ( dataPriv.get( el, type ) === undefined ) {
			jQuery.event.add( el, type, returnTrue );
		}
		return;
	}

	// Register the controller as a special universal handler for all event namespaces
	dataPriv.set( el, type, false );
	jQuery.event.add( el, type, {
		namespace: false,
		handler: function( event ) {
			var notAsync, result,
				saved = dataPriv.get( this, type );

			if ( ( event.isTrigger & 1 ) && this[ type ] ) {

				// Interrupt processing of the outer synthetic .trigger()ed event
				// Saved data should be false in such cases, but might be a leftover capture object
				// from an async native handler (gh-4350)
				if ( !saved.length ) {

					// Store arguments for use when handling the inner native event
					// There will always be at least one argument (an event object), so this array
					// will not be confused with a leftover capture object.
					saved = slice.call( arguments );
					dataPriv.set( this, type, saved );

					// Trigger the native event and capture its result
					// Support: IE <=9 - 11+
					// focus() and blur() are asynchronous
					notAsync = expectSync( this, type );
					this[ type ]();
					result = dataPriv.get( this, type );
					if ( saved !== result || notAsync ) {
						dataPriv.set( this, type, false );
					} else {
						result = {};
					}
					if ( saved !== result ) {

						// Cancel the outer synthetic event
						event.stopImmediatePropagation();
						event.preventDefault();
						return result.value;
					}

				// If this is an inner synthetic event for an event with a bubbling surrogate
				// (focus or blur), assume that the surrogate already propagated from triggering the
				// native event and prevent that from happening again here.
				// This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
				// bubbling surrogate propagates *after* the non-bubbling base), but that seems
				// less bad than duplication.
				} else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
					event.stopPropagation();
				}

			// If this is a native event triggered above, everything is now in order
			// Fire an inner synthetic event with the original arguments
			} else if ( saved.length ) {

				// ...and capture the result
				dataPriv.set( this, type, {
					value: jQuery.event.trigger(

						// Support: IE <=9 - 11+
						// Extend with the prototype to reset the above stopImmediatePropagation()
						jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),
						saved.slice( 1 ),
						this
					)
				} );

				// Abort handling of the native event
				event.stopImmediatePropagation();
			}
		}
	} );
}

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: Android <=2.3 only
				src.returnValue === false ?
			returnTrue :
			returnFalse;

		// Create target properties
		// Support: Safari <=6 - 7 only
		// Target should not be a text node (#504, #13143)
		this.target = ( src.target && src.target.nodeType === 3 ) ?
			src.target.parentNode :
			src.target;

		this.currentTarget = src.currentTarget;
		this.relatedTarget = src.relatedTarget;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || Date.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
	altKey: true,
	bubbles: true,
	cancelable: true,
	changedTouches: true,
	ctrlKey: true,
	detail: true,
	eventPhase: true,
	metaKey: true,
	pageX: true,
	pageY: true,
	shiftKey: true,
	view: true,
	"char": true,
	code: true,
	charCode: true,
	key: true,
	keyCode: true,
	button: true,
	buttons: true,
	clientX: true,
	clientY: true,
	offsetX: true,
	offsetY: true,
	pointerId: true,
	pointerType: true,
	screenX: true,
	screenY: true,
	targetTouches: true,
	toElement: true,
	touches: true,

	which: function( event ) {
		var button = event.button;

		// Add which for key events
		if ( event.which == null && rkeyEvent.test( event.type ) ) {
			return event.charCode != null ? event.charCode : event.keyCode;
		}

		// Add which for click: 1 === left; 2 === middle; 3 === right
		if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
			if ( button & 1 ) {
				return 1;
			}

			if ( button & 2 ) {
				return 3;
			}

			if ( button & 4 ) {
				return 2;
			}

			return 0;
		}

		return event.which;
	}
}, jQuery.event.addProp );

jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
	jQuery.event.special[ type ] = {

		// Utilize native event if possible so blur/focus sequence is correct
		setup: function() {

			// Claim the first handler
			// dataPriv.set( this, "focus", ... )
			// dataPriv.set( this, "blur", ... )
			leverageNative( this, type, expectSync );

			// Return false to allow normal processing in the caller
			return false;
		},
		trigger: function() {

			// Force setup before trigger
			leverageNative( this, type );

			// Return non-false to allow normal event-path propagation
			return true;
		},

		delegateType: delegateType
	};
} );

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var

	// Support: IE <=10 - 11, Edge 12 - 13 only
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
	if ( nodeName( elem, "table" ) &&
		nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
		elem.type = elem.type.slice( 5 );
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.get( src );
		events = pdataOld.events;

		if ( events ) {
			dataPriv.remove( dest, "handle events" );

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = flat( args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		valueIsFunction = isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( valueIsFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( valueIsFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android <=4.0 only, PhantomJS 1 only
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!dataPriv.access( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src && ( node.type || "" ).toLowerCase()  !== "module" ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl && !node.noModule ) {
								jQuery._evalUrl( node.src, {
									nonce: node.nonce || node.getAttribute( "nonce" )
								}, doc );
							}
						} else {
							DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && isAttached( node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html;
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = isAttached( elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i < l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i < l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined && elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: Android <=4.0 only, PhantomJS 1 only
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var getStyles = function( elem ) {

		// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

var swap = function( elem, options, callback ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.call( elem );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );



( function() {

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {

		// This is a singleton, we need to execute it only once
		if ( !div ) {
			return;
		}

		container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
			"margin-top:1px;padding:0;border:0";
		div.style.cssText =
			"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
			"margin:auto;border:1px;padding:1px;" +
			"width:60%;top:1%";
		documentElement.appendChild( container ).appendChild( div );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";

		// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
		reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;

		// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
		// Some styles come back with percentage values, even though they shouldn't
		div.style.right = "60%";
		pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;

		// Support: IE 9 - 11 only
		// Detect misreporting of content dimensions for box-sizing:border-box elements
		boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;

		// Support: IE 9 only
		// Detect overflow:scroll screwiness (gh-3699)
		// Support: Chrome <=64
		// Don't get tricked when zoom affects offsetWidth (gh-4029)
		div.style.position = "absolute";
		scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;

		documentElement.removeChild( container );

		// Nullify the div so it wouldn't be stored in the memory and
		// it will also be a sign that checks already performed
		div = null;
	}

	function roundPixelMeasures( measure ) {
		return Math.round( parseFloat( measure ) );
	}

	var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
		reliableTrDimensionsVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE <=9 - 11 only
	// Style of cloned element affects source element cloned (#8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	jQuery.extend( support, {
		boxSizingReliable: function() {
			computeStyleTests();
			return boxSizingReliableVal;
		},
		pixelBoxStyles: function() {
			computeStyleTests();
			return pixelBoxStylesVal;
		},
		pixelPosition: function() {
			computeStyleTests();
			return pixelPositionVal;
		},
		reliableMarginLeft: function() {
			computeStyleTests();
			return reliableMarginLeftVal;
		},
		scrollboxSize: function() {
			computeStyleTests();
			return scrollboxSizeVal;
		},

		// Support: IE 9 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Behavior in IE 9 is more subtle than in newer versions & it passes
		// some versions of this test; make sure not to make it pass there!
		reliableTrDimensions: function() {
			var table, tr, trChild, trStyle;
			if ( reliableTrDimensionsVal == null ) {
				table = document.createElement( "table" );
				tr = document.createElement( "tr" );
				trChild = document.createElement( "div" );

				table.style.cssText = "position:absolute;left:-11111px";
				tr.style.height = "1px";
				trChild.style.height = "9px";

				documentElement
					.appendChild( table )
					.appendChild( tr )
					.appendChild( trChild );

				trStyle = window.getComputedStyle( tr );
				reliableTrDimensionsVal = parseInt( trStyle.height ) > 3;

				documentElement.removeChild( table );
			}
			return reliableTrDimensionsVal;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,

		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

	computed = computed || getStyles( elem );

	// getPropertyValue is needed for:
	//   .css('filter') (IE 9 only, #12537)
	//   .css('--customProperty) (#3144)
	if ( computed ) {
		ret = computed.getPropertyValue( name ) || computed[ name ];

		if ( ret === "" && !isAttached( elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// https://drafts.csswg.org/cssom/#resolved-values
		if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE <=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style,
	vendorProps = {};

// Return a vendor-prefixed property or undefined
function vendorPropName( name ) {

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
function finalPropName( name ) {
	var final = jQuery.cssProps[ name ] || vendorProps[ name ];

	if ( final ) {
		return final;
	}
	if ( name in emptyStyle ) {
		return name;
	}
	return vendorProps[ name ] = vendorPropName( name ) || name;
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rcustomProp = /^--/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	};

function setPositiveNumber( _elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
	var i = dimension === "width" ? 1 : 0,
		extra = 0,
		delta = 0;

	// Adjustment may not be necessary
	if ( box === ( isBorderBox ? "border" : "content" ) ) {
		return 0;
	}

	for ( ; i < 4; i += 2 ) {

		// Both box models exclude margin
		if ( box === "margin" ) {
			delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
		}

		// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
		if ( !isBorderBox ) {

			// Add padding
			delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// For "border" or "margin", add border
			if ( box !== "padding" ) {
				delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );

			// But still keep track of it otherwise
			} else {
				extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}

		// If we get here with a border-box (content + padding + border), we're seeking "content" or
		// "padding" or "margin"
		} else {

			// For "content", subtract padding
			if ( box === "content" ) {
				delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// For "content" or "padding", subtract border
			if ( box !== "margin" ) {
				delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	// Account for positive content-box scroll gutter when requested by providing computedVal
	if ( !isBorderBox && computedVal >= 0 ) {

		// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
		// Assuming integer scroll gutter, subtract the rest and round down
		delta += Math.max( 0, Math.ceil(
			elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
			computedVal -
			delta -
			extra -
			0.5

		// If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
		// Use an explicit zero to avoid NaN (gh-3964)
		) ) || 0;
	}

	return delta;
}

function getWidthOrHeight( elem, dimension, extra ) {

	// Start with computed style
	var styles = getStyles( elem ),

		// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
		// Fake content-box until we know it's needed to know the true value.
		boxSizingNeeded = !support.boxSizingReliable() || extra,
		isBorderBox = boxSizingNeeded &&
			jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
		valueIsBorderBox = isBorderBox,

		val = curCSS( elem, dimension, styles ),
		offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );

	// Support: Firefox <=54
	// Return a confounding non-pixel value or feign ignorance, as appropriate.
	if ( rnumnonpx.test( val ) ) {
		if ( !extra ) {
			return val;
		}
		val = "auto";
	}


	// Support: IE 9 - 11 only
	// Use offsetWidth/offsetHeight for when box sizing is unreliable.
	// In those cases, the computed value can be trusted to be border-box.
	if ( ( !support.boxSizingReliable() && isBorderBox ||

		// Support: IE 10 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Interestingly, in some cases IE 9 doesn't suffer from this issue.
		!support.reliableTrDimensions() && nodeName( elem, "tr" ) ||

		// Fall back to offsetWidth/offsetHeight when value is "auto"
		// This happens for inline elements with no explicit setting (gh-3571)
		val === "auto" ||

		// Support: Android <=4.1 - 4.3 only
		// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
		!parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&

		// Make sure the element is visible & connected
		elem.getClientRects().length ) {

		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

		// Where available, offsetWidth/offsetHeight approximate border box dimensions.
		// Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
		// retrieved value as a content box dimension.
		valueIsBorderBox = offsetProp in elem;
		if ( valueIsBorderBox ) {
			val = elem[ offsetProp ];
		}
	}

	// Normalize "" and auto
	val = parseFloat( val ) || 0;

	// Adjust for the element's box model
	return ( val +
		boxModelAdjustment(
			elem,
			dimension,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles,

			// Provide the current computed size to request scroll gutter calculation (gh-3589)
			val
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"gridArea": true,
		"gridColumn": true,
		"gridColumnEnd": true,
		"gridColumnStart": true,
		"gridRow": true,
		"gridRowEnd": true,
		"gridRowStart": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name ),
			style = elem.style;

		// Make sure that we're working with the right name. We don't
		// want to query the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (#7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug #9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (#7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			// The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
			// "px" to a few hardcoded values.
			if ( type === "number" && !isCustomProp ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// background-* props affect original clone's values
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				if ( isCustomProp ) {
					style.setProperty( name, value );
				} else {
					style[ name ] = value;
				}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name );

		// Make sure that we're working with the right name. We don't
		// want to modify the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}

		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( _i, dimension ) {
	jQuery.cssHooks[ dimension ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
						swap( elem, cssShow, function() {
							return getWidthOrHeight( elem, dimension, extra );
						} ) :
						getWidthOrHeight( elem, dimension, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = getStyles( elem ),

				// Only read styles.position if the test has a chance to fail
				// to avoid forcing a reflow.
				scrollboxSizeBuggy = !support.scrollboxSize() &&
					styles.position === "absolute",

				// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
				boxSizingNeeded = scrollboxSizeBuggy || extra,
				isBorderBox = boxSizingNeeded &&
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra ?
					boxModelAdjustment(
						elem,
						dimension,
						extra,
						isBorderBox,
						styles
					) :
					0;

			// Account for unreliable border-box dimensions by comparing offset* to computed and
			// faking a content-box to get border and padding (gh-3699)
			if ( isBorderBox && scrollboxSizeBuggy ) {
				subtract -= Math.ceil(
					elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
					parseFloat( styles[ dimension ] ) -
					boxModelAdjustment( elem, dimension, "border", false, styles ) -
					0.5
				);
			}

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ dimension ] = value;
				value = jQuery.css( elem, dimension );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
				) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( prefix !== "margin" ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( Array.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 && (
					jQuery.cssHooks[ tween.prop ] ||
					tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, inProgress,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

function schedule() {
	if ( inProgress ) {
		if ( document.hidden === false && window.requestAnimationFrame ) {
			window.requestAnimationFrame( schedule );
		} else {
			window.setTimeout( schedule, jQuery.fx.interval );
		}

		jQuery.fx.tick();
	}
}

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = Date.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
		isBox = "width" in props || "height" in props,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHiddenWithinTree( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Queue-skipping animations hijack the fx hooks
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Detect show/hide animations
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.test( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// Pretend to be hidden if this is a "show" and
				// there is still data from a stopped show/hide
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;

				// Ignore all other no-op show/hide data
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
		}
	}

	// Bail out if this is a no-op like .hide().hide()
	propTween = !jQuery.isEmptyObject( props );
	if ( !propTween && jQuery.isEmptyObject( orig ) ) {
		return;
	}

	// Restrict "overflow" and "display" styles during box animations
	if ( isBox && elem.nodeType === 1 ) {

		// Support: IE <=9 - 11, Edge 12 - 15
		// Record all 3 overflow attributes because IE does not infer the shorthand
		// from identically-valued overflowX and overflowY and Edge just mirrors
		// the overflowX value there.
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Identify a display type, preferring old show/hide data over the CSS cascade
		restoreDisplay = dataShow && dataShow.display;
		if ( restoreDisplay == null ) {
			restoreDisplay = dataPriv.get( elem, "display" );
		}
		display = jQuery.css( elem, "display" );
		if ( display === "none" ) {
			if ( restoreDisplay ) {
				display = restoreDisplay;
			} else {

				// Get nonempty value(s) by temporarily forcing visibility
				showHide( [ elem ], true );
				restoreDisplay = elem.style.display || restoreDisplay;
				display = jQuery.css( elem, "display" );
				showHide( [ elem ] );
			}
		}

		// Animate inline elements as inline-block
		if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
			if ( jQuery.css( elem, "float" ) === "none" ) {

				// Restore the original display value at the end of pure show/hide animations
				if ( !propTween ) {
					anim.done( function() {
						style.display = restoreDisplay;
					} );
					if ( restoreDisplay == null ) {
						display = style.display;
						restoreDisplay = display === "none" ? "" : display;
					}
				}
				style.display = "inline-block";
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// Implement show/hide animations
	propTween = false;
	for ( prop in orig ) {

		// General show/hide setup for this element animation
		if ( !propTween ) {
			if ( dataShow ) {
				if ( "hidden" in dataShow ) {
					hidden = dataShow.hidden;
				}
			} else {
				dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
			}

			// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
			if ( toggle ) {
				dataShow.hidden = !hidden;
			}

			// Show elements before animating them
			if ( hidden ) {
				showHide( [ elem ], true );
			}

			/* eslint-disable no-loop-func */

			anim.done( function() {

			/* eslint-enable no-loop-func */

				// The final step of a "hide" animation is actually hiding the element
				if ( !hidden ) {
					showHide( [ elem ] );
				}
				dataPriv.remove( elem, "fxshow" );
				for ( prop in orig ) {
					jQuery.style( elem, prop, orig[ prop ] );
				}
			} );
		}

		// Per-property setup
		propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
		if ( !( prop in dataShow ) ) {
			dataShow[ prop ] = propTween.start;
			if ( hidden ) {
				propTween.end = propTween.start;
				propTween.start = 0;
			}
		}
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( Array.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3 only
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			// If there's more to do, yield
			if ( percent < 1 && length ) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if ( !length ) {
				deferred.notifyWith( elem, [ animation, 1, 0 ] );
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith( elem, [ animation ] );
			return false;
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					result.stop.bind( result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	// Attach callbacks from options
	animation
		.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	return animation;
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnothtmlwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !isFunction( easing ) && easing
	};

	// Go to the end state if fx are off
	if ( jQuery.fx.off ) {
		opt.duration = 0;

	} else {
		if ( typeof opt.duration !== "number" ) {
			if ( opt.duration in jQuery.fx.speeds ) {
				opt.duration = jQuery.fx.speeds[ opt.duration ];

			} else {
				opt.duration = jQuery.fx.speeds._default;
			}
		}
	}

	// Normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};
			doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = Date.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Run the timer and safely remove it when done (allowing for external removal)
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	jQuery.fx.start();
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( inProgress ) {
		return;
	}

	inProgress = true;
	schedule();
};

jQuery.fx.stop = function() {
	inProgress = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: Android <=4.3 only
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE <=11 only
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: IE <=11 only
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// Attribute hooks are determined by the lowercase version
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name,
			i = 0,

			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value && value.match( rnothtmlwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle,
			lowercaseName = name.toLowerCase();

		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ lowercaseName ];
			attrHandle[ lowercaseName ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				lowercaseName :
				null;
			attrHandle[ lowercaseName ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// Support: IE <=9 - 11 only
				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				if ( tabindex ) {
					return parseInt( tabindex, 10 );
				}

				if (
					rfocusable.test( elem.nodeName ) ||
					rclickable.test( elem.nodeName ) &&
					elem.href
				) {
					return 0;
				}

				return -1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




	// Strip and collapse whitespace according to HTML spec
	// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
	function stripAndCollapse( value ) {
		var tokens = value.match( rnothtmlwhite ) || [];
		return tokens.join( " " );
	}


function getClass( elem ) {
	return elem.getAttribute && elem.getAttribute( "class" ) || "";
}

function classesToArray( value ) {
	if ( Array.isArray( value ) ) {
		return value;
	}
	if ( typeof value === "string" ) {
		return value.match( rnothtmlwhite ) || [];
	}
	return [];
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		classes = classesToArray( value );

		if ( classes.length ) {
			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		classes = classesToArray( value );

		if ( classes.length ) {
			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );

				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {

						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isValidValue = type === "string" || Array.isArray( value );

		if ( typeof stateVal === "boolean" && isValidValue ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		if ( isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		return this.each( function() {
			var className, i, self, classNames;

			if ( isValidValue ) {

				// Toggle individual class names
				i = 0;
				self = jQuery( this );
				classNames = classesToArray( value );

				while ( ( className = classNames[ i++ ] ) ) {

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
						"" :
						dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
					return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, valueIsFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				// Handle most common string cases
				if ( typeof ret === "string" ) {
					return ret.replace( rreturn, "" );
				}

				// Handle cases where value is null/undef or number
				return ret == null ? "" : ret;
			}

			return;
		}

		valueIsFunction = isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( valueIsFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( Array.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE <=10 - 11 only
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option, i,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one",
					values = one ? null : [],
					max = one ? index + 1 : options.length;

				if ( index < 0 ) {
					i = max;

				} else {
					i = one ? index : 0;
				}

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// Support: IE <=9 only
					// IE8-9 doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							!option.disabled &&
							( !option.parentNode.disabled ||
								!nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					/* eslint-disable no-cond-assign */

					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
					) {
						optionSet = true;
					}

					/* eslint-enable no-cond-assign */
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( Array.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion


support.focusin = "onfocusin" in window;


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	stopPropagationCallback = function( e ) {
		e.stopPropagation();
	};

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = lastElement = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
			lastElement = cur;
			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = (
					dataPriv.get( cur, "events" ) || Object.create( null )
				)[ event.type ] &&
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &&
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name as the event.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;

					if ( event.isPropagationStopped() ) {
						lastElement.addEventListener( type, stopPropagationCallback );
					}

					elem[ type ]();

					if ( event.isPropagationStopped() ) {
						lastElement.removeEventListener( type, stopPropagationCallback );
					}

					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {

				// Handle: regular nodes (via `this.ownerDocument`), window
				// (via `this.document`) & document (via `this`).
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					dataPriv.remove( doc, fix );

				} else {
					dataPriv.access( doc, fix, attaches );
				}
			}
		};
	} );
}
var location = window.location;

var nonce = { guid: Date.now() };

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE 9 - 11 only
	// IE throws on parseFromString with invalid input.
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {
		xml = undefined;
	}

	if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + data );
	}
	return xml;
};


var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( Array.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && toType( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, valueOrFunction ) {

			// If value is a function, invoke it and use its return value
			var value = isFunction( valueOrFunction ) ?
				valueOrFunction() :
				valueOrFunction;

			s[ s.length ] = encodeURIComponent( key ) + "=" +
				encodeURIComponent( value == null ? "" : value );
		};

	if ( a == null ) {
		return "";
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} )
		.filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} )
		.map( function( _i, elem ) {
			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


var
	r20 = /%20/g,
	rhash = /#.*$/,
	rantiCache = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );
	originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];

		if ( isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",

		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": JSON.parse,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// Request state (becomes false upon send and true upon completion)
			completed,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// uncached part of the url
			uncached,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
					jQuery( callbackContext ) :
					jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( completed ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
									( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
										.concat( match[ 2 ] );
							}
						}
						match = responseHeaders[ key.toLowerCase() + " " ];
					}
					return match == null ? null : match.join( ", " );
				},

				// Raw string
				getAllResponseHeaders: function() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( completed == null ) {
						name = requestHeadersNames[ name.toLowerCase() ] =
							requestHeadersNames[ name.toLowerCase() ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( completed == null ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( completed ) {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for ( code in map ) {
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR );

		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE <=8 - 11, Edge 12 - 15
			// IE throws exception on accessing the href property if url is malformed,
			// e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE <=8 - 11 only
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( completed ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		// Remove hash to simplify url manipulation
		cacheURL = s.url.replace( rhash, "" );

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// Remember the hash so we can put it back
			uncached = s.url.slice( cacheURL.length );

			// If data is available and should be processed, append data to url
			if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
				cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;

				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add or update anti-cache param if needed
			if ( s.cache === false ) {
				cacheURL = cacheURL.replace( rantiCache, "$1" );
				uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) +
					uncached;
			}

			// Put hash and anti-cache on the URL that will be requested (gh-1732)
			s.url = cacheURL + uncached;

		// Change '%20' to '+' if this is encoded form body content (gh-2658)
		} else if ( s.data && s.processData &&
			( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
			s.data = s.data.replace( r20, "+" );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		completeDeferred.add( s.complete );
		jqXHR.done( s.success );
		jqXHR.fail( s.error );

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( completed ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				completed = false;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Rethrow post-completion exceptions
				if ( completed ) {
					throw e;
				}

				// Propagate others as results
				done( -1, e );
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Ignore repeat invocations
			if ( completed ) {
				return;
			}

			completed = true;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Use a noop converter for missing script
			if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) {
				s.converters[ "text script" ] = function() {};
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( _i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );

jQuery.ajaxPrefilter( function( s ) {
	var i;
	for ( i in s.headers ) {
		if ( i.toLowerCase() === "content-type" ) {
			s.contentType = s.headers[ i ] || "";
		}
	}
} );


jQuery._evalUrl = function( url, options, doc ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (#11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,

		// Only evaluate the response if it is successful (gh-4126)
		// dataFilter is not invoked for failure responses, so using it instead
		// of the default converter is kludgy but it works.
		converters: {
			"text script": function() {}
		},
		dataFilter: function( response ) {
			jQuery.globalEval( response, options, doc );
		}
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( this[ 0 ] ) {
			if ( isFunction( html ) ) {
				html = html.call( this[ 0 ] );
			}

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var htmlIsFunction = isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function( selector ) {
		this.parent( selector ).not( "body" ).each( function() {
			jQuery( this ).replaceWith( this.childNodes );
		} );
		return this;
	}
} );


jQuery.expr.pseudos.hidden = function( elem ) {
	return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
	return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};




jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE <=9 only
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType && xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.ontimeout =
									xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE <=9 only
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see #8605, #14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE <=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );

				// Support: IE 9 only
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent && options.data || null );
				} catch ( e ) {

					// #14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
	if ( s.crossDomain ) {
		s.contents.script = false;
	}
} );

// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain or forced-by-attrs requests
	if ( s.crossDomain || s.scriptAttrs ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" )
					.attr( s.scriptAttrs || {} )
					.prop( { charset: s.scriptCharset, src: s.url } )
					.on( "load error", callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					} );

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
	var body = document.implementation.createHTMLDocument( "" ).body;
	body.innerHTML = "<form></form><form></form>";
	return body.childNodes.length === 2;
} )();


// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( typeof data !== "string" ) {
		return [];
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}

	var base, parsed, scripts;

	if ( !context ) {

		// Stop scripts or inline event handlers from being executed immediately
		// by using document.implementation
		if ( support.createHTMLDocument ) {
			context = document.implementation.createHTMLDocument( "" );

			// Set the base href for the created document
			// so any parsed elements with URLs
			// are based on the document's URL (gh-2965)
			base = context.createElement( "base" );
			base.href = document.location.href;
			context.head.appendChild( base );
		} else {
			context = document;
		}
	}

	parsed = rsingleTag.exec( data );
	scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = stripAndCollapse( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




jQuery.expr.pseudos.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			if ( typeof props.top === "number" ) {
				props.top += "px";
			}
			if ( typeof props.left === "number" ) {
				props.left += "px";
			}
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {

	// offset() relates an element's border box to the document origin
	offset: function( options ) {

		// Preserve chaining for setter
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var rect, win,
			elem = this[ 0 ];

		if ( !elem ) {
			return;
		}

		// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
		// Support: IE <=11 only
		// Running getBoundingClientRect on a
		// disconnected node in IE throws an error
		if ( !elem.getClientRects().length ) {
			return { top: 0, left: 0 };
		}

		// Get document-relative position by adding viewport scroll to viewport-relative gBCR
		rect = elem.getBoundingClientRect();
		win = elem.ownerDocument.defaultView;
		return {
			top: rect.top + win.pageYOffset,
			left: rect.left + win.pageXOffset
		};
	},

	// position() relates an element's margin box to its offset parent's padding box
	// This corresponds to the behavior of CSS absolute positioning
	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset, doc,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// position:fixed elements are offset from the viewport, which itself always has zero offset
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume position:fixed implies availability of getBoundingClientRect
			offset = elem.getBoundingClientRect();

		} else {
			offset = this.offset();

			// Account for the *real* offset parent, which can be the document or its root element
			// when a statically positioned element is identified
			doc = elem.ownerDocument;
			offsetParent = elem.offsetParent || doc.documentElement;
			while ( offsetParent &&
				( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
				jQuery.css( offsetParent, "position" ) === "static" ) {

				offsetParent = offsetParent.parentNode;
			}
			if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {

				// Incorporate borders into its offset, since they are outside its content origin
				parentOffset = jQuery( offsetParent ).offset();
				parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
				parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
			}
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {

			// Coalesce documents and windows
			var win;
			if ( isWindow( elem ) ) {
				win = elem;
			} else if ( elem.nodeType === 9 ) {
				win = elem.defaultView;
			}

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( _i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
		function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( isWindow( elem ) ) {

					// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
					return funcName.indexOf( "outer" ) === 0 ?
						elem[ "inner" + name ] :
						elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable );
		};
	} );
} );


jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( _i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );

jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( _i, name ) {

		// Handle event binding
		jQuery.fn[ name ] = function( data, fn ) {
			return arguments.length > 0 ?
				this.on( name, null, data, fn ) :
				this.trigger( name );
		};
	} );




// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function( fn, context ) {
	var tmp, args, proxy;

	if ( typeof context === "string" ) {
		tmp = fn[ context ];
		context = fn;
		fn = tmp;
	}

	// Quick check to determine if target is callable, in the spec
	// this throws a TypeError, but we will just return undefined.
	if ( !isFunction( fn ) ) {
		return undefined;
	}

	// Simulated bind
	args = slice.call( arguments, 2 );
	proxy = function() {
		return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
	};

	// Set the guid of unique handler to the same of original handler, so it can be removed
	proxy.guid = fn.guid = fn.guid || jQuery.guid++;

	return proxy;
};

jQuery.holdReady = function( hold ) {
	if ( hold ) {
		jQuery.readyWait++;
	} else {
		jQuery.ready( true );
	}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
jQuery.isFunction = isFunction;
jQuery.isWindow = isWindow;
jQuery.camelCase = camelCase;
jQuery.type = toType;

jQuery.now = Date.now;

jQuery.isNumeric = function( obj ) {

	// As of jQuery 3.0, isNumeric is limited to
	// strings and numbers (primitives or objects)
	// that can be coerced to finite numbers (gh-2662)
	var type = jQuery.type( obj );
	return ( type === "number" || type === "string" ) &&

		// parseFloat NaNs numeric-cast false positives ("")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		!isNaN( obj - parseFloat( obj ) );
};

jQuery.trim = function( text ) {
	return text == null ?
		"" :
		( text + "" ).replace( rtrim, "" );
};



// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" && define.amd ) {
	define( "jquery", [], function() {
		return jQuery;
	} );
}




var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === "undefined" ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );
/*!
 * jQuery Migrate - v3.1.0 - 2019-06-08
 * Copyright OpenJS Foundation and other contributors
 */
;( function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], function ( jQuery ) {
			return factory( jQuery, window );
		} );
	} else if ( typeof module === "object" && module.exports ) {

		// Node/CommonJS
		// eslint-disable-next-line no-undef
		module.exports = factory( require( "jquery" ), window );
	} else {

		// Browser globals
		factory( jQuery, window );
	}
} )( function( jQuery, window ) {
"use strict";


jQuery.migrateVersion = "3.1.0";

/* exported jQueryVersionSince, compareVersions */

// Returns 0 if v1 == v2, -1 if v1 < v2, 1 if v1 > v2
function compareVersions( v1, v2 ) {
	var rVersionParts = /^(\d+)\.(\d+)\.(\d+)/,
		v1p = rVersionParts.exec( v1 ) || [ ],
		v2p = rVersionParts.exec( v2 ) || [ ];

	for ( var i = 1; i <= 3; i++ ) {
		if ( +v1p[ i ] > +v2p[ i ] ) {
			return 1;
		}
		if ( +v1p[ i ] < +v2p[ i ] ) {
			return -1;
		}
	}
	return 0;
}

function jQueryVersionSince( version ) {
	return compareVersions( jQuery.fn.jquery, version ) >= 0;
}

/* exported migrateWarn, migrateWarnFunc, migrateWarnProp */

( function() {

  // Hide our shame!
  jQuery.migrateMute = true;

	// Support: IE9 only
	// IE9 only creates console object when dev tools are first opened
	// IE9 console is a host object, callable but doesn't have .apply()
	if ( !window.console || !window.console.log ) {
		return;
	}

	// Need jQuery 3.0.0+ and no older Migrate loaded
	if ( !jQuery || !jQueryVersionSince( "3.0.0" ) ) {
		window.console.log( "JQMIGRATE: jQuery 3.0.0+ REQUIRED" );
	}
	if ( jQuery.migrateWarnings ) {
		window.console.log( "JQMIGRATE: Migrate plugin loaded multiple times" );
	}

	// Show a message on the console so devs know we're active
	window.console.log( "JQMIGRATE: Migrate is installed" +
		( jQuery.migrateMute ? "" : " with logging active" ) +
		", version " + jQuery.migrateVersion );

} )();

var warnedAbout = {};

// List of warnings already given; public read only
jQuery.migrateWarnings = [];

// Set to false to disable traces that appear with warnings
if ( jQuery.migrateTrace === undefined ) {
	jQuery.migrateTrace = true;
}

// Forget any warnings we've already given; public
jQuery.migrateReset = function() {
	warnedAbout = {};
	jQuery.migrateWarnings.length = 0;
};

function migrateWarn( msg ) {
	var console = window.console;
	if ( !warnedAbout[ msg ] ) {
		warnedAbout[ msg ] = true;
		jQuery.migrateWarnings.push( msg );
		if ( console && console.warn && !jQuery.migrateMute ) {
			console.warn( "JQMIGRATE: " + msg );
			if ( jQuery.migrateTrace && console.trace ) {
				console.trace();
			}
		}
	}
}

function migrateWarnProp( obj, prop, value, msg ) {
	Object.defineProperty( obj, prop, {
		configurable: true,
		enumerable: true,
		get: function() {
			migrateWarn( msg );
			return value;
		},
		set: function( newValue ) {
			migrateWarn( msg );
			value = newValue;
		}
	} );
}

function migrateWarnFunc( obj, prop, newFunc, msg ) {
	obj[ prop ] = function() {
		migrateWarn( msg );
		return newFunc.apply( this, arguments );
	};
}

if ( window.document.compatMode === "BackCompat" ) {

	// JQuery has never supported or tested Quirks Mode
	migrateWarn( "jQuery is not compatible with Quirks Mode" );
}


var oldInit = jQuery.fn.init,
	oldIsNumeric = jQuery.isNumeric,
	oldFind = jQuery.find,
	rattrHashTest = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,
	rattrHashGlob = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g;

jQuery.fn.init = function( arg1 ) {
	var args = Array.prototype.slice.call( arguments );

	if ( typeof arg1 === "string" && arg1 === "#" ) {

		// JQuery( "#" ) is a bogus ID selector, but it returned an empty set before jQuery 3.0
		migrateWarn( "jQuery( '#' ) is not a valid selector" );
		args[ 0 ] = [];
	}

	return oldInit.apply( this, args );
};
jQuery.fn.init.prototype = jQuery.fn;

jQuery.find = function( selector ) {
	var args = Array.prototype.slice.call( arguments );

	// Support: PhantomJS 1.x
	// String#match fails to match when used with a //g RegExp, only on some strings
	if ( typeof selector === "string" && rattrHashTest.test( selector ) ) {

		// First see if qS thinks it's a valid selector, if so avoid a false positive
		try {
			window.document.querySelector( selector );
		} catch ( err1 ) {

			// Didn't *look* valid to qSA, warn and try quoting what we think is the value
			selector = selector.replace( rattrHashGlob, function( _, attr, op, value ) {
				return "[" + attr + op + "\"" + value + "\"]";
			} );

			// If the regexp *may* have created an invalid selector, don't update it
			// Note that there may be false alarms if selector uses jQuery extensions
			try {
				window.document.querySelector( selector );
				migrateWarn( "Attribute selector with '#' must be quoted: " + args[ 0 ] );
				args[ 0 ] = selector;
			} catch ( err2 ) {
				migrateWarn( "Attribute selector with '#' was not fixed: " + args[ 0 ] );
			}
		}
	}

	return oldFind.apply( this, args );
};

// Copy properties attached to original jQuery.find method (e.g. .attr, .isXML)
var findProp;
for ( findProp in oldFind ) {
	if ( Object.prototype.hasOwnProperty.call( oldFind, findProp ) ) {
		jQuery.find[ findProp ] = oldFind[ findProp ];
	}
}

// The number of elements contained in the matched element set
jQuery.fn.size = function() {
	migrateWarn( "jQuery.fn.size() is deprecated and removed; use the .length property" );
	return this.length;
};

jQuery.parseJSON = function() {
	migrateWarn( "jQuery.parseJSON is deprecated; use JSON.parse" );
	return JSON.parse.apply( null, arguments );
};

// Begin additions fromjQuery Migrate 1->2
var matched, browser;

jQuery.uaMatch = function( ua ) {
	ua = ua.toLowerCase();

	var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
		/(msie) ([\w.]+)/.exec( ua ) ||
		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
		[];

	return {
		browser: match[ 1 ] || "",
		version: match[ 2 ] || "0"
	};
};

if ( !jQuery.browser ) {
	matched = jQuery.uaMatch( navigator.userAgent );
	browser = {};

	if ( matched.browser ) {
		browser[ matched.browser ] = true;
		browser.version = matched.version;
	}

	// Chrome is Webkit, but Webkit is also Safari.
	if ( browser.chrome ) {
		browser.webkit = true;
	} else if ( browser.webkit ) {
		browser.safari = true;
	}

	jQuery.browser = browser;
}
// End additions fromjQuery Migrate 1->2

jQuery.isNumeric = function( val ) {

	// The jQuery 2.2.3 implementation of isNumeric
	function isNumeric2( obj ) {
		var realStringObj = obj && obj.toString();
		return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
	}

	var newValue = oldIsNumeric( val ),
		oldValue = isNumeric2( val );

	if ( newValue !== oldValue ) {
		migrateWarn( "jQuery.isNumeric() should not be called on constructed objects" );
	}

	return oldValue;
};

if ( jQueryVersionSince( "3.3.0" ) ) {
	migrateWarnFunc( jQuery, "isWindow",
		function( obj ) {
			return obj != null && obj === obj.window;
		},
		"jQuery.isWindow() is deprecated"
	);
}

migrateWarnFunc( jQuery, "holdReady", jQuery.holdReady,
	"jQuery.holdReady is deprecated" );

migrateWarnFunc( jQuery, "unique", jQuery.uniqueSort,
	"jQuery.unique is deprecated; use jQuery.uniqueSort" );

// Now jQuery.expr.pseudos is the standard incantation
migrateWarnProp( jQuery.expr, "filters", jQuery.expr.pseudos,
	"jQuery.expr.filters is deprecated; use jQuery.expr.pseudos" );
migrateWarnProp( jQuery.expr, ":", jQuery.expr.pseudos,
	"jQuery.expr[':'] is deprecated; use jQuery.expr.pseudos" );

// Prior to jQuery 3.2 there were internal refs so we don't warn there
if ( jQueryVersionSince( "3.2.0" ) ) {
	migrateWarnFunc( jQuery, "nodeName", jQuery.nodeName,
	"jQuery.nodeName is deprecated" );
}


var oldAjax = jQuery.ajax;

jQuery.ajax = function( ) {
	var jQXHR = oldAjax.apply( this, arguments );

	// Be sure we got a jQXHR (e.g., not sync)
	if ( jQXHR.promise ) {
		migrateWarnFunc( jQXHR, "success", jQXHR.done,
			"jQXHR.success is deprecated and removed" );
		migrateWarnFunc( jQXHR, "error", jQXHR.fail,
			"jQXHR.error is deprecated and removed" );
		migrateWarnFunc( jQXHR, "complete", jQXHR.always,
			"jQXHR.complete is deprecated and removed" );
	}

	return jQXHR;
};


var oldRemoveAttr = jQuery.fn.removeAttr,
	oldToggleClass = jQuery.fn.toggleClass,
	rmatchNonSpace = /\S+/g;

jQuery.fn.removeAttr = function( name ) {
	var self = this;

	jQuery.each( name.match( rmatchNonSpace ), function( _i, attr ) {
		if ( jQuery.expr.match.bool.test( attr ) ) {
			migrateWarn( "jQuery.fn.removeAttr no longer sets boolean properties: " + attr );
			self.prop( attr, false );
		}
	} );

	return oldRemoveAttr.apply( this, arguments );
};

jQuery.fn.toggleClass = function( state ) {

	// Only deprecating no-args or single boolean arg
	if ( state !== undefined && typeof state !== "boolean" ) {
		return oldToggleClass.apply( this, arguments );
	}

	migrateWarn( "jQuery.fn.toggleClass( boolean ) is deprecated" );

	// Toggle entire class name of each element
	return this.each( function() {
		var className = this.getAttribute && this.getAttribute( "class" ) || "";

		if ( className ) {
			jQuery.data( this, "__className__", className );
		}

		// If the element has a class name or if we're passed `false`,
		// then remove the whole classname (if there was one, the above saved it).
		// Otherwise bring back whatever was previously saved (if anything),
		// falling back to the empty string if nothing was stored.
		if ( this.setAttribute ) {
			this.setAttribute( "class",
				className || state === false ?
				"" :
				jQuery.data( this, "__className__" ) || ""
			);
		}
	} );
};


var internalSwapCall = false;

// If this version of jQuery has .swap(), don't false-alarm on internal uses
if ( jQuery.swap ) {
	jQuery.each( [ "height", "width", "reliableMarginRight" ], function( _, name ) {
		var oldHook = jQuery.cssHooks[ name ] && jQuery.cssHooks[ name ].get;

		if ( oldHook ) {
			jQuery.cssHooks[ name ].get = function() {
				var ret;

				internalSwapCall = true;
				ret = oldHook.apply( this, arguments );
				internalSwapCall = false;
				return ret;
			};
		}
	} );
}

jQuery.swap = function( elem, options, callback, args ) {
	var ret, name,
		old = {};

	if ( !internalSwapCall ) {
		migrateWarn( "jQuery.swap() is undocumented and deprecated" );
	}

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.apply( elem, args || [] );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};

var oldData = jQuery.data;

jQuery.data = function( elem, name, value ) {
	var curData;

	// Name can be an object, and each entry in the object is meant to be set as data
	if ( name && typeof name === "object" && arguments.length === 2 ) {
		curData = jQuery.hasData( elem ) && oldData.call( this, elem );
		var sameKeys = {};
		for ( var key in name ) {
			if ( key !== jQuery.camelCase( key ) ) {
				migrateWarn( "jQuery.data() always sets/gets camelCased names: " + key );
				curData[ key ] = name[ key ];
			} else {
				sameKeys[ key ] = name[ key ];
			}
		}

		oldData.call( this, elem, sameKeys );

		return name;
	}

	// If the name is transformed, look for the un-transformed name in the data object
	if ( name && typeof name === "string" && name !== jQuery.camelCase( name ) ) {
		curData = jQuery.hasData( elem ) && oldData.call( this, elem );
		if ( curData && name in curData ) {
			migrateWarn( "jQuery.data() always sets/gets camelCased names: " + name );
			if ( arguments.length > 2 ) {
				curData[ name ] = value;
			}
			return curData[ name ];
		}
	}

	return oldData.apply( this, arguments );
};

var oldTweenRun = jQuery.Tween.prototype.run;
var linearEasing = function( pct ) {
		return pct;
	};

jQuery.Tween.prototype.run = function( ) {
	if ( jQuery.easing[ this.easing ].length > 1 ) {
		migrateWarn(
			"'jQuery.easing." + this.easing.toString() + "' should use only one argument"
		);

		jQuery.easing[ this.easing ] = linearEasing;
	}

	oldTweenRun.apply( this, arguments );
};

var intervalValue = jQuery.fx.interval || 13,
	intervalMsg = "jQuery.fx.interval is deprecated";

// Support: IE9, Android <=4.4
// Avoid false positives on browsers that lack rAF
// Don't warn if document is hidden, jQuery uses setTimeout (#292)
if ( window.requestAnimationFrame ) {
	Object.defineProperty( jQuery.fx, "interval", {
		configurable: true,
		enumerable: true,
		get: function() {
			if ( !window.document.hidden ) {
				migrateWarn( intervalMsg );
			}
			return intervalValue;
		},
		set: function( newValue ) {
			migrateWarn( intervalMsg );
			intervalValue = newValue;
		}
	} );
}

var oldLoad = jQuery.fn.load,
	oldEventAdd = jQuery.event.add,
	originalFix = jQuery.event.fix;

jQuery.event.props = [];
jQuery.event.fixHooks = {};

migrateWarnProp( jQuery.event.props, "concat", jQuery.event.props.concat,
	"jQuery.event.props.concat() is deprecated and removed" );

jQuery.event.fix = function( originalEvent ) {
	var event,
		type = originalEvent.type,
		fixHook = this.fixHooks[ type ],
		props = jQuery.event.props;

	if ( props.length ) {
		migrateWarn( "jQuery.event.props are deprecated and removed: " + props.join() );
		while ( props.length ) {
			jQuery.event.addProp( props.pop() );
		}
	}

	if ( fixHook && !fixHook._migrated_ ) {
		fixHook._migrated_ = true;
		migrateWarn( "jQuery.event.fixHooks are deprecated and removed: " + type );
		if ( ( props = fixHook.props ) && props.length ) {
			while ( props.length ) {
				jQuery.event.addProp( props.pop() );
			}
		}
	}

	event = originalFix.call( this, originalEvent );

	return fixHook && fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
};

jQuery.event.add = function( elem, types ) {

	// This misses the multiple-types case but that seems awfully rare
	if ( elem === window && types === "load" && window.document.readyState === "complete" ) {
		migrateWarn( "jQuery(window).on('load'...) called after load event occurred" );
	}
	return oldEventAdd.apply( this, arguments );
};

jQuery.each( [ "load", "unload", "error" ], function( _, name ) {

	jQuery.fn[ name ] = function() {
		var args = Array.prototype.slice.call( arguments, 0 );

		// If this is an ajax load() the first arg should be the string URL;
		// technically this could also be the "Anything" arg of the event .load()
		// which just goes to show why this dumb signature has been deprecated!
		// jQuery custom builds that exclude the Ajax module justifiably die here.
		if ( name === "load" && typeof args[ 0 ] === "string" ) {
			return oldLoad.apply( this, args );
		}

		migrateWarn( "jQuery.fn." + name + "() is deprecated" );

		args.splice( 0, 0, name );
		if ( arguments.length ) {
			return this.on.apply( this, args );
		}

		// Use .triggerHandler here because:
		// - load and unload events don't need to bubble, only applied to window or image
		// - error event should not bubble to window, although it does pre-1.7
		// See http://bugs.jquery.com/ticket/11820
		this.triggerHandler.apply( this, args );
		return this;
	};

} );

jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( _i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		migrateWarn( "jQuery.fn." + name + "() event shorthand is deprecated" );
		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};
} );

// Trigger "ready" event only once, on document ready
jQuery( function() {
	jQuery( window.document ).triggerHandler( "ready" );
} );

jQuery.event.special.ready = {
	setup: function() {
		if ( this === window.document ) {
			migrateWarn( "'ready' event is deprecated" );
		}
	}
};

jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		migrateWarn( "jQuery.fn.bind() is deprecated" );
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		migrateWarn( "jQuery.fn.unbind() is deprecated" );
		return this.off( types, null, fn );
	},
	delegate: function( selector, types, data, fn ) {
		migrateWarn( "jQuery.fn.delegate() is deprecated" );
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {
		migrateWarn( "jQuery.fn.undelegate() is deprecated" );
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},
	hover: function( fnOver, fnOut ) {
		migrateWarn( "jQuery.fn.hover() is deprecated" );
		return this.on( "mouseenter", fnOver ).on( "mouseleave", fnOut || fnOver );
	}
} );


var oldOffset = jQuery.fn.offset;

jQuery.fn.offset = function() {
	var docElem,
		elem = this[ 0 ],
		origin = { top: 0, left: 0 };

	if ( !elem || !elem.nodeType ) {
		migrateWarn( "jQuery.fn.offset() requires a valid DOM element" );
		return origin;
	}

	docElem = ( elem.ownerDocument || window.document ).documentElement;
	if ( !jQuery.contains( docElem, elem ) ) {
		migrateWarn( "jQuery.fn.offset() requires an element connected to a document" );
		return origin;
	}

	return oldOffset.apply( this, arguments );
};


var oldParam = jQuery.param;

jQuery.param = function( data, traditional ) {
	var ajaxTraditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;

	if ( traditional === undefined && ajaxTraditional ) {

		migrateWarn( "jQuery.param() no longer uses jQuery.ajaxSettings.traditional" );
		traditional = ajaxTraditional;
	}

	return oldParam.call( this, data, traditional );
};

var oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack;

jQuery.fn.andSelf = function() {
	migrateWarn( "jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()" );
	return oldSelf.apply( this, arguments );
};


var oldDeferred = jQuery.Deferred,
	tuples = [

		// Action, add listener, callbacks, .then handlers, final state
		[ "resolve", "done", jQuery.Callbacks( "once memory" ),
			jQuery.Callbacks( "once memory" ), "resolved" ],
		[ "reject", "fail", jQuery.Callbacks( "once memory" ),
			jQuery.Callbacks( "once memory" ), "rejected" ],
		[ "notify", "progress", jQuery.Callbacks( "memory" ),
			jQuery.Callbacks( "memory" ) ]
	];

jQuery.Deferred = function( func ) {
	var deferred = oldDeferred(),
		promise = deferred.promise();

	deferred.pipe = promise.pipe = function( /* fnDone, fnFail, fnProgress */ ) {
		var fns = arguments;

		migrateWarn( "deferred.pipe() is deprecated" );

		return jQuery.Deferred( function( newDefer ) {
			jQuery.each( tuples, function( i, tuple ) {
				var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];

				// Deferred.done(function() { bind to newDefer or newDefer.resolve })
				// deferred.fail(function() { bind to newDefer or newDefer.reject })
				// deferred.progress(function() { bind to newDefer or newDefer.notify })
				deferred[ tuple[ 1 ] ]( function() {
					var returned = fn && fn.apply( this, arguments );
					if ( returned && jQuery.isFunction( returned.promise ) ) {
						returned.promise()
							.done( newDefer.resolve )
							.fail( newDefer.reject )
							.progress( newDefer.notify );
					} else {
						newDefer[ tuple[ 0 ] + "With" ](
							this === promise ? newDefer.promise() : this,
							fn ? [ returned ] : arguments
						);
					}
				} );
			} );
			fns = null;
		} ).promise();

	};

	if ( func ) {
		func.call( deferred, deferred );
	}

	return deferred;
};

// Preserve handler of uncaught exceptions in promise chains
jQuery.Deferred.exceptionHook = oldDeferred.exceptionHook;

return jQuery;
} );
( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.ui = $.ui || {};

return $.ui.version = "1.13.0";

} );


/*!
 * jQuery UI :data 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.extend( $.expr.pseudos, {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );
} );


/*!
 * jQuery UI Disable Selection 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated
( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );

} );


/*!
 * jQuery UI Focusable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// Selectors
$.ui.focusable = function( element, hasTabindex ) {
	var map, mapName, img, focusableIfVisible, fieldset,
		nodeName = element.nodeName.toLowerCase();

	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" );
		return img.length > 0 && img.is( ":visible" );
	}

	if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
		focusableIfVisible = !element.disabled;

		if ( focusableIfVisible ) {

			// Form controls within a disabled fieldset are disabled.
			// However, controls within the fieldset's legend do not get disabled.
			// Since controls generally aren't placed inside legends, we skip
			// this portion of the check.
			fieldset = $( element ).closest( "fieldset" )[ 0 ];
			if ( fieldset ) {
				focusableIfVisible = !fieldset.disabled;
			}
		}
	} else if ( "a" === nodeName ) {
		focusableIfVisible = element.href || hasTabindex;
	} else {
		focusableIfVisible = hasTabindex;
	}

	return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};

// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
	var visibility = element.css( "visibility" );
	while ( visibility === "inherit" ) {
		element = element.parent();
		visibility = element.css( "visibility" );
	}
	return visibility === "visible";
}

$.extend( $.expr.pseudos, {
	focusable: function( element ) {
		return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
	}
} );

return $.ui.focusable;

} );

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// Support: IE8 Only
// IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
// with a string, so we need to find the proper form.
return $.fn._form = function() {
	return typeof this[ 0 ].form === "string" ? this.closest( "form" ) : $( this[ 0 ].form );
};

} );

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// This file is deprecated
return $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
} );


/*!
 * jQuery UI Keycode 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};

} );


/*!
 * jQuery UI Labels 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: http://api.jqueryui.com/labels/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.labels = function() {
	var ancestor, selector, id, labels, ancestors;

	if ( !this.length ) {
		return this.pushStack( [] );
	}

	// Check control.labels first
	if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
		return this.pushStack( this[ 0 ].labels );
	}

	// Support: IE <= 11, FF <= 37, Android <= 2.3 only
	// Above browsers do not support control.labels. Everything below is to support them
	// as well as document fragments. control.labels does not work on document fragments
	labels = this.eq( 0 ).parents( "label" );

	// Look for the label based on the id
	id = this.attr( "id" );
	if ( id ) {

		// We don't search against the document in case the element
		// is disconnected from the DOM
		ancestor = this.eq( 0 ).parents().last();

		// Get a full set of top level ancestors
		ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );

		// Create a selector for the label based on the id
		selector = "label[for='" + $.escapeSelector( id ) + "']";

		labels = labels.add( ancestors.find( selector ).addBack( selector ) );

	}

	// Return whatever we have found for labels
	return this.pushStack( labels );
};

} );


/*!
 * jQuery UI Support for jQuery core 1.8.x and newer 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 */

//>>label: jQuery 1.8+ Support
//>>group: Core
//>>description: Support version 1.8.x and newer of jQuery core

( function( factory ) {
"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// Support: jQuery 1.9.x or older
// $.expr[ ":" ] is deprecated.
if ( !$.expr.pseudos ) {
	$.expr.pseudos = $.expr[ ":" ];
}

// Support: jQuery 1.11.x or older
// $.unique has been renamed to $.uniqueSort
if ( !$.uniqueSort ) {
	$.uniqueSort = $.unique;
}

// Support: jQuery 2.2.x or older.
// This method has been defined in jQuery 3.0.0.
// Code from https://github.com/jquery/jquery/blob/e539bac79e666bba95bba86d690b4e609dca2286/src/selector/escapeSelector.js
if ( !$.escapeSelector ) {

	// CSS string/identifier serialization
	// https://drafts.csswg.org/cssom/#common-serializing-idioms
	var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;

	var fcssescape = function( ch, asCodePoint ) {
		if ( asCodePoint ) {

			// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
			if ( ch === "\0" ) {
				return "\uFFFD";
			}

			// Control characters and (dependent upon position) numbers get escaped as code points
			return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
		}

		// Other potentially-special ASCII characters get backslash-escaped
		return "\\" + ch;
	};

	$.escapeSelector = function( sel ) {
		return ( sel + "" ).replace( rcssescape, fcssescape );
	};
}

// Support: jQuery 3.4.x or older
// These methods have been defined in jQuery 3.5.0.
if ( !$.fn.even || !$.fn.odd ) {
	$.fn.extend( {
		even: function() {
			return this.filter( function( i ) {
				return i % 2 === 0;
			} );
		},
		odd: function() {
			return this.filter( function( i ) {
				return i % 2 === 1;
			} );
		}
	} );
}

} );

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// $.ui.plugin is deprecated. Use $.widget() extensions instead.
return $.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
				instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};

} );

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};

} );

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.safeBlur = function( element ) {

	// Support: IE9 - 10 only
	// If the <body> is blurred, IE will switch windows, see #9420
	if ( element && element.nodeName.toLowerCase() !== "body" ) {
		$( element ).trigger( "blur" );
	}
};

} );


/*!
 * jQuery UI Scroll Parent 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};

} );



/*!
 * jQuery UI Tabbable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: http://api.jqueryui.com/tabbable-selector/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version", "./focusable" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.extend( $.expr.pseudos, {
	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			hasTabindex = tabIndex != null;
		return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
	}
} );

} );


/*!
 * jQuery UI Unique ID 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );

} );
















( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
	"use strict";

// Create a local jQuery because jQuery Color relies on it and the
// global may not exist with AMD and a custom build (#10199).
// This module is a noop if used as a regular AMD module.
// eslint-disable-next-line no-unused-vars
var jQuery = $;

} );
/*!
 * jQuery Color Animations v2.2.0
 * https://github.com/jquery/jquery-color
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Sun May 10 09:02:36 2020 +0200
 */

( function( root, factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], factory );
	} else if ( typeof exports === "object" ) {
		module.exports = factory( require( "jquery" ) );
	} else {
		factory( root.jQuery );
	}
} )( this, function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
		"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	class2type = {},
	toString = class2type.toString,

	// plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

	// a set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {

			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 ),
					execResult[ 4 ] ?
						( parseInt( execResult[ 4 ], 16 ) / 255 ).toFixed( 2 ) :
						1
				];
			}
		}, {

			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ),
					execResult[ 4 ] ?
						( parseInt( execResult[ 4 ] + execResult[ 4 ], 16 ) / 255 )
							.toFixed( 2 ) :
						1
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// jQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	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
	};
} );

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
	function( _i, name ) {
		class2type[ "[object " + name + "]" ] = name.toLowerCase();
	} );

function getType( obj ) {
	if ( obj == null ) {
		return obj + "";
	}

	return typeof obj === "object" ?
		class2type[ toString.call( obj ) ] || "object" :
		typeof obj;
}

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return ( allowEmpty || !prop.def ) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// 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 Math.min( type.max, Math.max( 0, value ) );
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( _i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// if this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// exit each( stringParsers ) here because we matched
			return false;
		}
	} );

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// if this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = getType( red ),
			rgba = this._rgba = [];

		// more than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( _key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			} );
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( _spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				} );
			} else {
				each( spaces, function( _spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// if the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// if the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// this is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					} );

					// everything defined but alpha?
					if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {

						// use the default of 1
						if ( inst[ cache ][ 3 ] == null ) {
							inst[ cache ][ 3 ] = 1;
						}

						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				} );
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if ( isCache ) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				} );
			}
			return same;
		} );
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		} );
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( _key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// if null, don't override start value
			if ( endValue === null ) {
				return;
			}

			// if null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		} );
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {

		// if we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		} ) );
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				if ( v != null ) {
					return v;
				}
				return i > 2 ? 1 : 0;
			} );

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			} );

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// default to 0 when nulls exist
			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 = getType( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		} );

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {

		// alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var local, cur, match, fn,
				vtype = getType( value );

			if ( key === "alpha" ) {
				fn = this._hsla ? "hsla" : "rgba";
			} else {
				fn = spaceName;
			}
			local = this[ fn ]();
			cur = local[ prop.idx ];

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = getType( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	} );
} );

// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( _i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( getType( 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 UI Effects 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Effects Core
//>>group: Effects
/* eslint-disable max-len */
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
/* eslint-enable max-len */
//>>docs: http://api.jqueryui.com/category/effects-core/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./jquery-var-for-color",
			"./vendor/jquery-color/jquery.color",
			"./version"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var dataSpace = "ui-effects-",
	dataSpaceStyle = "ui-effects-style",
	dataSpaceAnimated = "ui-effects-animated";

$.effects = {
	effect: {}
};

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each(
	[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
	function( _, prop ) {
		$.fx.step[ prop ] = function( fx ) {
			if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
				jQuery.style( fx.elem, prop, fx.end );
				fx.setAttr = true;
			}
		};
	}
);

function camelCase( string ) {
	return string.replace( /-([\da-z])/gi, function( all, letter ) {
		return letter.toUpperCase();
	} );
}

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ camelCase( key ) ] = style[ key ];
			}
		}

	// Support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// Support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// Map the animated objects to store the original styles.
		allAnimations = allAnimations.map( function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		} );

		// Apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function( i, action ) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			} );
		};
		applyClassChange();

		// Map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map( function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		} );

		// Apply original class
		animated.attr( "class", baseClass );

		// Map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map( function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend( {}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				} );

			this.el.animate( this.diff, opts );
			return dfd.promise();
		} );

		// Once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done( function() {

			// Set the final class
			applyClassChange();

			// For each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function( key ) {
					el.css( key, "" );
				} );
			} );

			// This is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		} );
	} );
};

$.fn.extend( {
	addClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.addClass ),

	removeClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.removeClass ),

	toggleClass: ( function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {

					// Without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						( force ? { add: classNames } : { remove: classNames } ),
						speed, easing, callback );
				}
			} else {

				// Without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	} )( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback ) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
} );

} )();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

( function() {

if ( $.expr && $.expr.pseudos && $.expr.pseudos.animated ) {
	$.expr.pseudos.animated = ( function( orig ) {
		return function( elem ) {
			return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
		};
	} )( $.expr.pseudos.animated );
}

if ( $.uiBackCompat !== false ) {
	$.extend( $.effects, {

		// Saves a set of properties in a data storage
		save: function( element, set ) {
			var i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
				}
			}
		},

		// Restores a set of previously saved properties from a data storage
		restore: function( element, set ) {
			var val, i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					val = element.data( dataSpace + set[ i ] );
					element.css( set[ i ], val );
				}
			}
		},

		setMode: function( el, mode ) {
			if ( mode === "toggle" ) {
				mode = el.is( ":hidden" ) ? "show" : "hide";
			}
			return mode;
		},

		// Wraps the element around a wrapper that copies position properties
		createWrapper: function( element ) {

			// If the element is already wrapped, return it
			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				return element.parent();
			}

			// Wrap the element
			var props = {
					width: element.outerWidth( true ),
					height: element.outerHeight( true ),
					"float": element.css( "float" )
				},
				wrapper = $( "<div></div>" )
					.addClass( "ui-effects-wrapper" )
					.css( {
						fontSize: "100%",
						background: "transparent",
						border: "none",
						margin: 0,
						padding: 0
					} ),

				// Store the size in case width/height are defined in % - Fixes #5245
				size = {
					width: element.width(),
					height: element.height()
				},
				active = document.activeElement;

			// Support: Firefox
			// Firefox incorrectly exposes anonymous content
			// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
			try {
				// eslint-disable-next-line no-unused-expressions
				active.id;
			} catch ( e ) {
				active = document.body;
			}

			element.wrap( wrapper );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).trigger( "focus" );
			}

			// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
			// lose the reference to the wrapped element
			wrapper = element.parent();

			// Transfer positioning properties to the wrapper
			if ( element.css( "position" ) === "static" ) {
				wrapper.css( { position: "relative" } );
				element.css( { position: "relative" } );
			} else {
				$.extend( props, {
					position: element.css( "position" ),
					zIndex: element.css( "z-index" )
				} );
				$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
					props[ pos ] = element.css( pos );
					if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
						props[ pos ] = "auto";
					}
				} );
				element.css( {
					position: "relative",
					top: 0,
					left: 0,
					right: "auto",
					bottom: "auto"
				} );
			}
			element.css( size );

			return wrapper.css( props ).show();
		},

		removeWrapper: function( element ) {
			var active = document.activeElement;

			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				element.parent().replaceWith( element );

				// Fixes #7595 - Elements lose focus when wrapped.
				if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
					$( active ).trigger( "focus" );
				}
			}

			return element;
		}
	} );
}

$.extend( $.effects, {
	version: "1.13.0",

	define: function( name, mode, effect ) {
		if ( !effect ) {
			effect = mode;
			mode = "effect";
		}

		$.effects.effect[ name ] = effect;
		$.effects.effect[ name ].mode = mode;

		return effect;
	},

	scaledDimensions: function( element, percent, direction ) {
		if ( percent === 0 ) {
			return {
				height: 0,
				width: 0,
				outerHeight: 0,
				outerWidth: 0
			};
		}

		var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
			y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;

		return {
			height: element.height() * y,
			width: element.width() * x,
			outerHeight: element.outerHeight() * y,
			outerWidth: element.outerWidth() * x
		};

	},

	clipToBox: function( animation ) {
		return {
			width: animation.clip.right - animation.clip.left,
			height: animation.clip.bottom - animation.clip.top,
			left: animation.clip.left,
			top: animation.clip.top
		};
	},

	// Injects recently queued functions to be first in line (after "inprogress")
	unshift: function( element, queueLength, count ) {
		var queue = element.queue();

		if ( queueLength > 1 ) {
			queue.splice.apply( queue,
				[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
		}
		element.dequeue();
	},

	saveStyle: function( element ) {
		element.data( dataSpaceStyle, element[ 0 ].style.cssText );
	},

	restoreStyle: function( element ) {
		element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
		element.removeData( dataSpaceStyle );
	},

	mode: function( element, mode ) {
		var hidden = element.is( ":hidden" );

		if ( mode === "toggle" ) {
			mode = hidden ? "show" : "hide";
		}
		if ( hidden ? mode === "hide" : mode === "show" ) {
			mode = "none";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	getBaseline: function( origin, original ) {
		var y, x;

		switch ( origin[ 0 ] ) {
		case "top":
			y = 0;
			break;
		case "middle":
			y = 0.5;
			break;
		case "bottom":
			y = 1;
			break;
		default:
			y = origin[ 0 ] / original.height;
		}

		switch ( origin[ 1 ] ) {
		case "left":
			x = 0;
			break;
		case "center":
			x = 0.5;
			break;
		case "right":
			x = 1;
			break;
		default:
			x = origin[ 1 ] / original.width;
		}

		return {
			x: x,
			y: y
		};
	},

	// Creates a placeholder element so that the original element can be made absolute
	createPlaceholder: function( element ) {
		var placeholder,
			cssPosition = element.css( "position" ),
			position = element.position();

		// Lock in margins first to account for form elements, which
		// will change margin if you explicitly set height
		// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
		// Support: Safari
		element.css( {
			marginTop: element.css( "marginTop" ),
			marginBottom: element.css( "marginBottom" ),
			marginLeft: element.css( "marginLeft" ),
			marginRight: element.css( "marginRight" )
		} )
		.outerWidth( element.outerWidth() )
		.outerHeight( element.outerHeight() );

		if ( /^(static|relative)/.test( cssPosition ) ) {
			cssPosition = "absolute";

			placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {

				// Convert inline to inline block to account for inline elements
				// that turn to inline block based on content (like img)
				display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
					"inline-block" :
					"block",
				visibility: "hidden",

				// Margins need to be set to account for margin collapse
				marginTop: element.css( "marginTop" ),
				marginBottom: element.css( "marginBottom" ),
				marginLeft: element.css( "marginLeft" ),
				marginRight: element.css( "marginRight" ),
				"float": element.css( "float" )
			} )
			.outerWidth( element.outerWidth() )
			.outerHeight( element.outerHeight() )
			.addClass( "ui-effects-placeholder" );

			element.data( dataSpace + "placeholder", placeholder );
		}

		element.css( {
			position: cssPosition,
			left: position.left,
			top: position.top
		} );

		return placeholder;
	},

	removePlaceholder: function( element ) {
		var dataKey = dataSpace + "placeholder",
				placeholder = element.data( dataKey );

		if ( placeholder ) {
			placeholder.remove();
			element.removeData( dataKey );
		}
	},

	// Removes a placeholder if it exists and restores
	// properties that were modified during placeholder creation
	cleanUp: function( element ) {
		$.effects.restoreStyle( element );
		$.effects.removePlaceholder( element );
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		} );
		return value;
	}
} );

// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// Allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// Convert to an object
	effect = { effect: effect };

	// Catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// Catch (effect, callback)
	if ( typeof options === "function" ) {
		callback = options;
		speed = null;
		options = {};
	}

	// Catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// Catch (effect, options, callback)
	if ( typeof speed === "function" ) {
		callback = speed;
		speed = null;
	}

	// Add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {

	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( typeof option === "function" ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend( {
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			effectMethod = $.effects.effect[ args.effect ],
			defaultMode = effectMethod.mode,
			queue = args.queue,
			queueName = queue || "fx",
			complete = args.complete,
			mode = args.mode,
			modes = [],
			prefilter = function( next ) {
				var el = $( this ),
					normalizedMode = $.effects.mode( el, mode ) || defaultMode;

				// Sentinel for duck-punching the :animated pseudo-selector
				el.data( dataSpaceAnimated, true );

				// Save effect mode for later use,
				// we can't just call $.effects.mode again later,
				// as the .show() below destroys the initial state
				modes.push( normalizedMode );

				// See $.uiBackCompat inside of run() for removal of defaultMode in 1.14
				if ( defaultMode && ( normalizedMode === "show" ||
						( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
					el.show();
				}

				if ( !defaultMode || normalizedMode !== "none" ) {
					$.effects.saveStyle( el );
				}

				if ( typeof next === "function" ) {
					next();
				}
			};

		if ( $.fx.off || !effectMethod ) {

			// Delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, complete );
			} else {
				return this.each( function() {
					if ( complete ) {
						complete.call( this );
					}
				} );
			}
		}

		function run( next ) {
			var elem = $( this );

			function cleanup() {
				elem.removeData( dataSpaceAnimated );

				$.effects.cleanUp( elem );

				if ( args.mode === "hide" ) {
					elem.hide();
				}

				done();
			}

			function done() {
				if ( typeof complete === "function" ) {
					complete.call( elem[ 0 ] );
				}

				if ( typeof next === "function" ) {
					next();
				}
			}

			// Override mode option on a per element basis,
			// as toggle can be either show or hide depending on element state
			args.mode = modes.shift();

			if ( $.uiBackCompat !== false && !defaultMode ) {
				if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, done );
				}
			} else {
				if ( args.mode === "none" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, cleanup );
				}
			}
		}

		// Run prefilter on all elements first to ensure that
		// any showing or hiding happens before placeholder creation,
		// which ensures that any layout changes are correctly captured.
		return queue === false ?
			this.each( prefilter ).each( run ) :
			this.queue( queueName, prefilter ).queue( queueName, run );
	},

	show: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.show ),

	hide: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.hide ),

	toggle: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.toggle ),

	cssUnit: function( key ) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		} );
		return val;
	},

	cssClip: function( clipObj ) {
		if ( clipObj ) {
			return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
				clipObj.bottom + "px " + clipObj.left + "px)" );
		}
		return parseClip( this.css( "clip" ), this );
	},

	transfer: function( options, done ) {
		var element = $( this ),
			target = $( options.to ),
			targetFixed = target.css( "position" ) === "fixed",
			body = $( "body" ),
			fixTop = targetFixed ? body.scrollTop() : 0,
			fixLeft = targetFixed ? body.scrollLeft() : 0,
			endPosition = target.offset(),
			animation = {
				top: endPosition.top - fixTop,
				left: endPosition.left - fixLeft,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = element.offset(),
			transfer = $( "<div class='ui-effects-transfer'></div>" );

		transfer
			.appendTo( "body" )
			.addClass( options.className )
			.css( {
				top: startPosition.top - fixTop,
				left: startPosition.left - fixLeft,
				height: element.innerHeight(),
				width: element.innerWidth(),
				position: targetFixed ? "fixed" : "absolute"
			} )
			.animate( animation, options.duration, options.easing, function() {
				transfer.remove();
				if ( typeof done === "function" ) {
					done();
				}
			} );
	}
} );

function parseClip( str, element ) {
		var outerWidth = element.outerWidth(),
			outerHeight = element.outerHeight(),
			clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
			values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];

		return {
			top: parseFloat( values[ 1 ] ) || 0,
			right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
			bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
			left: parseFloat( values[ 4 ] ) || 0
		};
}

$.fx.step.clip = function( fx ) {
	if ( !fx.clipInit ) {
		fx.start = $( fx.elem ).cssClip();
		if ( typeof fx.end === "string" ) {
			fx.end = parseClip( fx.end, fx.elem );
		}
		fx.clipInit = true;
	}

	$( fx.elem ).cssClip( {
		top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
		right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
		bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
		left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
	} );
};

} )();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

( function() {

// Based on easing equations from Robert Penner (http://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;
	};
} );

} )();

return $.effects;

} );



/*!
 * jQuery UI Form Reset Mixin 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: http://api.jqueryui.com/form-reset-mixin/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./form",
			"./version"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.formResetMixin = {
	_formResetHandler: function() {
		var form = $( this );

		// Wait for the form reset to actually happen before refreshing
		setTimeout( function() {
			var instances = form.data( "ui-form-reset-instances" );
			$.each( instances, function() {
				this.refresh();
			} );
		} );
	},

	_bindFormResetHandler: function() {
		this.form = this.element._form();
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" ) || [];
		if ( !instances.length ) {

			// We don't use _on() here because we use a single event handler per form
			this.form.on( "reset.ui-form-reset", this._formResetHandler );
		}
		instances.push( this );
		this.form.data( "ui-form-reset-instances", instances );
	},

	_unbindFormResetHandler: function() {
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" );
		instances.splice( $.inArray( this, instances ), 1 );
		if ( instances.length ) {
			this.form.data( "ui-form-reset-instances", instances );
		} else {
			this.form
				.removeData( "ui-form-reset-instances" )
				.off( "reset.ui-form-reset" );
		}
	}
};

} );


/*!
 * jQuery UI Position 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function isWindow( obj ) {
	return obj != null && obj === obj.window;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style=" +
				"'display:block;position:absolute;width:200px;height:200px;overflow:hidden;'>" +
				"<div style='height:300px;width:auto;'></div></div>" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isElemWindow = isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isElemWindow && !isDocument;
		return {
			element: withinElement,
			isWindow: isElemWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,

		// Make sure string options are treated as CSS selectors
		target = typeof options.of === "string" ?
			$( document ).find( options.of ) :
			$( options.of ),

		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

return $.ui.position;

} );


/*!
 * jQuery UI Widget 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var widgetUuid = 0;
var widgetHasOwnProperty = Array.prototype.hasOwnProperty;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {

			// Only trigger remove when necessary to save time
			events = $._data( elem, "events" );
			if ( events && events.remove ) {
				$( elem ).triggerHandler( "remove" );
			}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( Array.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr.pseudos[ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( typeof value !== "function" ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( widgetHasOwnProperty.call( input[ inputIndex ], key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( typeof instance[ options ] !== "function" ||
						options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function bindRemoveEvent() {
			options.element.each( function( _, element ) {
				var isTracked = $.map( that.classesElementLookup, function( elements ) {
					return elements;
				} )
					.some( function( elements ) {
						return elements.is( element );
					} );

				if ( !isTracked ) {
					that._on( $( element ), {
						remove: "_untrackClassesElement"
					} );
				}
			} );
		}

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					bindRemoveEvent();
					current = $( $.uniqueSort( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );

		this._off( $( event.target ) );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( typeof callback === "function" &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		} else if ( options === true ) {
			options = {};
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

return $.widget;

} );



/*!
 * jQuery UI Effects Blind 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Blind Effect
//>>group: Effects
//>>description: Blinds the element.
//>>docs: http://api.jqueryui.com/blind-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "blind", "hide", function( options, done ) {
	var map = {
			up: [ "bottom", "top" ],
			vertical: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			horizontal: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		element = $( this ),
		direction = options.direction || "up",
		start = element.cssClip(),
		animate = { clip: $.extend( {}, start ) },
		placeholder = $.effects.createPlaceholder( element );

	animate.clip[ map[ direction ][ 0 ] ] = animate.clip[ map[ direction ][ 1 ] ];

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animate ) );
		}

		animate.clip = start;
	}

	if ( placeholder ) {
		placeholder.animate( $.effects.clipToBox( animate ), options.duration, options.easing );
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );

} );



/*!
 * jQuery UI Effects Bounce 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Bounce Effect
//>>group: Effects
//>>description: Bounces an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/bounce-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "bounce", function( options, done ) {
	var upAnim, downAnim, refValue,
		element = $( this ),

		// Defaults:
		mode = options.mode,
		hide = mode === "hide",
		show = mode === "show",
		direction = options.direction || "up",
		distance = options.distance,
		times = options.times || 5,

		// Number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = options.duration / anims,
		easing = options.easing,

		// Utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i = 0,

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	refValue = element.css( ref );

	// Default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = element[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = refValue;

		// If we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		element
			.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// Start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = refValue;

	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( ; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element
			.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element.animate( upAnim, speed, easing );
	}

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );

} );



/*!
 * jQuery UI Effects Clip 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Clip Effect
//>>group: Effects
//>>description: Clips the element on and off like an old TV.
//>>docs: http://api.jqueryui.com/clip-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "clip", "hide", function( options, done ) {
	var start,
		animate = {},
		element = $( this ),
		direction = options.direction || "vertical",
		both = direction === "both",
		horizontal = both || direction === "horizontal",
		vertical = both || direction === "vertical";

	start = element.cssClip();
	animate.clip = {
		top: vertical ? ( start.bottom - start.top ) / 2 : start.top,
		right: horizontal ? ( start.right - start.left ) / 2 : start.right,
		bottom: vertical ? ( start.bottom - start.top ) / 2 : start.bottom,
		left: horizontal ? ( start.right - start.left ) / 2 : start.left
	};

	$.effects.createPlaceholder( element );

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		animate.clip = start;
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );

} );

} );



/*!
 * jQuery UI Effects Drop 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Drop Effect
//>>group: Effects
//>>description: Moves an element in one direction and hides it at the same time.
//>>docs: http://api.jqueryui.com/drop-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "drop", "hide", function( options, done ) {

	var distance,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "-=" : "+=",
		oppositeMotion = ( motion === "+=" ) ? "-=" : "+=",
		animation = {
			opacity: 0
		};

	$.effects.createPlaceholder( element );

	distance = options.distance ||
		element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	animation[ ref ] = motion + distance;

	if ( show ) {
		element.css( animation );

		animation[ ref ] = oppositeMotion + distance;
		animation.opacity = 1;
	}

	// Animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );

} );



/*!
 * jQuery UI Effects Explode 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Explode Effect
//>>group: Effects
/* eslint-disable max-len */
//>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
/* eslint-enable max-len */
//>>docs: http://api.jqueryui.com/explode-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "explode", "hide", function( options, done ) {

	var i, j, left, top, mx, my,
		rows = options.pieces ? Math.round( Math.sqrt( options.pieces ) ) : 3,
		cells = rows,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",

		// Show and then visibility:hidden the element before calculating offset
		offset = element.show().css( "visibility", "hidden" ).offset(),

		// Width and height of a piece
		width = Math.ceil( element.outerWidth() / cells ),
		height = Math.ceil( element.outerHeight() / rows ),
		pieces = [];

	// Children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// Clone the element for each row and cell.
	for ( i = 0; i < rows; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2;

		for ( j = 0; j < cells; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			element
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css( {
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				} )

				// Select the wrapper - make it overflow: hidden and absolute positioned based on
				// where the original was located +left and +top equal to the size of pieces
				.parent()
					.addClass( "ui-effects-explode" )
					.css( {
						position: "absolute",
						overflow: "hidden",
						width: width,
						height: height,
						left: left + ( show ? mx * width : 0 ),
						top: top + ( show ? my * height : 0 ),
						opacity: show ? 0 : 1
					} )
					.animate( {
						left: left + ( show ? 0 : mx * width ),
						top: top + ( show ? 0 : my * height ),
						opacity: show ? 1 : 0
					}, options.duration || 500, options.easing, childComplete );
		}
	}

	function animComplete() {
		element.css( {
			visibility: "visible"
		} );
		$( pieces ).remove();
		done();
	}
} );

} );



/*!
 * jQuery UI Effects Fade 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fade Effect
//>>group: Effects
//>>description: Fades the element.
//>>docs: http://api.jqueryui.com/fade-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "fade", "toggle", function( options, done ) {
	var show = options.mode === "show";

	$( this )
		.css( "opacity", show ? 0 : 1 )
		.animate( {
			opacity: show ? 1 : 0
		}, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );

} );



/*!
 * jQuery UI Effects Fold 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fold Effect
//>>group: Effects
//>>description: Folds an element first horizontally and then vertically.
//>>docs: http://api.jqueryui.com/fold-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "fold", "hide", function( options, done ) {

	// Create element
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		size = options.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!options.horizFirst,
		ref = horizFirst ? [ "right", "bottom" ] : [ "bottom", "right" ],
		duration = options.duration / 2,

		placeholder = $.effects.createPlaceholder( element ),

		start = element.cssClip(),
		animation1 = { clip: $.extend( {}, start ) },
		animation2 = { clip: $.extend( {}, start ) },

		distance = [ start[ ref[ 0 ] ], start[ ref[ 1 ] ] ],

		queuelen = element.queue().length;

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	animation1.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 1 ] ] = 0;

	if ( show ) {
		element.cssClip( animation2.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animation2 ) );
		}

		animation2.clip = start;
	}

	// Animate
	element
		.queue( function( next ) {
			if ( placeholder ) {
				placeholder
					.animate( $.effects.clipToBox( animation1 ), duration, options.easing )
					.animate( $.effects.clipToBox( animation2 ), duration, options.easing );
			}

			next();
		} )
		.animate( animation1, duration, options.easing )
		.animate( animation2, duration, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, 4 );
} );

} );



/*!
 * jQuery UI Effects Highlight 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Highlight Effect
//>>group: Effects
//>>description: Highlights the background of an element in a defined color for a custom duration.
//>>docs: http://api.jqueryui.com/highlight-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "highlight", "show", function( options, done ) {
	var element = $( this ),
		animation = {
			backgroundColor: element.css( "backgroundColor" )
		};

	if ( options.mode === "hide" ) {
		animation.opacity = 0;
	}

	$.effects.saveStyle( element );

	element
		.css( {
			backgroundImage: "none",
			backgroundColor: options.color || "#ffff99"
		} )
		.animate( animation, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );

} );



/*!
 * jQuery UI Effects Size 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Size Effect
//>>group: Effects
//>>description: Resize an element to a specified width and height.
//>>docs: http://api.jqueryui.com/size-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "size", function( options, done ) {

	// Create element
	var baseline, factor, temp,
		element = $( this ),

		// Copy for children
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = options.mode,
		restore = mode !== "effect",
		scale = options.scale || "both",
		origin = options.origin || [ "middle", "center" ],
		position = element.css( "position" ),
		pos = element.position(),
		original = $.effects.scaledDimensions( element ),
		from = options.from || original,
		to = options.to || $.effects.scaledDimensions( element, 0 );

	$.effects.createPlaceholder( element );

	if ( mode === "show" ) {
		temp = from;
		from = to;
		to = temp;
	}

	// Set scaling factor
	factor = {
		from: {
			y: from.height / original.height,
			x: from.width / original.width
		},
		to: {
			y: to.height / original.height,
			x: to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, vProps, factor.from.y, from );
			to = $.effects.setTransition( element, vProps, factor.to.y, to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			from = $.effects.setTransition( element, hProps, factor.from.x, from );
			to = $.effects.setTransition( element, hProps, factor.to.x, to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, cProps, factor.from.y, from );
			to = $.effects.setTransition( element, cProps, factor.to.y, to );
		}
	}

	// Adjust the position properties based on the provided origin points
	if ( origin ) {
		baseline = $.effects.getBaseline( origin, original );
		from.top = ( original.outerHeight - from.outerHeight ) * baseline.y + pos.top;
		from.left = ( original.outerWidth - from.outerWidth ) * baseline.x + pos.left;
		to.top = ( original.outerHeight - to.outerHeight ) * baseline.y + pos.top;
		to.left = ( original.outerWidth - to.outerWidth ) * baseline.x + pos.left;
	}
	delete from.outerHeight;
	delete from.outerWidth;
	element.css( from );

	// Animate the children if desired
	if ( scale === "content" || scale === "both" ) {

		vProps = vProps.concat( [ "marginTop", "marginBottom" ] ).concat( cProps );
		hProps = hProps.concat( [ "marginLeft", "marginRight" ] );

		// Only animate children with width attributes specified
		// TODO: is this right? should we include anything with css width specified as well
		element.find( "*[width]" ).each( function() {
			var child = $( this ),
				childOriginal = $.effects.scaledDimensions( child ),
				childFrom = {
					height: childOriginal.height * factor.from.y,
					width: childOriginal.width * factor.from.x,
					outerHeight: childOriginal.outerHeight * factor.from.y,
					outerWidth: childOriginal.outerWidth * factor.from.x
				},
				childTo = {
					height: childOriginal.height * factor.to.y,
					width: childOriginal.width * factor.to.x,
					outerHeight: childOriginal.height * factor.to.y,
					outerWidth: childOriginal.width * factor.to.x
				};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				childFrom = $.effects.setTransition( child, vProps, factor.from.y, childFrom );
				childTo = $.effects.setTransition( child, vProps, factor.to.y, childTo );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				childFrom = $.effects.setTransition( child, hProps, factor.from.x, childFrom );
				childTo = $.effects.setTransition( child, hProps, factor.to.x, childTo );
			}

			if ( restore ) {
				$.effects.saveStyle( child );
			}

			// Animate children
			child.css( childFrom );
			child.animate( childTo, options.duration, options.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restoreStyle( child );
				}
			} );
		} );
	}

	// Animate
	element.animate( to, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: function() {

			var offset = element.offset();

			if ( to.opacity === 0 ) {
				element.css( "opacity", from.opacity );
			}

			if ( !restore ) {
				element
					.css( "position", position === "static" ? "relative" : position )
					.offset( offset );

				// Need to save style here so that automatic style restoration
				// doesn't restore to the original styles from before the animation.
				$.effects.saveStyle( element );
			}

			done();
		}
	} );

} );

} );




/*!
 * jQuery UI Effects Scale 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Scale Effect
//>>group: Effects
//>>description: Grows or shrinks an element and its content.
//>>docs: http://api.jqueryui.com/scale-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect",
			"./effect-size"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "scale", function( options, done ) {

	// Create element
	var el = $( this ),
		mode = options.mode,
		percent = parseInt( options.percent, 10 ) ||
			( parseInt( options.percent, 10 ) === 0 ? 0 : ( mode !== "effect" ? 0 : 100 ) ),

		newOptions = $.extend( true, {
			from: $.effects.scaledDimensions( el ),
			to: $.effects.scaledDimensions( el, percent, options.direction || "both" ),
			origin: options.origin || [ "middle", "center" ]
		}, options );

	// Fade option to support puff
	if ( options.fade ) {
		newOptions.from.opacity = 1;
		newOptions.to.opacity = 0;
	}

	$.effects.effect.size.call( this, newOptions, done );
} );

} );




/*!
 * jQuery UI Effects Puff 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Puff Effect
//>>group: Effects
//>>description: Creates a puff effect by scaling the element up and hiding it at the same time.
//>>docs: http://api.jqueryui.com/puff-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect",
			"./effect-scale"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "puff", "hide", function( options, done ) {
	var newOptions = $.extend( true, {}, options, {
		fade: true,
		percent: parseInt( options.percent, 10 ) || 150
	} );

	$.effects.effect.scale.call( this, newOptions, done );
} );

} );



/*!
 * jQuery UI Effects Pulsate 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Pulsate Effect
//>>group: Effects
//>>description: Pulsates an element n times by changing the opacity to zero and back.
//>>docs: http://api.jqueryui.com/pulsate-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "pulsate", "show", function( options, done ) {
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		showhide = show || hide,

		// Showing or hiding leaves off the "last" animation
		anims = ( ( options.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = options.duration / anims,
		animateTo = 0,
		i = 1,
		queuelen = element.queue().length;

	if ( show || !element.is( ":visible" ) ) {
		element.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// Anims - 1 opacity "toggles"
	for ( ; i < anims; i++ ) {
		element.animate( { opacity: animateTo }, duration, options.easing );
		animateTo = 1 - animateTo;
	}

	element.animate( { opacity: animateTo }, duration, options.easing );

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );

} );



/*!
 * jQuery UI Effects Shake 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Shake Effect
//>>group: Effects
//>>description: Shakes an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/shake-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "shake", function( options, done ) {

	var i = 1,
		element = $( this ),
		direction = options.direction || "left",
		distance = options.distance || 20,
		times = options.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( options.duration / anims ),
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		animation = {},
		animation1 = {},
		animation2 = {},

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	element.animate( animation, speed, options.easing );

	// Shakes
	for ( ; i < times; i++ ) {
		element
			.animate( animation1, speed, options.easing )
			.animate( animation2, speed, options.easing );
	}

	element
		.animate( animation1, speed, options.easing )
		.animate( animation, speed / 2, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );

} );



/*!
 * jQuery UI Effects Slide 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slide Effect
//>>group: Effects
//>>description: Slides an element in and out of the viewport.
//>>docs: http://api.jqueryui.com/slide-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.effects.define( "slide", "show", function( options, done ) {
	var startClip, startRef,
		element = $( this ),
		map = {
			up: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		mode = options.mode,
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		distance = options.distance ||
			element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ),
		animation = {};

	$.effects.createPlaceholder( element );

	startClip = element.cssClip();
	startRef = element.position()[ ref ];

	// Define hide animation
	animation[ ref ] = ( positiveMotion ? -1 : 1 ) * distance + startRef;
	animation.clip = element.cssClip();
	animation.clip[ map[ direction ][ 1 ] ] = animation.clip[ map[ direction ][ 0 ] ];

	// Reverse the animation if we're showing
	if ( mode === "show" ) {
		element.cssClip( animation.clip );
		element.css( ref, animation[ ref ] );
		animation.clip = startClip;
		animation[ ref ] = startRef;
	}

	// Actually animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );

} );



/*!
 * jQuery UI Effects Transfer 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../effect"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var effect;
if ( $.uiBackCompat !== false ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
return effect;

} );





/*!
 * jQuery UI Accordion 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Accordion
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Displays collapsible content panels for presenting information in a limited amount of space.
/* eslint-enable max-len */
//>>docs: http://api.jqueryui.com/accordion/
//>>demos: http://jqueryui.com/accordion/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/accordion.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../keycode",
			"../unique-id",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.accordion", {
	version: "1.13.0",
	options: {
		active: 0,
		animate: {},
		classes: {
			"ui-accordion-header": "ui-corner-top",
			"ui-accordion-header-collapsed": "ui-corner-all",
			"ui-accordion-content": "ui-corner-bottom"
		},
		collapsible: false,
		event: "click",
		header: function( elem ) {
			return elem.find( "> li > :first-child" ).add( elem.find( "> :not(li)" ).even() );
		},
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// Callbacks
		activate: null,
		beforeActivate: null
	},

	hideProps: {
		borderTopWidth: "hide",
		borderBottomWidth: "hide",
		paddingTop: "hide",
		paddingBottom: "hide",
		height: "hide"
	},

	showProps: {
		borderTopWidth: "show",
		borderBottomWidth: "show",
		paddingTop: "show",
		paddingBottom: "show",
		height: "show"
	},

	_create: function() {
		var options = this.options;

		this.prevShow = this.prevHide = $();
		this._addClass( "ui-accordion", "ui-widget ui-helper-reset" );
		this.element.attr( "role", "tablist" );

		// Don't allow collapsible: false and active: false / null
		if ( !options.collapsible && ( options.active === false || options.active == null ) ) {
			options.active = 0;
		}

		this._processPanels();

		// handle negative values
		if ( options.active < 0 ) {
			options.active += this.headers.length;
		}
		this._refresh();
	},

	_getCreateEventData: function() {
		return {
			header: this.active,
			panel: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icon, children,
			icons = this.options.icons;

		if ( icons ) {
			icon = $( "<span>" );
			this._addClass( icon, "ui-accordion-header-icon", "ui-icon " + icons.header );
			icon.prependTo( this.headers );
			children = this.active.children( ".ui-accordion-header-icon" );
			this._removeClass( children, icons.header )
				._addClass( children, null, icons.activeHeader )
				._addClass( this.headers, "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this._removeClass( this.headers, "ui-accordion-icons" );
		this.headers.children( ".ui-accordion-header-icon" ).remove();
	},

	_destroy: function() {
		var contents;

		// Clean up main element
		this.element.removeAttr( "role" );

		// Clean up headers
		this.headers
			.removeAttr( "role aria-expanded aria-selected aria-controls tabIndex" )
			.removeUniqueId();

		this._destroyIcons();

		// Clean up content panels
		contents = this.headers.next()
			.css( "display", "" )
			.removeAttr( "role aria-hidden aria-labelledby" )
			.removeUniqueId();

		if ( this.options.heightStyle !== "content" ) {
			contents.css( "height", "" );
		}
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {

			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "event" ) {
			if ( this.options.event ) {
				this._off( this.headers, this.options.event );
			}
			this._setupEvents( value );
		}

		this._super( key, value );

		// Setting collapsible: false while collapsed; open first panel
		if ( key === "collapsible" && !value && this.options.active === false ) {
			this._activate( 0 );
		}

		if ( key === "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", value );

		// Support: IE8 Only
		// #5332 / #6059 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		this._toggleClass( null, "ui-state-disabled", !!value );
		this._toggleClass( this.headers.add( this.headers.next() ), null, "ui-state-disabled",
			!!value );
	},

	_keydown: function( event ) {
		if ( event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
		case keyCode.RIGHT:
		case keyCode.DOWN:
			toFocus = this.headers[ ( currentIndex + 1 ) % length ];
			break;
		case keyCode.LEFT:
		case keyCode.UP:
			toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
			break;
		case keyCode.SPACE:
		case keyCode.ENTER:
			this._eventHandler( event );
			break;
		case keyCode.HOME:
			toFocus = this.headers[ 0 ];
			break;
		case keyCode.END:
			toFocus = this.headers[ length - 1 ];
			break;
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			$( toFocus ).trigger( "focus" );
			event.preventDefault();
		}
	},

	_panelKeyDown: function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().trigger( "focus" );
		}
	},

	refresh: function() {
		var options = this.options;
		this._processPanels();

		// Was collapsed or no panel
		if ( ( options.active === false && options.collapsible === true ) ||
				!this.headers.length ) {
			options.active = false;
			this.active = $();

		// active false only when collapsible is true
		} else if ( options.active === false ) {
			this._activate( 0 );

		// was active, but active panel is gone
		} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {

			// all remaining panel are disabled
			if ( this.headers.length === this.headers.find( ".ui-state-disabled" ).length ) {
				options.active = false;
				this.active = $();

			// activate previous panel
			} else {
				this._activate( Math.max( 0, options.active - 1 ) );
			}

		// was active, active panel still exists
		} else {

			// make sure active index is correct
			options.active = this.headers.index( this.active );
		}

		this._destroyIcons();

		this._refresh();
	},

	_processPanels: function() {
		var prevHeaders = this.headers,
			prevPanels = this.panels;

		if ( typeof this.options.header === "function" ) {
			this.headers = this.options.header( this.element );
		} else {
			this.headers = this.element.find( this.options.header );
		}
		this._addClass( this.headers, "ui-accordion-header ui-accordion-header-collapsed",
			"ui-state-default" );

		this.panels = this.headers.next().filter( ":not(.ui-accordion-content-active)" ).hide();
		this._addClass( this.panels, "ui-accordion-content", "ui-helper-reset ui-widget-content" );

		// Avoid memory leaks (#10056)
		if ( prevPanels ) {
			this._off( prevHeaders.not( this.headers ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent();

		this.active = this._findActive( options.active );
		this._addClass( this.active, "ui-accordion-header-active", "ui-state-active" )
			._removeClass( this.active, "ui-accordion-header-collapsed" );
		this._addClass( this.active.next(), "ui-accordion-content-active" );
		this.active.next().show();

		this.headers
			.attr( "role", "tab" )
			.each( function() {
				var header = $( this ),
					headerId = header.uniqueId().attr( "id" ),
					panel = header.next(),
					panelId = panel.uniqueId().attr( "id" );
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			} )
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
				.attr( {
					"aria-selected": "false",
					"aria-expanded": "false",
					tabIndex: -1
				} )
				.next()
					.attr( {
						"aria-hidden": "true"
					} )
					.hide();

		// Make sure at least one header is in the tab order
		if ( !this.active.length ) {
			this.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active.attr( {
				"aria-selected": "true",
				"aria-expanded": "true",
				tabIndex: 0
			} )
				.next()
					.attr( {
						"aria-hidden": "false"
					} );
		}

		this._createIcons();

		this._setupEvents( options.event );

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			this.element.siblings( ":visible" ).each( function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			} );

			this.headers.each( function() {
				maxHeight -= $( this ).outerHeight( true );
			} );

			this.headers.next()
				.each( function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				} )
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.headers.next()
				.each( function() {
					var isVisible = $( this ).is( ":visible" );
					if ( !isVisible ) {
						$( this ).show();
					}
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
					if ( !isVisible ) {
						$( this ).hide();
					}
				} )
				.height( maxHeight );
		}
	},

	_activate: function( index ) {
		var active = this._findActive( index )[ 0 ];

		// Trying to activate the already active panel
		if ( active === this.active[ 0 ] ) {
			return;
		}

		// Trying to collapse, simulate a click on the currently active header
		active = active || this.active[ 0 ];

		this._eventHandler( {
			target: active,
			currentTarget: active,
			preventDefault: $.noop
		} );
	},

	_findActive: function( selector ) {
		return typeof selector === "number" ? this.headers.eq( selector ) : $();
	},

	_setupEvents: function( event ) {
		var events = {
			keydown: "_keydown"
		};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			} );
		}

		this._off( this.headers.add( this.headers.next() ) );
		this._on( this.headers, events );
		this._on( this.headers.next(), { keydown: "_panelKeyDown" } );
		this._hoverable( this.headers );
		this._focusable( this.headers );
	},

	_eventHandler: function( event ) {
		var activeChildren, clickedChildren,
			options = this.options,
			active = this.active,
			clicked = $( event.currentTarget ),
			clickedIsActive = clicked[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : clicked.next(),
			toHide = active.next(),
			eventData = {
				oldHeader: active,
				oldPanel: toHide,
				newHeader: collapsing ? $() : clicked,
				newPanel: toShow
			};

		event.preventDefault();

		if (

				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||

				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.headers.index( clicked );

		// When the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $() : clicked;
		this._toggle( eventData );

		// Switch classes
		// corner classes on the previously active header stay after the animation
		this._removeClass( active, "ui-accordion-header-active", "ui-state-active" );
		if ( options.icons ) {
			activeChildren = active.children( ".ui-accordion-header-icon" );
			this._removeClass( activeChildren, null, options.icons.activeHeader )
				._addClass( activeChildren, null, options.icons.header );
		}

		if ( !clickedIsActive ) {
			this._removeClass( clicked, "ui-accordion-header-collapsed" )
				._addClass( clicked, "ui-accordion-header-active", "ui-state-active" );
			if ( options.icons ) {
				clickedChildren = clicked.children( ".ui-accordion-header-icon" );
				this._removeClass( clickedChildren, null, options.icons.header )
					._addClass( clickedChildren, null, options.icons.activeHeader );
			}

			this._addClass( clicked.next(), "ui-accordion-content-active" );
		}
	},

	_toggle: function( data ) {
		var toShow = data.newPanel,
			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

		// Handle activating a panel during the animation for another activation
		this.prevShow.add( this.prevHide ).stop( true, true );
		this.prevShow = toShow;
		this.prevHide = toHide;

		if ( this.options.animate ) {
			this._animate( toShow, toHide, data );
		} else {
			toHide.hide();
			toShow.show();
			this._toggleComplete( data );
		}

		toHide.attr( {
			"aria-hidden": "true"
		} );
		toHide.prev().attr( {
			"aria-selected": "false",
			"aria-expanded": "false"
		} );

		// if we're switching panels, remove the old header from the tab order
		// if we're opening from collapsed state, remove the previous header from the tab order
		// if we're collapsing, then keep the collapsing header in the tab order
		if ( toShow.length && toHide.length ) {
			toHide.prev().attr( {
				"tabIndex": -1,
				"aria-expanded": "false"
			} );
		} else if ( toShow.length ) {
			this.headers.filter( function() {
				return parseInt( $( this ).attr( "tabIndex" ), 10 ) === 0;
			} )
				.attr( "tabIndex", -1 );
		}

		toShow
			.attr( "aria-hidden", "false" )
			.prev()
				.attr( {
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				} );
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			boxSizing = toShow.css( "box-sizing" ),
			down = toShow.length &&
				( !toHide.length || ( toShow.index() < toHide.index() ) ),
			animate = this.options.animate || {},
			options = down && animate.down || animate,
			complete = function() {
				that._toggleComplete( data );
			};

		if ( typeof options === "number" ) {
			duration = options;
		}
		if ( typeof options === "string" ) {
			easing = options;
		}

		// fall back from options to animation in case of partial down settings
		easing = easing || options.easing || animate.easing;
		duration = duration || options.duration || animate.duration;

		if ( !toHide.length ) {
			return toShow.animate( this.showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( this.hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( this.hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		} );
		toShow
			.hide()
			.animate( this.showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						if ( boxSizing === "content-box" ) {
							adjust += fx.now;
						}
					} else if ( that.options.heightStyle !== "content" ) {
						fx.now = Math.round( total - toHide.outerHeight() - adjust );
						adjust = 0;
					}
				}
			} );
	},

	_toggleComplete: function( data ) {
		var toHide = data.oldPanel,
			prev = toHide.prev();

		this._removeClass( toHide, "ui-accordion-content-active" );
		this._removeClass( prev, "ui-accordion-header-active" )
			._addClass( prev, "ui-accordion-header-collapsed" );

		// 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 UI Menu 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../keycode",
			"../position",
			"../safe-active-element",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.menu", {
	version: "1.13.0",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// Callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.lastMousePosition = { x: null, y: null };
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();

				this._activateItem( event );
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) &&
							active.closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": "_activateItem",
			"mousemove .ui-menu-item": "_activateItem",
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this._menuItems().first();

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay( function() {
					var notContained = !$.contains(
						this.element[ 0 ],
						$.ui.safeActiveElement( this.document[ 0 ] )
					);
					if ( notContained ) {
						this.collapseAll( event );
					}
				} );
			},
			keydown: "_keydown"
		} );

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event, true );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		} );
	},

	_activateItem: function( event ) {

		// Ignore mouse events while typeahead is active, see #10458.
		// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
		// is over an item in the menu
		if ( this.previousFilter ) {
			return;
		}

		// If the mouse didn't actually move, but the page was scrolled, ignore the event (#9356)
		if ( event.clientX === this.lastMousePosition.x &&
				event.clientY === this.lastMousePosition.y ) {
			return;
		}

		this.lastMousePosition = {
			x: event.clientX,
			y: event.clientY
		};

		var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
			target = $( event.currentTarget );

		// Ignore bubbled events on parent items, see #11641
		if ( actualTarget[ 0 ] !== target[ 0 ] ) {
			return;
		}

		// If the item is already active, there's nothing to do
		if ( target.is( ".ui-state-active" ) ) {
			return;
		}

		// Remove ui-state-active class from siblings of the newly focused menu item
		// to avoid a jump caused by adjacent elements both having a class with a border
		this._removeClass( target.siblings().children( ".ui-state-active" ),
			null, "ui-state-active" );
		this.focus( event, target );
	},

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			skip = false;

			// Support number pad values
			character = event.keyCode >= 96 && event.keyCode <= 105 ?
				( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay( function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items, newSubmenus, newItems, newWrappers,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each( function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				that._addClass( item, "ui-menu-divider", "ui-widget-content" );
			}
		} );

		// Don't refresh list items that are already adapted
		newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
		newWrappers = newItems.children()
			.not( ".ui-menu" )
				.uniqueId()
				.attr( {
					tabIndex: -1,
					role: this._itemRole()
				} );
		this._addClass( newItems, "ui-menu-item" )
			._addClass( newWrappers, "ui-menu-item-wrapper" );

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	focus: function( event, item ) {
		var nested, focused, activeParent;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening( nested );
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

		this._trigger( "blur", event, { item: this.active } );
		this.active = null;
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the caret icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay( function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend( {
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all
			// sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, all ? 0 : this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active && this._menuItems( this.active.children( ".ui-menu" ) ).first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay( function() {
				this.focus( event, newItem );
			} );
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_menuItems: function( menu ) {
		return ( menu || this.element )
			.find( this.options.items )
			.filter( ".ui-menu-item" );
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.last();
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.first();
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this._menuItems( this.activeMenu )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.innerHeight();

			// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
			if ( $.fn.jquery.indexOf( "3.2." ) === 0 ) {
				height += this.element[ 0 ].offsetHeight - this.element.outerHeight();
			}

			this.active.nextAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this._menuItems( this.activeMenu )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.innerHeight();

			// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
			if ( $.fn.jquery.indexOf( "3.2." ) === 0 ) {
				height += this.element[ 0 ].offsetHeight - this.element.outerHeight();
			}

			this.active.prevAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this._menuItems( this.activeMenu ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {

		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function( character ) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

				// Only match on items, not dividers or other content (#10571)
				.filter( ".ui-menu-item" )
					.filter( function() {
						return regex.test(
							String.prototype.trim.call(
								$( this ).children( ".ui-menu-item-wrapper" ).text() ) );
					} );
	}
} );

} );







/*!
 * jQuery UI Autocomplete 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: http://api.jqueryui.com/autocomplete/
//>>demos: http://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./menu",
			"../keycode",
			"../position",
			"../safe-active-element",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.autocomplete", {
	version: "1.13.0",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {

		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// IE also treats inputs as contentEditable
		// All other element types are determined by whether or not they're contentEditable
		this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this._addClass( "ui-autocomplete-input" );
		this.element.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// Replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		} );

		this._initSource();
		this.menu = $( "<ul>" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()

			// Support: IE 11 only, Edge <= 14
			// For other browsers, we preventDefault() on the mousedown event
			// to keep the dropdown from taking focus from the input. This doesn't
			// work for IE/Edge, causing problems with selection and scrolling (#9638)
			// Happily, IE and Edge support an "unselectable" attribute that
			// prevents an element from receiving focus, exactly what we want here.
			.attr( {
				"unselectable": "on"
			} )
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// Prevent moving focus out of the text field
				event.preventDefault();
			},
			menufocus: function( event, ui ) {
				var label, item;

				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						} );

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && String.prototype.trim.call( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
					this.element.trigger( "focus" );
					this.previous = previous;

					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay( function() {
						this.previous = previous;
						this.selectedItem = item;
					} );
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		} );

		this.liveRegion = $( "<div>", {
			role: "status",
			"aria-live": "assertive",
			"aria-relevant": "additions"
		} )
			.appendTo( this.document[ 0 ].body );

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( Array.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay( function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// Always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this._addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this._removeClass( "ui-autocomplete-loading" );
			}
		}.bind( this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {

		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			} );
		} );
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// Size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend( {
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" )
			.append( $( "<div>" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// Prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	},

	// Support: Chrome <=50
	// We should be able to just use this.element.prop( "isContentEditable" )
	// but hidden elements always report false in Chrome.
	// https://code.google.com/p/chromium/issues/detail?id=313082
	_isContentEditable: function( element ) {
		if ( !element.length ) {
			return false;
		}

		var editable = element.prop( "contentEditable" );

		if ( editable === "inherit" ) {
			return this._isContentEditable( element.parent() );
		}

		return editable === "true";
	}
} );

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	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.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
} );

return $.ui.autocomplete;

} );


/*!
 * jQuery UI Controlgroup 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Controlgroup
//>>group: Widgets
//>>description: Visually groups form control widgets
//>>docs: http://api.jqueryui.com/controlgroup/
//>>demos: http://jqueryui.com/controlgroup/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/controlgroup.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;

return $.widget( "ui.controlgroup", {
	version: "1.13.0",
	defaultElement: "<div>",
	options: {
		direction: "horizontal",
		disabled: null,
		onlyVisible: true,
		items: {
			"button": "input[type=button], input[type=submit], input[type=reset], button, a",
			"controlgroupLabel": ".ui-controlgroup-label",
			"checkboxradio": "input[type='checkbox'], input[type='radio']",
			"selectmenu": "select",
			"spinner": ".ui-spinner-input"
		}
	},

	_create: function() {
		this._enhance();
	},

	// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
	_enhance: function() {
		this.element.attr( "role", "toolbar" );
		this.refresh();
	},

	_destroy: function() {
		this._callChildMethod( "destroy" );
		this.childWidgets.removeData( "ui-controlgroup-data" );
		this.element.removeAttr( "role" );
		if ( this.options.items.controlgroupLabel ) {
			this.element
				.find( this.options.items.controlgroupLabel )
				.find( ".ui-controlgroup-label-contents" )
				.contents().unwrap();
		}
	},

	_initWidgets: function() {
		var that = this,
			childWidgets = [];

		// First we iterate over each of the items options
		$.each( this.options.items, function( widget, selector ) {
			var labels;
			var options = {};

			// Make sure the widget has a selector set
			if ( !selector ) {
				return;
			}

			if ( widget === "controlgroupLabel" ) {
				labels = that.element.find( selector );
				labels.each( function() {
					var element = $( this );

					if ( element.children( ".ui-controlgroup-label-contents" ).length ) {
						return;
					}
					element.contents()
						.wrapAll( "<span class='ui-controlgroup-label-contents'></span>" );
				} );
				that._addClass( labels, null, "ui-widget ui-widget-content ui-state-default" );
				childWidgets = childWidgets.concat( labels.get() );
				return;
			}

			// Make sure the widget actually exists
			if ( !$.fn[ widget ] ) {
				return;
			}

			// We assume everything is in the middle to start because we can't determine
			// first / last elements until all enhancments are done.
			if ( that[ "_" + widget + "Options" ] ) {
				options = that[ "_" + widget + "Options" ]( "middle" );
			} else {
				options = { classes: {} };
			}

			// Find instances of this widget inside controlgroup and init them
			that.element
				.find( selector )
				.each( function() {
					var element = $( this );
					var instance = element[ widget ]( "instance" );

					// We need to clone the default options for this type of widget to avoid
					// polluting the variable options which has a wider scope than a single widget.
					var instanceOptions = $.widget.extend( {}, options );

					// If the button is the child of a spinner ignore it
					// TODO: Find a more generic solution
					if ( widget === "button" && element.parent( ".ui-spinner" ).length ) {
						return;
					}

					// Create the widget if it doesn't exist
					if ( !instance ) {
						instance = element[ widget ]()[ widget ]( "instance" );
					}
					if ( instance ) {
						instanceOptions.classes =
							that._resolveClassesValues( instanceOptions.classes, instance );
					}
					element[ widget ]( instanceOptions );

					// Store an instance of the controlgroup to be able to reference
					// from the outermost element for changing options and refresh
					var widgetElement = element[ widget ]( "widget" );
					$.data( widgetElement[ 0 ], "ui-controlgroup-data",
						instance ? instance : element[ widget ]( "instance" ) );

					childWidgets.push( widgetElement[ 0 ] );
				} );
		} );

		this.childWidgets = $( $.uniqueSort( childWidgets ) );
		this._addClass( this.childWidgets, "ui-controlgroup-item" );
	},

	_callChildMethod: function( method ) {
		this.childWidgets.each( function() {
			var element = $( this ),
				data = element.data( "ui-controlgroup-data" );
			if ( data && data[ method ] ) {
				data[ method ]();
			}
		} );
	},

	_updateCornerClass: function( element, position ) {
		var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
		var add = this._buildSimpleOptions( position, "label" ).classes.label;

		this._removeClass( element, null, remove );
		this._addClass( element, null, add );
	},

	_buildSimpleOptions: function( position, key ) {
		var direction = this.options.direction === "vertical";
		var result = {
			classes: {}
		};
		result.classes[ key ] = {
			"middle": "",
			"first": "ui-corner-" + ( direction ? "top" : "left" ),
			"last": "ui-corner-" + ( direction ? "bottom" : "right" ),
			"only": "ui-corner-all"
		}[ position ];

		return result;
	},

	_spinnerOptions: function( position ) {
		var options = this._buildSimpleOptions( position, "ui-spinner" );

		options.classes[ "ui-spinner-up" ] = "";
		options.classes[ "ui-spinner-down" ] = "";

		return options;
	},

	_buttonOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-button" );
	},

	_checkboxradioOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-checkboxradio-label" );
	},

	_selectmenuOptions: function( position ) {
		var direction = this.options.direction === "vertical";
		return {
			width: direction ? "auto" : false,
			classes: {
				middle: {
					"ui-selectmenu-button-open": "",
					"ui-selectmenu-button-closed": ""
				},
				first: {
					"ui-selectmenu-button-open": "ui-corner-" + ( direction ? "top" : "tl" ),
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "top" : "left" )
				},
				last: {
					"ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "bottom" : "right" )
				},
				only: {
					"ui-selectmenu-button-open": "ui-corner-top",
					"ui-selectmenu-button-closed": "ui-corner-all"
				}

			}[ position ]
		};
	},

	_resolveClassesValues: function( classes, instance ) {
		var result = {};
		$.each( classes, function( key ) {
			var current = instance.options.classes[ key ] || "";
			current = String.prototype.trim.call( current.replace( controlgroupCornerRegex, "" ) );
			result[ key ] = ( current + " " + classes[ key ] ).replace( /\s+/g, " " );
		} );
		return result;
	},

	_setOption: function( key, value ) {
		if ( key === "direction" ) {
			this._removeClass( "ui-controlgroup-" + this.options.direction );
		}

		this._super( key, value );
		if ( key === "disabled" ) {
			this._callChildMethod( value ? "disable" : "enable" );
			return;
		}

		this.refresh();
	},

	refresh: function() {
		var children,
			that = this;

		this._addClass( "ui-controlgroup ui-controlgroup-" + this.options.direction );

		if ( this.options.direction === "horizontal" ) {
			this._addClass( null, "ui-helper-clearfix" );
		}
		this._initWidgets();

		children = this.childWidgets;

		// We filter here because we need to track all childWidgets not just the visible ones
		if ( this.options.onlyVisible ) {
			children = children.filter( ":visible" );
		}

		if ( children.length ) {

			// We do this last because we need to make sure all enhancment is done
			// before determining first and last
			$.each( [ "first", "last" ], function( index, value ) {
				var instance = children[ value ]().data( "ui-controlgroup-data" );

				if ( instance && that[ "_" + instance.widgetName + "Options" ] ) {
					var options = that[ "_" + instance.widgetName + "Options" ](
						children.length === 1 ? "only" : value
					);
					options.classes = that._resolveClassesValues( options.classes, instance );
					instance.element[ instance.widgetName ]( options );
				} else {
					that._updateCornerClass( children[ value ](), value );
				}
			} );

			// Finally call the refresh method on each of the child widgets.
			this._callChildMethod( "refresh" );
		}
	}
} );
} );




/*!
 * jQuery UI Checkboxradio 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Checkboxradio
//>>group: Widgets
//>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
//>>docs: http://api.jqueryui.com/checkboxradio/
//>>demos: http://jqueryui.com/checkboxradio/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.structure: ../../themes/base/checkboxradio.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../form-reset-mixin",
			"../labels",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.checkboxradio", [ $.ui.formResetMixin, {
	version: "1.13.0",
	options: {
		disabled: null,
		label: null,
		icon: true,
		classes: {
			"ui-checkboxradio-label": "ui-corner-all",
			"ui-checkboxradio-icon": "ui-corner-all"
		}
	},

	_getCreateOptions: function() {
		var disabled, labels;
		var that = this;
		var options = this._super() || {};

		// We read the type here, because it makes more sense to throw a element type error first,
		// rather then the error for lack of a label. Often if its the wrong type, it
		// won't have a label (e.g. calling on a div, btn, etc)
		this._readType();

		labels = this.element.labels();

		// If there are multiple labels, use the last one
		this.label = $( labels[ labels.length - 1 ] );
		if ( !this.label.length ) {
			$.error( "No label found for checkboxradio widget" );
		}

		this.originalLabel = "";

		// We need to get the label text but this may also need to make sure it does not contain the
		// input itself.
		this.label.contents().not( this.element[ 0 ] ).each( function() {

			// The label contents could be text, html, or a mix. We concat each element to get a
			// string representation of the label, without the input as part of it.
			that.originalLabel += this.nodeType === 3 ? $( this ).text() : this.outerHTML;
		} );

		// Set the label option if we found label text
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}
		return options;
	},

	_create: function() {
		var checked = this.element[ 0 ].checked;

		this._bindFormResetHandler();

		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled;
		}

		this._setOption( "disabled", this.options.disabled );
		this._addClass( "ui-checkboxradio", "ui-helper-hidden-accessible" );
		this._addClass( this.label, "ui-checkboxradio-label", "ui-button ui-widget" );

		if ( this.type === "radio" ) {
			this._addClass( this.label, "ui-checkboxradio-radio-label" );
		}

		if ( this.options.label && this.options.label !== this.originalLabel ) {
			this._updateLabel();
		} else if ( this.originalLabel ) {
			this.options.label = this.originalLabel;
		}

		this._enhance();

		if ( checked ) {
			this._addClass( this.label, "ui-checkboxradio-checked", "ui-state-active" );
		}

		this._on( {
			change: "_toggleClasses",
			focus: function() {
				this._addClass( this.label, null, "ui-state-focus ui-visual-focus" );
			},
			blur: function() {
				this._removeClass( this.label, null, "ui-state-focus ui-visual-focus" );
			}
		} );
	},

	_readType: function() {
		var nodeName = this.element[ 0 ].nodeName.toLowerCase();
		this.type = this.element[ 0 ].type;
		if ( nodeName !== "input" || !/radio|checkbox/.test( this.type ) ) {
			$.error( "Can't create checkboxradio on element.nodeName=" + nodeName +
				" and element.type=" + this.type );
		}
	},

	// Support jQuery Mobile enhanced option
	_enhance: function() {
		this._updateIcon( this.element[ 0 ].checked );
	},

	widget: function() {
		return this.label;
	},

	_getRadioGroup: function() {
		var group;
		var name = this.element[ 0 ].name;
		var nameSelector = "input[name='" + $.escapeSelector( name ) + "']";

		if ( !name ) {
			return $( [] );
		}

		if ( this.form.length ) {
			group = $( this.form[ 0 ].elements ).filter( nameSelector );
		} else {

			// Not inside a form, check all inputs that also are not inside a form
			group = $( nameSelector ).filter( function() {
				return $( this )._form().length === 0;
			} );
		}

		return group.not( this.element );
	},

	_toggleClasses: function() {
		var checked = this.element[ 0 ].checked;
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );

		if ( this.options.icon && this.type === "checkbox" ) {
			this._toggleClass( this.icon, null, "ui-icon-check ui-state-checked", checked )
				._toggleClass( this.icon, null, "ui-icon-blank", !checked );
		}

		if ( this.type === "radio" ) {
			this._getRadioGroup()
				.each( function() {
					var instance = $( this ).checkboxradio( "instance" );

					if ( instance ) {
						instance._removeClass( instance.label,
							"ui-checkboxradio-checked", "ui-state-active" );
					}
				} );
		}
	},

	_destroy: function() {
		this._unbindFormResetHandler();

		if ( this.icon ) {
			this.icon.remove();
			this.iconSpace.remove();
		}
	},

	_setOption: function( key, value ) {

		// We don't allow the value to be set to nothing
		if ( key === "label" && !value ) {
			return;
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( this.label, null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;

			// Don't refresh when setting disabled
			return;
		}
		this.refresh();
	},

	_updateIcon: function( checked ) {
		var toAdd = "ui-icon ui-icon-background ";

		if ( this.options.icon ) {
			if ( !this.icon ) {
				this.icon = $( "<span>" );
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-checkboxradio-icon-space" );
			}

			if ( this.type === "checkbox" ) {
				toAdd += checked ? "ui-icon-check ui-state-checked" : "ui-icon-blank";
				this._removeClass( this.icon, null, checked ? "ui-icon-blank" : "ui-icon-check" );
			} else {
				toAdd += "ui-icon-blank";
			}
			this._addClass( this.icon, "ui-checkboxradio-icon", toAdd );
			if ( !checked ) {
				this._removeClass( this.icon, null, "ui-icon-check ui-state-checked" );
			}
			this.icon.prependTo( this.label ).after( this.iconSpace );
		} else if ( this.icon !== undefined ) {
			this.icon.remove();
			this.iconSpace.remove();
			delete this.icon;
		}
	},

	_updateLabel: function() {

		// Remove the contents of the label ( minus the icon, icon space, and input )
		var contents = this.label.contents().not( this.element[ 0 ] );
		if ( this.icon ) {
			contents = contents.not( this.icon[ 0 ] );
		}
		if ( this.iconSpace ) {
			contents = contents.not( this.iconSpace[ 0 ] );
		}
		contents.remove();

		this.label.append( this.options.label );
	},

	refresh: function() {
		var checked = this.element[ 0 ].checked,
			isDisabled = this.element[ 0 ].disabled;

		this._updateIcon( checked );
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );
		if ( this.options.label !== null ) {
			this._updateLabel();
		}

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { "disabled": isDisabled } );
		}
	}

} ] );

return $.ui.checkboxradio;

} );





/*!
 * jQuery UI Button 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Button
//>>group: Widgets
//>>description: Enhances a form with themeable buttons.
//>>docs: http://api.jqueryui.com/button/
//>>demos: http://jqueryui.com/button/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",

			// These are only for backcompat
			// TODO: Remove after 1.12
			"./controlgroup",
			"./checkboxradio",

			"../keycode",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.button", {
	version: "1.13.0",
	defaultElement: "<button>",
	options: {
		classes: {
			"ui-button": "ui-corner-all"
		},
		disabled: null,
		icon: null,
		iconPosition: "beginning",
		label: null,
		showLabel: true
	},

	_getCreateOptions: function() {
		var disabled,

			// This is to support cases like in jQuery Mobile where the base widget does have
			// an implementation of _getCreateOptions
			options = this._super() || {};

		this.isInput = this.element.is( "input" );

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}

		this.originalLabel = this.isInput ? this.element.val() : this.element.html();
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		return options;
	},

	_create: function() {
		if ( !this.option.showLabel & !this.options.icon ) {
			this.options.showLabel = true;
		}

		// We have to check the option again here even though we did in _getCreateOptions,
		// because null may have been passed on init which would override what was set in
		// _getCreateOptions
		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled || false;
		}

		this.hasTitle = !!this.element.attr( "title" );

		// Check to see if the label needs to be set or if its already correct
		if ( this.options.label && this.options.label !== this.originalLabel ) {
			if ( this.isInput ) {
				this.element.val( this.options.label );
			} else {
				this.element.html( this.options.label );
			}
		}
		this._addClass( "ui-button", "ui-widget" );
		this._setOption( "disabled", this.options.disabled );
		this._enhance();

		if ( this.element.is( "a" ) ) {
			this._on( {
				"keyup": function( event ) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						event.preventDefault();

						// Support: PhantomJS <= 1.9, IE 8 Only
						// If a native click is available use it so we actually cause navigation
						// otherwise just trigger a click event
						if ( this.element[ 0 ].click ) {
							this.element[ 0 ].click();
						} else {
							this.element.trigger( "click" );
						}
					}
				}
			} );
		}
	},

	_enhance: function() {
		if ( !this.element.is( "button" ) ) {
			this.element.attr( "role", "button" );
		}

		if ( this.options.icon ) {
			this._updateIcon( "icon", this.options.icon );
			this._updateTooltip();
		}
	},

	_updateTooltip: function() {
		this.title = this.element.attr( "title" );

		if ( !this.options.showLabel && !this.title ) {
			this.element.attr( "title", this.options.label );
		}
	},

	_updateIcon: function( option, value ) {
		var icon = option !== "iconPosition",
			position = icon ? this.options.iconPosition : value,
			displayBlock = position === "top" || position === "bottom";

		// Create icon
		if ( !this.icon ) {
			this.icon = $( "<span>" );

			this._addClass( this.icon, "ui-button-icon", "ui-icon" );

			if ( !this.options.showLabel ) {
				this._addClass( "ui-button-icon-only" );
			}
		} else if ( icon ) {

			// If we are updating the icon remove the old icon class
			this._removeClass( this.icon, null, this.options.icon );
		}

		// If we are updating the icon add the new icon class
		if ( icon ) {
			this._addClass( this.icon, null, value );
		}

		this._attachIcon( position );

		// If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
		// the iconSpace if there is one.
		if ( displayBlock ) {
			this._addClass( this.icon, null, "ui-widget-icon-block" );
			if ( this.iconSpace ) {
				this.iconSpace.remove();
			}
		} else {

			// Position is beginning or end so remove the ui-widget-icon-block class and add the
			// space if it does not exist
			if ( !this.iconSpace ) {
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-button-icon-space" );
			}
			this._removeClass( this.icon, null, "ui-wiget-icon-block" );
			this._attachIconSpace( position );
		}
	},

	_destroy: function() {
		this.element.removeAttr( "role" );

		if ( this.icon ) {
			this.icon.remove();
		}
		if ( this.iconSpace ) {
			this.iconSpace.remove();
		}
		if ( !this.hasTitle ) {
			this.element.removeAttr( "title" );
		}
	},

	_attachIconSpace: function( iconPosition ) {
		this.icon[ /^(?:end|bottom)/.test( iconPosition ) ? "before" : "after" ]( this.iconSpace );
	},

	_attachIcon: function( iconPosition ) {
		this.element[ /^(?:end|bottom)/.test( iconPosition ) ? "append" : "prepend" ]( this.icon );
	},

	_setOptions: function( options ) {
		var newShowLabel = options.showLabel === undefined ?
				this.options.showLabel :
				options.showLabel,
			newIcon = options.icon === undefined ? this.options.icon : options.icon;

		if ( !newShowLabel && !newIcon ) {
			options.showLabel = true;
		}
		this._super( options );
	},

	_setOption: function( key, value ) {
		if ( key === "icon" ) {
			if ( value ) {
				this._updateIcon( key, value );
			} else if ( this.icon ) {
				this.icon.remove();
				if ( this.iconSpace ) {
					this.iconSpace.remove();
				}
			}
		}

		if ( key === "iconPosition" ) {
			this._updateIcon( key, value );
		}

		// Make sure we can't end up with a button that has neither text nor icon
		if ( key === "showLabel" ) {
				this._toggleClass( "ui-button-icon-only", null, !value );
				this._updateTooltip();
		}

		if ( key === "label" ) {
			if ( this.isInput ) {
				this.element.val( value );
			} else {

				// If there is an icon, append it, else nothing then append the value
				// this avoids removal of the icon when setting label text
				this.element.html( value );
				if ( this.icon ) {
					this._attachIcon( this.options.iconPosition );
					this._attachIconSpace( this.options.iconPosition );
				}
			}
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;
			if ( value ) {
				this.element.trigger( "blur" );
			}
		}
	},

	refresh: function() {

		// Make sure to only check disabled if its an element that supports this otherwise
		// check for the disabled class to determine state
		var isDisabled = this.element.is( "input, button" ) ?
			this.element[ 0 ].disabled : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { disabled: isDisabled } );
		}

		this._updateTooltip();
	}
} );

// DEPRECATED
if ( $.uiBackCompat !== false ) {

	// Text and Icons options
	$.widget( "ui.button", $.ui.button, {
		options: {
			text: true,
			icons: {
				primary: null,
				secondary: null
			}
		},

		_create: function() {
			if ( this.options.showLabel && !this.options.text ) {
				this.options.showLabel = this.options.text;
			}
			if ( !this.options.showLabel && this.options.text ) {
				this.options.text = this.options.showLabel;
			}
			if ( !this.options.icon && ( this.options.icons.primary ||
					this.options.icons.secondary ) ) {
				if ( this.options.icons.primary ) {
					this.options.icon = this.options.icons.primary;
				} else {
					this.options.icon = this.options.icons.secondary;
					this.options.iconPosition = "end";
				}
			} else if ( this.options.icon ) {
				this.options.icons.primary = this.options.icon;
			}
			this._super();
		},

		_setOption: function( key, value ) {
			if ( key === "text" ) {
				this._super( "showLabel", value );
				return;
			}
			if ( key === "showLabel" ) {
				this.options.text = value;
			}
			if ( key === "icon" ) {
				this.options.icons.primary = value;
			}
			if ( key === "icons" ) {
				if ( value.primary ) {
					this._super( "icon", value.primary );
					this._super( "iconPosition", "beginning" );
				} else if ( value.secondary ) {
					this._super( "icon", value.secondary );
					this._super( "iconPosition", "end" );
				}
			}
			this._superApply( arguments );
		}
	} );

	$.fn.button = ( function( orig ) {
		return function( options ) {
			var isMethodCall = typeof options === "string";
			var args = Array.prototype.slice.call( arguments, 1 );
			var returnValue = this;

			if ( isMethodCall ) {

				// If this is an empty collection, we need to have the instance method
				// return undefined instead of the jQuery instance
				if ( !this.length && options === "instance" ) {
					returnValue = undefined;
				} else {
					this.each( function() {
						var methodValue;
						var type = $( this ).attr( "type" );
						var name = type !== "checkbox" && type !== "radio" ?
							"button" :
							"checkboxradio";
						var instance = $.data( this, "ui-" + name );

						if ( options === "instance" ) {
							returnValue = instance;
							return false;
						}

						if ( !instance ) {
							return $.error( "cannot call methods on button" +
								" prior to initialization; " +
								"attempted to call method '" + options + "'" );
						}

						if ( typeof instance[ options ] !== "function" ||
							options.charAt( 0 ) === "_" ) {
							return $.error( "no such method '" + options + "' for button" +
								" widget instance" );
						}

						methodValue = instance[ options ].apply( instance, args );

						if ( methodValue !== instance && methodValue !== undefined ) {
							returnValue = methodValue && methodValue.jquery ?
								returnValue.pushStack( methodValue.get() ) :
								methodValue;
							return false;
						}
					} );
				}
			} else {

				// Allow multiple hashes to be passed on init
				if ( args.length ) {
					options = $.widget.extend.apply( null, [ options ].concat( args ) );
				}

				this.each( function() {
					var type = $( this ).attr( "type" );
					var name = type !== "checkbox" && type !== "radio" ? "button" : "checkboxradio";
					var instance = $.data( this, "ui-" + name );

					if ( instance ) {
						instance.option( options || {} );
						if ( instance._init ) {
							instance._init();
						}
					} else {
						if ( name === "button" ) {
							orig.call( $( this ), options );
							return;
						}

						$( this ).checkboxradio( $.extend( { icon: false }, options ) );
					}
				} );
			}

			return returnValue;
		};
	} )( $.fn.button );

	$.fn.buttonset = function() {
		if ( !$.ui.controlgroup ) {
			$.error( "Controlgroup widget missing" );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" && arguments[ 2 ] ) {
			return this.controlgroup.apply( this,
				[ arguments[ 0 ], "items.button", arguments[ 2 ] ] );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" ) {
			return this.controlgroup.apply( this, [ arguments[ 0 ], "items.button" ] );
		}
		if ( typeof arguments[ 0 ] === "object" && arguments[ 0 ].items ) {
			arguments[ 0 ].items = {
				button: arguments[ 0 ].items
			};
		}
		return this.controlgroup.apply( this, arguments );
	};
}

return $.ui.button;

} );



/* eslint-disable max-len, camelcase */
/*!
 * jQuery UI Datepicker 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Datepicker
//>>group: Widgets
//>>description: Displays a calendar from an input or inline for selecting dates.
//>>docs: http://api.jqueryui.com/datepicker/
//>>demos: http://jqueryui.com/datepicker/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/datepicker.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../keycode"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.extend( $.ui, { datepicker: { version: "1.13.0" } } );

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {

		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {

			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[ "" ] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: [ "January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December" ], // Names of months for drop-down and formatting
		monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
		dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
		dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
		dayNamesMin: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "", // Additional text to append to the year in the month headers,
		selectMonthLabel: "Select month", // Invisible label for month selector
		selectYearLabel: "Select year" // Invisible label for year selector
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		onUpdateDatepicker: null, // Define a callback function when the datepicker is updated
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend( this._defaults, this.regional[ "" ] );
	this.regional.en = $.extend( true, {}, this.regional[ "" ] );
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
}

$.extend( Datepicker.prototype, {

	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function( settings ) {
		datepicker_extendRemove( this._defaults, settings || {} );
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function( target, settings ) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = ( nodeName === "div" || nodeName === "span" );
		if ( !target.id ) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst( $( target ), inline );
		inst.settings = $.extend( {}, settings || {} );
		if ( nodeName === "input" ) {
			this._connectDatepicker( target, inst );
		} else if ( inline ) {
			this._inlineDatepicker( target, inst );
		}
	},

	/* Create a new instance object. */
	_newInst: function( target, inline ) {
		var id = target[ 0 ].id.replace( /([^A-Za-z0-9_\-])/g, "\\\\$1" ); // escape jQuery meta chars
		return { id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: ( !inline ? this.dpDiv : // presentation div
			datepicker_bindHover( $( "<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) ) ) };
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function( target, inst ) {
		var input = $( target );
		inst.append = $( [] );
		inst.trigger = $( [] );
		if ( input.hasClass( this.markerClassName ) ) {
			return;
		}
		this._attachments( input, inst );
		input.addClass( this.markerClassName ).on( "keydown", this._doKeyDown ).
			on( "keypress", this._doKeyPress ).on( "keyup", this._doKeyUp );
		this._autoSize( inst );
		$.data( target, "datepicker", inst );

		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function( input, inst ) {
		var showOn, buttonText, buttonImage,
			appendText = this._get( inst, "appendText" ),
			isRTL = this._get( inst, "isRTL" );

		if ( inst.append ) {
			inst.append.remove();
		}
		if ( appendText ) {
			inst.append = $( "<span>" )
				.addClass( this._appendClass )
				.text( appendText );
			input[ isRTL ? "before" : "after" ]( inst.append );
		}

		input.off( "focus", this._showDatepicker );

		if ( inst.trigger ) {
			inst.trigger.remove();
		}

		showOn = this._get( inst, "showOn" );
		if ( showOn === "focus" || showOn === "both" ) { // pop-up date picker when in the marked field
			input.on( "focus", this._showDatepicker );
		}
		if ( showOn === "button" || showOn === "both" ) { // pop-up date picker when button clicked
			buttonText = this._get( inst, "buttonText" );
			buttonImage = this._get( inst, "buttonImage" );

			if ( this._get( inst, "buttonImageOnly" ) ) {
				inst.trigger = $( "<img>" )
					.addClass( this._triggerClass )
					.attr( {
						src: buttonImage,
						alt: buttonText,
						title: buttonText
					} );
			} else {
				inst.trigger = $( "<button type='button'>" )
					.addClass( this._triggerClass );
				if ( buttonImage ) {
					inst.trigger.html(
						$( "<img>" )
							.attr( {
								src: buttonImage,
								alt: buttonText,
								title: buttonText
							} )
					);
				} else {
					inst.trigger.text( buttonText );
				}
			}

			input[ isRTL ? "before" : "after" ]( inst.trigger );
			inst.trigger.on( "click", function() {
				if ( $.datepicker._datepickerShowing && $.datepicker._lastInput === input[ 0 ] ) {
					$.datepicker._hideDatepicker();
				} else if ( $.datepicker._datepickerShowing && $.datepicker._lastInput !== input[ 0 ] ) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker( input[ 0 ] );
				} else {
					$.datepicker._showDatepicker( input[ 0 ] );
				}
				return false;
			} );
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function( inst ) {
		if ( this._get( inst, "autoSize" ) && !inst.inline ) {
			var findMax, max, maxI, i,
				date = new Date( 2009, 12 - 1, 20 ), // Ensure double digits
				dateFormat = this._get( inst, "dateFormat" );

			if ( dateFormat.match( /[DM]/ ) ) {
				findMax = function( names ) {
					max = 0;
					maxI = 0;
					for ( i = 0; i < names.length; i++ ) {
						if ( names[ i ].length > max ) {
							max = names[ i ].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth( findMax( this._get( inst, ( dateFormat.match( /MM/ ) ?
					"monthNames" : "monthNamesShort" ) ) ) );
				date.setDate( findMax( this._get( inst, ( dateFormat.match( /DD/ ) ?
					"dayNames" : "dayNamesShort" ) ) ) + 20 - date.getDay() );
			}
			inst.input.attr( "size", this._formatDate( inst, date ).length );
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function( target, inst ) {
		var divSpan = $( target );
		if ( divSpan.hasClass( this.markerClassName ) ) {
			return;
		}
		divSpan.addClass( this.markerClassName ).append( inst.dpDiv );
		$.data( target, "datepicker", inst );
		this._setDate( inst, this._getDefaultDate( inst ), true );
		this._updateDatepicker( inst );
		this._updateAlternate( inst );

		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if ( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}

		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// 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.on( "keydown", this._doKeyDown );
			$( "body" ).append( this._dialogInput );
			inst = this._dialogInst = this._newInst( this._dialogInput, false );
			inst.settings = {};
			$.data( this._dialogInput[ 0 ], "datepicker", inst );
		}
		datepicker_extendRemove( inst.settings, settings || {} );
		date = ( date && date.constructor === Date ? this._formatDate( inst, date ) : date );
		this._dialogInput.val( date );

		this._pos = ( pos ? ( pos.length ? pos : [ pos.pageX, pos.pageY ] ) : null );
		if ( !this._pos ) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[ ( browserWidth / 2 ) - 100 + scrollX, ( browserHeight / 2 ) - 150 + scrollY ];
		}

		// Move input on screen for focus, but hidden behind dialog
		this._dialogInput.css( "left", ( this._pos[ 0 ] + 20 ) + "px" ).css( "top", this._pos[ 1 ] + "px" );
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass( this._dialogClass );
		this._showDatepicker( this._dialogInput[ 0 ] );
		if ( $.blockUI ) {
			$.blockUI( this.dpDiv );
		}
		$.data( this._dialogInput[ 0 ], "datepicker", inst );
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function( target ) {
		var nodeName,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData( target, "datepicker" );
		if ( nodeName === "input" ) {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass( this.markerClassName ).
				off( "focus", this._showDatepicker ).
				off( "keydown", this._doKeyDown ).
				off( "keypress", this._doKeyPress ).
				off( "keyup", this._doKeyUp );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			$target.removeClass( this.markerClassName ).empty();
		}

		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
			this._curInst = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = false;
			inst.trigger.filter( "button" ).
				each( function() {
					this.disabled = false;
				} ).end().
				filter( "img" ).css( { opacity: "1.0", cursor: "" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().removeClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", false );
		}
		this._disabledInputs = $.map( this._disabledInputs,

			// Delete entry
			function( value ) {
				return ( value === target ? null : value );
			} );
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function( target ) {
		var nodeName, inline,
			$target = $( target ),
			inst = $.data( target, "datepicker" );

		if ( !$target.hasClass( this.markerClassName ) ) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if ( nodeName === "input" ) {
			target.disabled = true;
			inst.trigger.filter( "button" ).
				each( function() {
					this.disabled = true;
				} ).end().
				filter( "img" ).css( { opacity: "0.5", cursor: "default" } );
		} else if ( nodeName === "div" || nodeName === "span" ) {
			inline = $target.children( "." + this._inlineClass );
			inline.children().addClass( "ui-state-disabled" );
			inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
				prop( "disabled", true );
		}
		this._disabledInputs = $.map( this._disabledInputs,

			// Delete entry
			function( value ) {
				return ( value === target ? null : value );
			} );
		this._disabledInputs[ this._disabledInputs.length ] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function( target ) {
		if ( !target ) {
			return false;
		}
		for ( var i = 0; i < this._disabledInputs.length; i++ ) {
			if ( this._disabledInputs[ i ] === target ) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function( target ) {
		try {
			return $.data( target, "datepicker" );
		} catch ( err ) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function( target, name, value ) {
		var settings, date, minDate, maxDate,
			inst = this._getInst( target );

		if ( arguments.length === 2 && typeof name === "string" ) {
			return ( name === "defaults" ? $.extend( {}, $.datepicker._defaults ) :
				( inst ? ( name === "all" ? $.extend( {}, inst.settings ) :
				this._get( inst, name ) ) : null ) );
		}

		settings = name || {};
		if ( typeof name === "string" ) {
			settings = {};
			settings[ name ] = value;
		}

		if ( inst ) {
			if ( this._curInst === inst ) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker( target, true );
			minDate = this._getMinMaxDate( inst, "min" );
			maxDate = this._getMinMaxDate( inst, "max" );
			datepicker_extendRemove( inst.settings, settings );

			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if ( minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined ) {
				inst.settings.minDate = this._formatDate( inst, minDate );
			}
			if ( maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined ) {
				inst.settings.maxDate = this._formatDate( inst, maxDate );
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker( target );
				} else {
					this._enableDatepicker( target );
				}
			}
			this._attachments( $( target ), inst );
			this._autoSize( inst );
			this._setDate( inst, date );
			this._updateAlternate( inst );
			this._updateDatepicker( inst );
		}
	},

	// Change method deprecated
	_changeDatepicker: function( target, name, value ) {
		this._optionDatepicker( target, name, value );
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function( target ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._updateDatepicker( inst );
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function( target, date ) {
		var inst = this._getInst( target );
		if ( inst ) {
			this._setDate( inst, date );
			this._updateDatepicker( inst );
			this._updateAlternate( inst );
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function( target, noDefault ) {
		var inst = this._getInst( target );
		if ( inst && !inst.inline ) {
			this._setDateFromField( inst, noDefault );
		}
		return ( inst ? this._getDate( inst ) : null );
	},

	/* Handle keystrokes. */
	_doKeyDown: function( event ) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst( event.target ),
			handled = true,
			isRTL = inst.dpDiv.is( ".ui-datepicker-rtl" );

		inst._keyEvent = true;
		if ( $.datepicker._datepickerShowing ) {
			switch ( event.keyCode ) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $( "td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv );
						if ( sel[ 0 ] ) {
							$.datepicker._selectDay( event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ] );
						}

						onSelect = $.datepicker._get( inst, "onSelect" );
						if ( onSelect ) {
							dateStr = $.datepicker._formatDate( inst );

							// Trigger custom callback
							onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							-$.datepicker._get( inst, "stepBigMonths" ) :
							-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
							+$.datepicker._get( inst, "stepBigMonths" ) :
							+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						break; // next month/year on page down/+ ctrl
				case 35: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._clearDate( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._gotoToday( event.target );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? +1 : -1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// -1 day on ctrl or command +left
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								-$.datepicker._get( inst, "stepBigMonths" ) :
								-$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +left on Mac
						break;
				case 38: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, -7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, ( isRTL ? -1 : +1 ), "D" );
						}
						handled = event.ctrlKey || event.metaKey;

						// +1 day on ctrl or command +right
						if ( event.originalEvent.altKey ) {
							$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
								+$.datepicker._get( inst, "stepBigMonths" ) :
								+$.datepicker._get( inst, "stepMonths" ) ), "M" );
						}

						// next month/year on alt +right
						break;
				case 40: if ( event.ctrlKey || event.metaKey ) {
							$.datepicker._adjustDate( event.target, +7, "D" );
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if ( event.keyCode === 36 && event.ctrlKey ) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker( this );
		} else {
			handled = false;
		}

		if ( handled ) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function( event ) {
		var chars, chr,
			inst = $.datepicker._getInst( event.target );

		if ( $.datepicker._get( inst, "constrainInput" ) ) {
			chars = $.datepicker._possibleChars( $.datepicker._get( inst, "dateFormat" ) );
			chr = String.fromCharCode( event.charCode == null ? event.keyCode : event.charCode );
			return event.ctrlKey || event.metaKey || ( chr < " " || !chars || chars.indexOf( chr ) > -1 );
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function( event ) {
		var date,
			inst = $.datepicker._getInst( event.target );

		if ( inst.input.val() !== inst.lastVal ) {
			try {
				date = $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
					( inst.input ? inst.input.val() : null ),
					$.datepicker._getFormatConfig( inst ) );

				if ( date ) { // only if valid
					$.datepicker._setDateFromField( inst );
					$.datepicker._updateAlternate( inst );
					$.datepicker._updateDatepicker( inst );
				}
			} catch ( err ) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function( input ) {
		input = input.target || input;
		if ( input.nodeName.toLowerCase() !== "input" ) { // find from button/image trigger
			input = $( "input", input.parentNode )[ 0 ];
		}

		if ( $.datepicker._isDisabledDatepicker( input ) || $.datepicker._lastInput === input ) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst( input );
		if ( $.datepicker._curInst && $.datepicker._curInst !== inst ) {
			$.datepicker._curInst.dpDiv.stop( true, true );
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[ 0 ] );
			}
		}

		beforeShow = $.datepicker._get( inst, "beforeShow" );
		beforeShowSettings = beforeShow ? beforeShow.apply( input, [ input, inst ] ) : {};
		if ( beforeShowSettings === false ) {
			return;
		}
		datepicker_extendRemove( inst.settings, beforeShowSettings );

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField( inst );

		if ( $.datepicker._inDialog ) { // hide cursor
			input.value = "";
		}
		if ( !$.datepicker._pos ) { // position below input
			$.datepicker._pos = $.datepicker._findPos( input );
			$.datepicker._pos[ 1 ] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$( input ).parents().each( function() {
			isFixed |= $( this ).css( "position" ) === "fixed";
			return !isFixed;
		} );

		offset = { left: $.datepicker._pos[ 0 ], top: $.datepicker._pos[ 1 ] };
		$.datepicker._pos = null;

		//to avoid flashes on Firefox
		inst.dpDiv.empty();

		// determine sizing offscreen
		inst.dpDiv.css( { position: "absolute", display: "block", top: "-1000px" } );
		$.datepicker._updateDatepicker( inst );

		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset( inst, offset, isFixed );
		inst.dpDiv.css( { position: ( $.datepicker._inDialog && $.blockUI ?
			"static" : ( isFixed ? "fixed" : "absolute" ) ), display: "none",
			left: offset.left + "px", top: offset.top + "px" } );

		if ( !inst.inline ) {
			showAnim = $.datepicker._get( inst, "showAnim" );
			duration = $.datepicker._get( inst, "duration" );
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show( showAnim, $.datepicker._get( inst, "showOptions" ), duration );
			} else {
				inst.dpDiv[ showAnim || "show" ]( showAnim ? duration : null );
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.trigger( "focus" );
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function( inst ) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append( this._generateHTML( inst ) );
		this._attachHandlers( inst );

		var origyearshtml,
			numMonths = this._getNumberOfMonths( inst ),
			cols = numMonths[ 1 ],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" ),
			onUpdateDatepicker = $.datepicker._get( inst, "onUpdateDatepicker" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass( "ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4" ).width( "" );
		if ( cols > 1 ) {
			inst.dpDiv.addClass( "ui-datepicker-multi-" + cols ).css( "width", ( width * cols ) + "em" );
		}
		inst.dpDiv[ ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-multi" );
		inst.dpDiv[ ( this._get( inst, "isRTL" ) ? "add" : "remove" ) +
			"Class" ]( "ui-datepicker-rtl" );

		if ( inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.trigger( "focus" );
		}

		// Deffered render of the years select (to avoid flashes on Firefox)
		if ( inst.yearshtml ) {
			origyearshtml = inst.yearshtml;
			setTimeout( function() {

				//assure that inst.yearshtml didn't change.
				if ( origyearshtml === inst.yearshtml && inst.yearshtml ) {
					inst.dpDiv.find( "select.ui-datepicker-year" ).first().replaceWith( inst.yearshtml );
				}
				origyearshtml = inst.yearshtml = null;
			}, 0 );
		}

		if ( onUpdateDatepicker ) {
			onUpdateDatepicker.apply( ( inst.input ? inst.input[ 0 ] : null ), [ inst ] );
		}
	},

	// #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.pseudos.hidden( obj ) ) ) {
			obj = obj[ isRTL ? "previousSibling" : "nextSibling" ];
		}

		position = $( obj ).offset();
		return [ position.left, position.top ];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function( input ) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if ( !inst || ( input && inst !== $.data( input, "datepicker" ) ) ) {
			return;
		}

		if ( this._datepickerShowing ) {
			showAnim = this._get( inst, "showAnim" );
			duration = this._get( inst, "duration" );
			postProcess = function() {
				$.datepicker._tidyDialog( inst );
			};

			// 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 ).off( ".ui-datepicker-calendar" );
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function( event ) {
		if ( !$.datepicker._curInst ) {
			return;
		}

		var $target = $( event.target ),
			inst = $.datepicker._getInst( $target[ 0 ] );

		if ( ( ( $target[ 0 ].id !== $.datepicker._mainDivId &&
				$target.parents( "#" + $.datepicker._mainDivId ).length === 0 &&
				!$target.hasClass( $.datepicker.markerClassName ) &&
				!$target.closest( "." + $.datepicker._triggerClass ).length &&
				$.datepicker._datepickerShowing && !( $.datepicker._inDialog && $.blockUI ) ) ) ||
			( $target.hasClass( $.datepicker.markerClassName ) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function( id, offset, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}
		this._adjustInstDate( inst, offset, period );
		this._updateDatepicker( inst );
	},

	/* Action for current link. */
	_gotoToday: function( id ) {
		var date,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		if ( this._get( inst, "gotoCurrent" ) && inst.currentDay ) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function( id, select, period ) {
		var target = $( id ),
			inst = this._getInst( target[ 0 ] );

		inst[ "selected" + ( period === "M" ? "Month" : "Year" ) ] =
		inst[ "draw" + ( period === "M" ? "Month" : "Year" ) ] =
			parseInt( select.options[ select.selectedIndex ].value, 10 );

		this._notifyChange( inst );
		this._adjustDate( target );
	},

	/* Action for selecting a day. */
	_selectDay: function( id, month, year, td ) {
		var inst,
			target = $( id );

		if ( $( td ).hasClass( this._unselectableClass ) || this._isDisabledDatepicker( target[ 0 ] ) ) {
			return;
		}

		inst = this._getInst( target[ 0 ] );
		inst.selectedDay = inst.currentDay = parseInt( $( "a", td ).attr( "data-date" ) );
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate( id, this._formatDate( inst,
			inst.currentDay, inst.currentMonth, inst.currentYear ) );
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function( id ) {
		var target = $( id );
		this._selectDate( target, "" );
	},

	/* Update the input field with the selected date. */
	_selectDate: function( id, dateStr ) {
		var onSelect,
			target = $( id ),
			inst = this._getInst( target[ 0 ] );

		dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
		if ( inst.input ) {
			inst.input.val( dateStr );
		}
		this._updateAlternate( inst );

		onSelect = this._get( inst, "onSelect" );
		if ( onSelect ) {
			onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );  // trigger custom callback
		} else if ( inst.input ) {
			inst.input.trigger( "change" ); // fire the change event
		}

		if ( inst.inline ) {
			this._updateDatepicker( inst );
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[ 0 ];
			if ( typeof( inst.input[ 0 ] ) !== "object" ) {
				inst.input.trigger( "focus" ); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function( inst ) {
		var altFormat, date, dateStr,
			altField = this._get( inst, "altField" );

		if ( altField ) { // update alternate field too
			altFormat = this._get( inst, "altFormat" ) || this._get( inst, "dateFormat" );
			date = this._getDate( inst );
			dateStr = this.formatDate( altFormat, date, this._getFormatConfig( inst ) );
			$( document ).find( altField ).val( dateStr );
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function( date ) {
		var day = date.getDay();
		return [ ( day > 0 && day < 6 ), "" ];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function( date ) {
		var time,
			checkDate = new Date( date.getTime() );

		// Find Thursday of this week starting on Monday
		checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) );

		time = checkDate.getTime();
		checkDate.setMonth( 0 ); // Compare with Jan 1
		checkDate.setDate( 1 );
		return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function( format, value, settings ) {
		if ( format == null || value == null ) {
			throw "Invalid arguments";
		}

		value = ( typeof value === "object" ? value.toString() : value + "" );
		if ( value === "" ) {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = ( settings ? settings.shortYearCutoff : null ) || this._defaults.shortYearCutoff,
			shortYearCutoff = ( typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt( shortYearCutoffTemp, 10 ) ),
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Extract a number from the string value
			getNumber = function( match ) {
				var isDoubled = lookAhead( match ),
					size = ( match === "@" ? 14 : ( match === "!" ? 20 :
					( match === "y" && isDoubled ? 4 : ( match === "o" ? 3 : 2 ) ) ) ),
					minSize = ( match === "y" ? size : 1 ),
					digits = new RegExp( "^\\d{" + minSize + "," + size + "}" ),
					num = value.substring( iValue ).match( digits );
				if ( !num ) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[ 0 ].length;
				return parseInt( num[ 0 ], 10 );
			},

			// Extract a name from the string value and convert to an index
			getName = function( match, shortNames, longNames ) {
				var index = -1,
					names = $.map( lookAhead( match ) ? longNames : shortNames, function( v, k ) {
						return [ [ k, v ] ];
					} ).sort( function( a, b ) {
						return -( a[ 1 ].length - b[ 1 ].length );
					} );

				$.each( names, function( i, pair ) {
					var name = pair[ 1 ];
					if ( value.substr( iValue, name.length ).toLowerCase() === name.toLowerCase() ) {
						index = pair[ 0 ];
						iValue += name.length;
						return false;
					}
				} );
				if ( index !== -1 ) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},

			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if ( value.charAt( iValue ) !== format.charAt( iFormat ) ) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d":
						day = getNumber( "d" );
						break;
					case "D":
						getName( "D", dayNamesShort, dayNames );
						break;
					case "o":
						doy = getNumber( "o" );
						break;
					case "m":
						month = getNumber( "m" );
						break;
					case "M":
						month = getName( "M", monthNamesShort, monthNames );
						break;
					case "y":
						year = getNumber( "y" );
						break;
					case "@":
						date = new Date( getNumber( "@" ) );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date( ( getNumber( "!" ) - this._ticksTo1970 ) / 10000 );
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if ( lookAhead( "'" ) ) {
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if ( iValue < value.length ) {
			extra = value.substr( iValue );
			if ( !/^\s+/.test( extra ) ) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if ( year === -1 ) {
			year = new Date().getFullYear();
		} else if ( year < 100 ) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				( year <= shortYearCutoff ? 0 : -100 );
		}

		if ( doy > -1 ) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth( year, month - 1 );
				if ( day <= dim ) {
					break;
				}
				month++;
				day -= dim;
			} while ( true );
		}

		date = this._daylightSavingAdjust( new Date( year, month - 1, day ) );
		if ( date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day ) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: ( ( ( 1970 - 1 ) * 365 + Math.floor( 1970 / 4 ) - Math.floor( 1970 / 100 ) +
		Math.floor( 1970 / 400 ) ) * 24 * 60 * 60 * 10000000 ),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function( format, date, settings ) {
		if ( !date ) {
			return "";
		}

		var iFormat,
			dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
			dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
			monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
			monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			},

			// Format a number, with leading zero if necessary
			formatNumber = function( match, value, len ) {
				var num = "" + value;
				if ( lookAhead( match ) ) {
					while ( num.length < len ) {
						num = "0" + num;
					}
				}
				return num;
			},

			// Format a name, short or long as requested
			formatName = function( match, value, shortNames, longNames ) {
				return ( lookAhead( match ) ? longNames[ value ] : shortNames[ value ] );
			},
			output = "",
			literal = false;

		if ( date ) {
			for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
				if ( literal ) {
					if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
						literal = false;
					} else {
						output += format.charAt( iFormat );
					}
				} else {
					switch ( format.charAt( iFormat ) ) {
						case "d":
							output += formatNumber( "d", date.getDate(), 2 );
							break;
						case "D":
							output += formatName( "D", date.getDay(), dayNamesShort, dayNames );
							break;
						case "o":
							output += formatNumber( "o",
								Math.round( ( new Date( date.getFullYear(), date.getMonth(), date.getDate() ).getTime() - new Date( date.getFullYear(), 0, 0 ).getTime() ) / 86400000 ), 3 );
							break;
						case "m":
							output += formatNumber( "m", date.getMonth() + 1, 2 );
							break;
						case "M":
							output += formatName( "M", date.getMonth(), monthNamesShort, monthNames );
							break;
						case "y":
							output += ( lookAhead( "y" ) ? date.getFullYear() :
								( date.getFullYear() % 100 < 10 ? "0" : "" ) + date.getFullYear() % 100 );
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if ( lookAhead( "'" ) ) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt( iFormat );
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function( format ) {
		var iFormat,
			chars = "",
			literal = false,

			// Check whether a format character is doubled
			lookAhead = function( match ) {
				var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
				if ( matches ) {
					iFormat++;
				}
				return matches;
			};

		for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
			if ( literal ) {
				if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
					literal = false;
				} else {
					chars += format.charAt( iFormat );
				}
			} else {
				switch ( format.charAt( iFormat ) ) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if ( lookAhead( "'" ) ) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt( iFormat );
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function( inst, name ) {
		return inst.settings[ name ] !== undefined ?
			inst.settings[ name ] : this._defaults[ name ];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function( inst, noDefault ) {
		if ( inst.input.val() === inst.lastVal ) {
			return;
		}

		var dateFormat = this._get( inst, "dateFormat" ),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate( inst ),
			date = defaultDate,
			settings = this._getFormatConfig( inst );

		try {
			date = this.parseDate( dateFormat, dates, settings ) || defaultDate;
		} catch ( 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 ).on( this.getAttribute( "data-event" ), handler[ this.getAttribute( "data-handler" ) ] );
		} );
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function( inst ) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date( tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() ) ), // clear time
			isRTL = this._get( inst, "isRTL" ),
			showButtonPanel = this._get( inst, "showButtonPanel" ),
			hideIfNoPrevNext = this._get( inst, "hideIfNoPrevNext" ),
			navigationAsDateFormat = this._get( inst, "navigationAsDateFormat" ),
			numMonths = this._getNumberOfMonths( inst ),
			showCurrentAtPos = this._get( inst, "showCurrentAtPos" ),
			stepMonths = this._get( inst, "stepMonths" ),
			isMultiMonth = ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ),
			currentDate = this._daylightSavingAdjust( ( !inst.currentDay ? new Date( 9999, 9, 9 ) :
				new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) ),
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if ( drawMonth < 0 ) {
			drawMonth += 12;
			drawYear--;
		}
		if ( maxDate ) {
			maxDraw = this._daylightSavingAdjust( new Date( maxDate.getFullYear(),
				maxDate.getMonth() - ( numMonths[ 0 ] * numMonths[ 1 ] ) + 1, maxDate.getDate() ) );
			maxDraw = ( minDate && maxDraw < minDate ? minDate : maxDraw );
			while ( this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 ) ) > maxDraw ) {
				drawMonth--;
				if ( drawMonth < 0 ) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get( inst, "prevText" );
		prevText = ( !navigationAsDateFormat ? prevText : this.formatDate( prevText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth - stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		if ( this._canAdjustMonth( inst, -1, drawYear, drawMonth ) ) {
			prev = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-prev ui-corner-all",
					"data-handler": "prev",
					"data-event": "click",
					title: prevText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "e" : "w" ) )
						.text( prevText )
				)[ 0 ].outerHTML;
		} else if ( hideIfNoPrevNext ) {
			prev = "";
		} else {
			prev = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-prev ui-corner-all ui-state-disabled",
					title: prevText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "e" : "w" ) )
						.text( prevText )
				)[ 0 ].outerHTML;
		}

		nextText = this._get( inst, "nextText" );
		nextText = ( !navigationAsDateFormat ? nextText : this.formatDate( nextText,
			this._daylightSavingAdjust( new Date( drawYear, drawMonth + stepMonths, 1 ) ),
			this._getFormatConfig( inst ) ) );

		if ( this._canAdjustMonth( inst, +1, drawYear, drawMonth ) ) {
			next = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-next ui-corner-all",
					"data-handler": "next",
					"data-event": "click",
					title: nextText
				} )
				.append(
					$( "<span>" )
						.addClass( "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "w" : "e" ) )
						.text( nextText )
				)[ 0 ].outerHTML;
		} else if ( hideIfNoPrevNext ) {
			next = "";
		} else {
			next = $( "<a>" )
				.attr( {
					"class": "ui-datepicker-next ui-corner-all ui-state-disabled",
					title: nextText
				} )
				.append(
					$( "<span>" )
						.attr( "class", "ui-icon ui-icon-circle-triangle-" +
							( isRTL ? "w" : "e" ) )
						.text( nextText )
				)[ 0 ].outerHTML;
		}

		currentText = this._get( inst, "currentText" );
		gotoDate = ( this._get( inst, "gotoCurrent" ) && inst.currentDay ? currentDate : today );
		currentText = ( !navigationAsDateFormat ? currentText :
			this.formatDate( currentText, gotoDate, this._getFormatConfig( inst ) ) );

		controls = "";
		if ( !inst.inline ) {
			controls = $( "<button>" )
				.attr( {
					type: "button",
					"class": "ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all",
					"data-handler": "hide",
					"data-event": "click"
				} )
				.text( this._get( inst, "closeText" ) )[ 0 ].outerHTML;
		}

		buttonPanel = "";
		if ( showButtonPanel ) {
			buttonPanel = $( "<div class='ui-datepicker-buttonpane ui-widget-content'>" )
				.append( isRTL ? controls : "" )
				.append( this._isInRange( inst, gotoDate ) ?
					$( "<button>" )
						.attr( {
							type: "button",
							"class": "ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all",
							"data-handler": "today",
							"data-event": "click"
						} )
						.text( currentText ) :
					"" )
				.append( isRTL ? "" : controls )[ 0 ].outerHTML;
		}

		firstDay = parseInt( this._get( inst, "firstDay" ), 10 );
		firstDay = ( isNaN( firstDay ) ? 0 : firstDay );

		showWeek = this._get( inst, "showWeek" );
		dayNames = this._get( inst, "dayNames" );
		dayNamesMin = this._get( inst, "dayNamesMin" );
		monthNames = this._get( inst, "monthNames" );
		monthNamesShort = this._get( inst, "monthNamesShort" );
		beforeShowDay = this._get( inst, "beforeShowDay" );
		showOtherMonths = this._get( inst, "showOtherMonths" );
		selectOtherMonths = this._get( inst, "selectOtherMonths" );
		defaultDate = this._getDefaultDate( inst );
		html = "";

		for ( row = 0; row < numMonths[ 0 ]; row++ ) {
			group = "";
			this.maxRows = 4;
			for ( col = 0; col < numMonths[ 1 ]; col++ ) {
				selectedDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, inst.selectedDay ) );
				cornerClass = " ui-corner-all";
				calender = "";
				if ( isMultiMonth ) {
					calender += "<div class='ui-datepicker-group";
					if ( numMonths[ 1 ] > 1 ) {
						switch ( col ) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + ( isRTL ? "right" : "left" ); break;
							case numMonths[ 1 ] - 1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + ( isRTL ? "left" : "right" ); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					( /all|left/.test( cornerClass ) && row === 0 ? ( isRTL ? next : prev ) : "" ) +
					( /all|right/.test( cornerClass ) && row === 0 ? ( isRTL ? prev : next ) : "" ) +
					this._generateMonthYearHeader( inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort ) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = ( showWeek ? "<th class='ui-datepicker-week-col'>" + this._get( inst, "weekHeader" ) + "</th>" : "" );
				for ( dow = 0; dow < 7; dow++ ) { // days of the week
					day = ( dow + firstDay ) % 7;
					thead += "<th scope='col'" + ( ( dow + firstDay + 6 ) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "" ) + ">" +
						"<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth( drawYear, drawMonth );
				if ( drawYear === inst.selectedYear && drawMonth === inst.selectedMonth ) {
					inst.selectedDay = Math.min( inst.selectedDay, daysInMonth );
				}
				leadDays = ( this._getFirstDayOfMonth( drawYear, drawMonth ) - firstDay + 7 ) % 7;
				curRows = Math.ceil( ( leadDays + daysInMonth ) / 7 ); // calculate the number of rows to generate
				numRows = ( isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows ); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 - leadDays ) );
				for ( dRow = 0; dRow < numRows; dRow++ ) { // create date picker rows
					calender += "<tr>";
					tbody = ( !showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get( inst, "calculateWeek" )( printDate ) + "</td>" );
					for ( dow = 0; dow < 7; dow++ ) { // create date picker days
						daySettings = ( beforeShowDay ?
							beforeShowDay.apply( ( inst.input ? inst.input[ 0 ] : null ), [ printDate ] ) : [ true, "" ] );
						otherMonth = ( printDate.getMonth() !== drawMonth );
						unselectable = ( otherMonth && !selectOtherMonths ) || !daySettings[ 0 ] ||
							( minDate && printDate < minDate ) || ( maxDate && printDate > maxDate );
						tbody += "<td class='" +
							( ( dow + firstDay + 6 ) % 7 >= 5 ? " ui-datepicker-week-end" : "" ) + // highlight weekends
							( otherMonth ? " ui-datepicker-other-month" : "" ) + // highlight days from other months
							( ( printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent ) || // user pressed key
							( defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime() ) ?

							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "" ) + // highlight selected day
							( unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "" ) +  // highlight unselectable days
							( otherMonth && !showOtherMonths ? "" : " " + daySettings[ 1 ] + // highlight custom dates
							( printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "" ) + // highlight selected day
							( printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "" ) ) + "'" + // highlight today (if different)
							( ( !otherMonth || showOtherMonths ) && daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace( /'/g, "&#39;" ) + "'" : "" ) + // cell title
							( unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'" ) + ">" + // actions
							( otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							( unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							( printDate.getTime() === today.getTime() ? " ui-state-highlight" : "" ) +
							( printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "" ) + // highlight selected day
							( otherMonth ? " ui-priority-secondary" : "" ) + // distinguish dates from other months
							"' href='#' aria-current='" + ( printDate.getTime() === currentDate.getTime() ? "true" : "false" ) + // mark date as selected for screen reader
							"' data-date='" + printDate.getDate() + // store date as data
							"'>" + printDate.getDate() + "</a>" ) ) + "</td>"; // display selectable date
						printDate.setDate( printDate.getDate() + 1 );
						printDate = this._daylightSavingAdjust( printDate );
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if ( drawMonth > 11 ) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + ( isMultiMonth ? "</div>" +
							( ( numMonths[ 0 ] > 0 && col === numMonths[ 1 ] - 1 ) ? "<div class='ui-datepicker-row-break'></div>" : "" ) : "" );
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function( inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort ) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get( inst, "changeMonth" ),
			changeYear = this._get( inst, "changeYear" ),
			showMonthAfterYear = this._get( inst, "showMonthAfterYear" ),
			selectMonthLabel = this._get( inst, "selectMonthLabel" ),
			selectYearLabel = this._get( inst, "selectYearLabel" ),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// Month selection
		if ( secondary || !changeMonth ) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[ drawMonth ] + "</span>";
		} else {
			inMinYear = ( minDate && minDate.getFullYear() === drawYear );
			inMaxYear = ( maxDate && maxDate.getFullYear() === drawYear );
			monthHtml += "<select class='ui-datepicker-month' aria-label='" + selectMonthLabel + "' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++ ) {
				if ( ( !inMinYear || month >= minDate.getMonth() ) && ( !inMaxYear || month <= maxDate.getMonth() ) ) {
					monthHtml += "<option value='" + month + "'" +
						( month === drawMonth ? " selected='selected'" : "" ) +
						">" + monthNamesShort[ month ] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if ( !showMonthAfterYear ) {
			html += monthHtml + ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" );
		}

		// Year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if ( secondary || !changeYear ) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {

				// determine range of years to display
				years = this._get( inst, "yearRange" ).split( ":" );
				thisYear = new Date().getFullYear();
				determineYear = function( value ) {
					var year = ( value.match( /c[+\-].*/ ) ? drawYear + parseInt( value.substring( 1 ), 10 ) :
						( value.match( /[+\-].*/ ) ? thisYear + parseInt( value, 10 ) :
						parseInt( value, 10 ) ) );
					return ( isNaN( year ) ? thisYear : year );
				};
				year = determineYear( years[ 0 ] );
				endYear = Math.max( year, determineYear( years[ 1 ] || "" ) );
				year = ( minDate ? Math.max( year, minDate.getFullYear() ) : year );
				endYear = ( maxDate ? Math.min( endYear, maxDate.getFullYear() ) : endYear );
				inst.yearshtml += "<select class='ui-datepicker-year' aria-label='" + selectYearLabel + "' data-handler='selectYear' data-event='change'>";
				for ( ; year <= endYear; year++ ) {
					inst.yearshtml += "<option value='" + year + "'" +
						( year === drawYear ? " selected='selected'" : "" ) +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get( inst, "yearSuffix" );
		if ( showMonthAfterYear ) {
			html += ( secondary || !( changeMonth && changeYear ) ? "&#xa0;" : "" ) + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function( inst, offset, period ) {
		var year = inst.selectedYear + ( period === "Y" ? offset : 0 ),
			month = inst.selectedMonth + ( period === "M" ? offset : 0 ),
			day = Math.min( inst.selectedDay, this._getDaysInMonth( year, month ) ) + ( period === "D" ? offset : 0 ),
			date = this._restrictMinMax( inst, this._daylightSavingAdjust( new Date( year, month, day ) ) );

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if ( period === "M" || period === "Y" ) {
			this._notifyChange( inst );
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function( inst, date ) {
		var minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			newDate = ( minDate && date < minDate ? minDate : date );
		return ( maxDate && newDate > maxDate ? maxDate : newDate );
	},

	/* Notify change of month/year. */
	_notifyChange: function( inst ) {
		var onChange = this._get( inst, "onChangeMonthYear" );
		if ( onChange ) {
			onChange.apply( ( inst.input ? inst.input[ 0 ] : null ),
				[ inst.selectedYear, inst.selectedMonth + 1, inst ] );
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function( inst ) {
		var numMonths = this._get( inst, "numberOfMonths" );
		return ( numMonths == null ? [ 1, 1 ] : ( typeof numMonths === "number" ? [ 1, numMonths ] : numMonths ) );
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function( inst, minMax ) {
		return this._determineDate( inst, this._get( inst, minMax + "Date" ), null );
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function( year, month ) {
		return 32 - this._daylightSavingAdjust( new Date( year, month, 32 ) ).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function( year, month ) {
		return new Date( year, month, 1 ).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function( inst, offset, curYear, curMonth ) {
		var numMonths = this._getNumberOfMonths( inst ),
			date = this._daylightSavingAdjust( new Date( curYear,
			curMonth + ( offset < 0 ? offset : numMonths[ 0 ] * numMonths[ 1 ] ), 1 ) );

		if ( offset < 0 ) {
			date.setDate( this._getDaysInMonth( date.getFullYear(), date.getMonth() ) );
		}
		return this._isInRange( inst, date );
	},

	/* Is the given date in the accepted range? */
	_isInRange: function( inst, date ) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate( inst, "min" ),
			maxDate = this._getMinMaxDate( inst, "max" ),
			minYear = null,
			maxYear = null,
			years = this._get( inst, "yearRange" );
			if ( years ) {
				yearSplit = years.split( ":" );
				currentYear = new Date().getFullYear();
				minYear = parseInt( yearSplit[ 0 ], 10 );
				maxYear = parseInt( yearSplit[ 1 ], 10 );
				if ( yearSplit[ 0 ].match( /[+\-].*/ ) ) {
					minYear += currentYear;
				}
				if ( yearSplit[ 1 ].match( /[+\-].*/ ) ) {
					maxYear += currentYear;
				}
			}

		return ( ( !minDate || date.getTime() >= minDate.getTime() ) &&
			( !maxDate || date.getTime() <= maxDate.getTime() ) &&
			( !minYear || date.getFullYear() >= minYear ) &&
			( !maxYear || date.getFullYear() <= maxYear ) );
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function( inst ) {
		var shortYearCutoff = this._get( inst, "shortYearCutoff" );
		shortYearCutoff = ( typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt( shortYearCutoff, 10 ) );
		return { shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get( inst, "dayNamesShort" ), dayNames: this._get( inst, "dayNames" ),
			monthNamesShort: this._get( inst, "monthNamesShort" ), monthNames: this._get( inst, "monthNames" ) };
	},

	/* Format the given date for display. */
	_formatDate: function( inst, day, month, year ) {
		if ( !day ) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = ( day ? ( typeof day === "object" ? day :
			this._daylightSavingAdjust( new Date( year, month, day ) ) ) :
			this._daylightSavingAdjust( new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
		return this.formatDate( this._get( inst, "dateFormat" ), date, this._getFormatConfig( inst ) );
	}
} );

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover( dpDiv ) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.on( "mouseout", selector, function() {
			$( this ).removeClass( "ui-state-hover" );
			if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-prev-hover" );
			}
			if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
				$( this ).removeClass( "ui-datepicker-next-hover" );
			}
		} )
		.on( "mouseover", selector, datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if ( !$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ] : datepicker_instActive.input[ 0 ] ) ) {
		$( this ).parents( ".ui-datepicker-calendar" ).find( "a" ).removeClass( "ui-state-hover" );
		$( this ).addClass( "ui-state-hover" );
		if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-prev-hover" );
		}
		if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
			$( this ).addClass( "ui-datepicker-next-hover" );
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove( target, props ) {
	$.extend( target, props );
	for ( var name in props ) {
		if ( props[ name ] == null ) {
			target[ name ] = props[ name ];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function( options ) {

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if ( !$.datepicker.initialized ) {
		$( document ).on( "mousedown", $.datepicker._checkExternalClick );
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ( $( "#" + $.datepicker._mainDivId ).length === 0 ) {
		$( "body" ).append( $.datepicker.dpDiv );
	}

	var otherArgs = Array.prototype.slice.call( arguments, 1 );
	if ( typeof options === "string" && ( options === "isDisabled" || options === "getDate" || options === "widget" ) ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	if ( options === "option" && arguments.length === 2 && typeof arguments[ 1 ] === "string" ) {
		return $.datepicker[ "_" + options + "Datepicker" ].
			apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
	}
	return this.each( function() {
		if ( typeof options === "string" ) {
			$.datepicker[ "_" + options + "Datepicker" ]
				.apply( $.datepicker, [ this ].concat( otherArgs ) );
		} else {
			$.datepicker._attachDatepicker( this, options );
		}
	} );
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.13.0";

return $.datepicker;

} );




/*!
 * jQuery UI Mouse 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../ie",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

return $.widget( "ui.mouse", {
	version: "1.13.0",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		if ( this._mouseStarted ) {
			this._mouseUp( event );
		}

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			if ( this._mouseStarted ) {
				this._mouseDrag( event );
			} else {
				this._mouseUp( event );
			}
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) {
		return true;
	}
} );

} );









/*!
 * jQuery UI Draggable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./mouse",
			"../data",
			"../plugin",
			"../safe-active-element",
			"../safe-blur",
			"../scroll-parent",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.draggable", $.ui.mouse, {
	version: "1.13.0",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// Callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if ( this.options.addClasses ) {
			this._addClass( "ui-draggable" );
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var o = this.options;

		// Among others, prevent a drag on a resizable-handle
		if ( this.helper || o.disabled ||
				$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle( event );
		if ( !this.handle ) {
			return false;
		}

		this._blurActiveElement( event );

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			target = $( event.target );

		// Don't blur if the event occurred on an element that is within
		// the currently focused element
		// See #10527, #12472
		if ( target.closest( activeElement ).length ) {
			return;
		}

		// Blur any element that currently has focus, see #4261
		$.ui.safeBlur( activeElement );
	},

	_mouseStart: function( event ) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		this._addClass( this.helper, "ui-draggable-dragging" );

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter( function() {
				return $( this ).css( "position" ) === "fixed";
			} ).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		if ( o.cursorAt ) {
			this._adjustOffsetFromHelper( o.cursorAt );
		}

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if ( this._trigger( "start", event ) === false ) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		// Execute the drag once - this causes the helper not to be visible before getting its
		// correct position
		this._mouseDrag( event, true );

		// If the ddmanager is used for droppables, inform the manager that dragging has started
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart( this, event );
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function( event, noPropagation ) {

		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Call plugins and callbacks and use the resulting position if something is returned
		if ( !noPropagation ) {
			var ui = this._uiHash();
			if ( this._trigger( "drag", event, ui ) === false ) {
				this._mouseUp( new $.Event( "mouseup", event ) );
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		return false;
	},

	_mouseStop: function( event ) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			dropped = $.ui.ddmanager.drop( this, event );
		}

		//if a drop comes from outside (a sortable)
		if ( this.dropped ) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ( ( this.options.revert === "invalid" && !dropped ) ||
				( this.options.revert === "valid" && dropped ) ||
				this.options.revert === true || ( typeof this.options.revert === "function" &&
				this.options.revert.call( this.element, dropped ) )
		) {
			$( this.helper ).animate(
				this.originalPosition,
				parseInt( this.options.revertDuration, 10 ),
				function() {
					if ( that._trigger( "stop", event ) !== false ) {
						that._clear();
					}
				}
			);
		} else {
			if ( this._trigger( "stop", event ) !== false ) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		// If the ddmanager is used for droppables, inform the manager that dragging has stopped
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop( this, event );
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {

			// The interaction is over; whether or not the click resulted in a drag,
			// focus the element
			this.element.trigger( "focus" );
		}

		return $.ui.mouse.prototype._mouseUp.call( this, event );
	},

	cancel: function() {

		if ( this.helper.is( ".ui-draggable-dragging" ) ) {
			this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function( event ) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this._addClass( this.handleElement, "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this._removeClass( this.handleElement, "ui-draggable-handle" );
	},

	_createHelper: function( event ) {

		var o = this.options,
			helperIsFunction = typeof o.helper === "function",
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if ( !helper.parents( "body" ).length ) {
			helper.appendTo( ( o.appendTo === "parent" ?
				this.element[ 0 ].parentNode :
				o.appendTo ) );
		}

		// Http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if ( helper[ 0 ] !== this.element[ 0 ] &&
				!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
			helper.css( "position", "absolute" );
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( Array.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
			right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
			bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() -
					this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() +
					( $( window ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document" ) {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ) {
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
					pageX = containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
					pageY = containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
					pageX = containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
					pageY = containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {

				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
				// argument errors in IE (see ticket #6950)
				top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
					this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
				pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
					top - this.offset.click.top > containment[ 3 ] ) ?
						top :
						( ( top - this.offset.click.top >= containment[ 1 ] ) ?
							top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;

				left = o.grid[ 0 ] ? this.originalPageX +
					Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
					this.originalPageX;
				pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
					left - this.offset.click.left > containment[ 2 ] ) ?
						left :
						( ( left - this.offset.click.left >= containment[ 0 ] ) ?
							left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this._removeClass( this.helper, "ui-draggable-dragging" );
		if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

} );

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each( function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// RefreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger( "activate", event, uiSortable );
			}
		} );
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop( event );

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {

				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		} );
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {

					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				} );
			}

			if ( innermostIntersecting ) {

				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );

					// Hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );

					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {

				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// Restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );
				}
			}
		} );
	}
} );

$.ui.plugin.add( "draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if ( t.css( "cursor" ) ) {
			o._cursor = t.css( "cursor" );
		}
		t.css( "cursor", o.cursor );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._cursor ) {
			$( "body" ).css( "cursor", o._cursor );
		}
	}
} );

$.ui.plugin.add( "draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if ( t.css( "opacity" ) ) {
			o._opacity = t.css( "opacity" );
		}
		t.css( "opacity", o.opacity );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._opacity ) {
			$( ui.helper ).css( "opacity", o._opacity );
		}
	}
} );

$.ui.plugin.add( "draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
				i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
						o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
						o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if ( !o.axis || o.axis !== "x" ) {
				if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
				} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() - o.scrollSpeed
					);
				} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() + o.scrollSpeed
					);
				}
			}

		}

		if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( i, event );
		}

	}
} );

$.ui.plugin.add( "draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
			.each( function() {
				var $t = $( this ),
					$o = $t.offset();
				if ( this !== i.element[ 0 ] ) {
					i.snapElements.push( {
						item: this,
						width: $t.outerWidth(), height: $t.outerHeight(),
						top: $o.top, left: $o.left
					} );
				}
			} );

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {

			l = inst.snapElements[ i ].left - inst.margins.left;
			r = l + inst.snapElements[ i ].width;
			t = inst.snapElements[ i ].top - inst.margins.top;
			b = t + inst.snapElements[ i ].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
					!$.contains( inst.snapElements[ i ].item.ownerDocument,
					inst.snapElements[ i ].item ) ) {
				if ( inst.snapElements[ i ].snapping ) {
					if ( inst.options.snap.release ) {
						inst.options.snap.release.call(
							inst.element,
							event,
							$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
						);
					}
				}
				inst.snapElements[ i ].snapping = false;
				continue;
			}

			if ( o.snapMode !== "inner" ) {
				ts = Math.abs( t - y2 ) <= d;
				bs = Math.abs( b - y1 ) <= d;
				ls = Math.abs( l - x2 ) <= d;
				rs = Math.abs( r - x1 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l - inst.helperProportions.width
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r
					} ).left;
				}
			}

			first = ( ts || bs || ls || rs );

			if ( o.snapMode !== "outer" ) {
				ts = Math.abs( t - y1 ) <= d;
				bs = Math.abs( b - y2 ) <= d;
				ls = Math.abs( l - x1 ) <= d;
				rs = Math.abs( r - x2 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r - inst.helperProportions.width
					} ).left;
				}
			}

			if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
				if ( inst.options.snap.snap ) {
					inst.options.snap.snap.call(
						inst.element,
						event,
						$.extend( inst._uiHash(), {
							snapItem: inst.snapElements[ i ].item
						} ) );
				}
			}
			inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );

		}

	}
} );

$.ui.plugin.add( "draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
				return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
					( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
			} );

		if ( !group.length ) {
			return;
		}

		min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
		$( group ).each( function( i ) {
			$( this ).css( "zIndex", min + i );
		} );
		this.css( "zIndex", ( min + group.length ) );
	}
} );

$.ui.plugin.add( "draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if ( t.css( "zIndex" ) ) {
			o._zIndex = t.css( "zIndex" );
		}
		t.css( "zIndex", o.zIndex );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if ( o._zIndex ) {
			$( ui.helper ).css( "zIndex", o._zIndex );
		}
	}
} );

return $.ui.draggable;

} );






/*!
 * jQuery UI Resizable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Resizable
//>>group: Interactions
//>>description: Enables resize functionality for any element.
//>>docs: http://api.jqueryui.com/resizable/
//>>demos: http://jqueryui.com/resizable/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/resizable.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./mouse",
			"../disable-selection",
			"../plugin",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.resizable", $.ui.mouse, {
	version: "1.13.0",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		classes: {
			"ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
		},
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,

		// See #7960
		zIndex: 90,

		// Callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseFloat( value ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseFloat( value ) );
	},

	_hasScroll: function( el, a ) {

		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
		try {
			el[ scroll ] = 1;
			has = ( el[ scroll ] > 0 );
			el[ scroll ] = 0;
		} catch ( e ) {

			// `el` might be a string, then setting `scroll` will throw
			// an error in strict mode; ignore it.
		}
		return has;
	},

	_create: function() {

		var margins,
			o = this.options,
			that = this;
		this._addClass( "ui-resizable" );

		$.extend( this, {
			_aspectRatio: !!( o.aspectRatio ),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		} );

		// Wrap the element if it cannot hold child nodes
		if ( this.element[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) {

			this.element.wrap(
				$( "<div class='ui-wrapper'></div>" ).css( {
					overflow: "hidden",
					position: this.element.css( "position" ),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css( "top" ),
					left: this.element.css( "left" )
				} )
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			margins = {
				marginTop: this.originalElement.css( "marginTop" ),
				marginRight: this.originalElement.css( "marginRight" ),
				marginBottom: this.originalElement.css( "marginBottom" ),
				marginLeft: this.originalElement.css( "marginLeft" )
			};

			this.element.css( margins );
			this.originalElement.css( "margin", 0 );

			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css( "resize" );
			this.originalElement.css( "resize", "none" );

			this._proportionallyResizeElements.push( this.originalElement.css( {
				position: "static",
				zoom: 1,
				display: "block"
			} ) );

			// Support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css( margins );

			this._proportionallyResize();
		}

		this._setupHandles();

		if ( o.autoHide ) {
			$( this.element )
				.on( "mouseenter", function() {
					if ( o.disabled ) {
						return;
					}
					that._removeClass( "ui-resizable-autohide" );
					that._handles.show();
				} )
				.on( "mouseleave", function() {
					if ( o.disabled ) {
						return;
					}
					if ( !that.resizing ) {
						that._addClass( "ui-resizable-autohide" );
						that._handles.hide();
					}
				} );
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();
		this._addedHandles.remove();

		var wrapper,
			_destroy = function( exp ) {
				$( exp )
					.removeData( "resizable" )
					.removeData( "ui-resizable" )
					.off( ".resizable" );
			};

		// TODO: Unwrap at same DOM position
		if ( this.elementIsWrapper ) {
			_destroy( this.element );
			wrapper = this.element;
			this.originalElement.css( {
				position: wrapper.css( "position" ),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css( "top" ),
				left: wrapper.css( "left" )
			} ).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css( "resize", this.originalResizeStyle );
		_destroy( this.originalElement );

		return this;
	},

	_setOption: function( key, value ) {
		this._super( key, value );

		switch ( key ) {
		case "handles":
			this._removeHandles();
			this._setupHandles();
			break;
		case "aspectRatio":
			this._aspectRatio = !!value;
			break;
		default:
			break;
		}
	},

	_setupHandles: function() {
		var o = this.options, handle, i, n, hname, axis, that = this;
		this.handles = o.handles ||
			( !$( ".ui-resizable-handle", this.element ).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		this._addedHandles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all" ) {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split( "," );
			this.handles = {};

			for ( i = 0; i < n.length; i++ ) {

				handle = String.prototype.trim.call( n[ i ] );
				hname = "ui-resizable-" + handle;
				axis = $( "<div>" );
				this._addClass( axis, "ui-resizable-handle " + hname );

				axis.css( { zIndex: o.zIndex } );

				this.handles[ handle ] = ".ui-resizable-" + handle;
				if ( !this.element.children( this.handles[ handle ] ).length ) {
					this.element.append( axis );
					this._addedHandles = this._addedHandles.add( axis );
				}
			}

		}

		this._renderAxis = function( target ) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for ( i in this.handles ) {

				if ( this.handles[ i ].constructor === String ) {
					this.handles[ i ] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown } );
				}

				if ( this.elementIsWrapper &&
						this.originalElement[ 0 ]
							.nodeName
							.match( /^(textarea|input|select|button)$/i ) ) {
					axis = $( this.handles[ i ], this.element );

					padWrapper = /sw|ne|nw|se|n|s/.test( i ) ?
						axis.outerHeight() :
						axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test( i ) ? "Top" :
						/se|sw|s/.test( i ) ? "Bottom" :
						/^e$/.test( i ) ? "Right" : "Left" ].join( "" );

					target.css( padPos, padWrapper );

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis( this.element );

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.on( "mouseover", function() {
			if ( !that.resizing ) {
				if ( this.className ) {
					axis = this.className.match( /ui-resizable-(se|sw|ne|nw|n|e|s|w)/i );
				}
				that.axis = axis && axis[ 1 ] ? axis[ 1 ] : "se";
			}
		} );

		if ( o.autoHide ) {
			this._handles.hide();
			this._addClass( "ui-resizable-autohide" );
		}
	},

	_removeHandles: function() {
		this._addedHandles.remove();
	},

	_mouseCapture: function( event ) {
		var i, handle,
			capture = false;

		for ( i in this.handles ) {
			handle = $( this.handles[ i ] )[ 0 ];
			if ( handle === event.target || $.contains( handle, event.target ) ) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function( event ) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num( this.helper.css( "left" ) );
		curtop = this._num( this.helper.css( "top" ) );

		if ( o.containment ) {
			curleft += $( o.containment ).scrollLeft() || 0;
			curtop += $( o.containment ).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = ( typeof o.aspectRatio === "number" ) ?
			o.aspectRatio :
			( ( this.originalSize.width / this.originalSize.height ) || 1 );

		cursor = $( ".ui-resizable-" + this.axis ).css( "cursor" );
		$( "body" ).css( "cursor", cursor === "auto" ? this.axis + "-resize" : cursor );

		this._addClass( "ui-resizable-resizing" );
		this._propagate( "start", event );
		return true;
	},

	_mouseDrag: function( event ) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = ( event.pageX - smp.left ) || 0,
			dy = ( event.pageY - smp.top ) || 0,
			trigger = this._change[ a ];

		this._updatePrevProperties();

		if ( !trigger ) {
			return false;
		}

		data = trigger.apply( this, [ event, dx, dy ] );

		this._updateVirtualBoundaries( event.shiftKey );
		if ( this._aspectRatio || event.shiftKey ) {
			data = this._updateRatio( data, event );
		}

		data = this._respectSize( data, event );

		this._updateCache( data );

		this._propagate( "resize", event );

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function( event ) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if ( this._helper ) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName );
			soffseth = ista && this._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: ( that.helper.width()  - soffsetw ),
				height: ( that.helper.height() - soffseth )
			};
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null;
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

			if ( !o.animate ) {
				this.element.css( $.extend( s, { top: top, left: left } ) );
			}

			that.helper.height( that.size.height );
			that.helper.width( that.size.width );

			if ( this._helper && !o.animate ) {
				this._proportionallyResize();
			}
		}

		$( "body" ).css( "cursor", "auto" );

		this._removeClass( "ui-resizable-resizing" );

		this._propagate( "stop", event );

		if ( this._helper ) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function( forceAspectRatio ) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber( o.minWidth ) ? o.minWidth : 0,
			maxWidth: this._isNumber( o.maxWidth ) ? o.maxWidth : Infinity,
			minHeight: this._isNumber( o.minHeight ) ? o.minHeight : 0,
			maxHeight: this._isNumber( o.maxHeight ) ? o.maxHeight : Infinity
		};

		if ( this._aspectRatio || forceAspectRatio ) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if ( pMinWidth > b.minWidth ) {
				b.minWidth = pMinWidth;
			}
			if ( pMinHeight > b.minHeight ) {
				b.minHeight = pMinHeight;
			}
			if ( pMaxWidth < b.maxWidth ) {
				b.maxWidth = pMaxWidth;
			}
			if ( pMaxHeight < b.maxHeight ) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function( data ) {
		this.offset = this.helper.offset();
		if ( this._isNumber( data.left ) ) {
			this.position.left = data.left;
		}
		if ( this._isNumber( data.top ) ) {
			this.position.top = data.top;
		}
		if ( this._isNumber( data.height ) ) {
			this.size.height = data.height;
		}
		if ( this._isNumber( data.width ) ) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if ( this._isNumber( data.height ) ) {
			data.width = ( data.height * this.aspectRatio );
		} else if ( this._isNumber( data.width ) ) {
			data.height = ( data.width / this.aspectRatio );
		}

		if ( a === "sw" ) {
			data.left = cpos.left + ( csize.width - data.width );
			data.top = null;
		}
		if ( a === "nw" ) {
			data.top = cpos.top + ( csize.height - data.height );
			data.left = cpos.left + ( csize.width - data.width );
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber( data.width ) && o.maxWidth && ( o.maxWidth < data.width ),
			ismaxh = this._isNumber( data.height ) && o.maxHeight && ( o.maxHeight < data.height ),
			isminw = this._isNumber( data.width ) && o.minWidth && ( o.minWidth > data.width ),
			isminh = this._isNumber( data.height ) && o.minHeight && ( o.minHeight > data.height ),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.originalPosition.top + this.originalSize.height,
			cw = /sw|nw|w/.test( a ), ch = /nw|ne|n/.test( a );
		if ( isminw ) {
			data.width = o.minWidth;
		}
		if ( isminh ) {
			data.height = o.minHeight;
		}
		if ( ismaxw ) {
			data.width = o.maxWidth;
		}
		if ( ismaxh ) {
			data.height = o.maxHeight;
		}

		if ( isminw && cw ) {
			data.left = dw - o.minWidth;
		}
		if ( ismaxw && cw ) {
			data.left = dw - o.maxWidth;
		}
		if ( isminh && ch ) {
			data.top = dh - o.minHeight;
		}
		if ( ismaxh && ch ) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if ( !data.width && !data.height && !data.left && data.top ) {
			data.top = null;
		} else if ( !data.width && !data.height && !data.top && data.left ) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseFloat( borders[ i ] ) || 0 );
			widths[ i ] += ( parseFloat( paddings[ i ] ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if ( !this._proportionallyResizeElements.length ) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++ ) {

			prel = this._proportionallyResizeElements[ i ];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if ( !this.outerDimensions ) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css( {
				height: ( element.height() - this.outerDimensions.height ) || 0,
				width: ( element.width() - this.outerDimensions.width ) || 0
			} );

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if ( this._helper ) {

			this.helper = this.helper || $( "<div></div>" ).css( { overflow: "hidden" } );

			this._addClass( this.helper, this._helper );
			this.helper.css( {
				width: this.element.outerWidth(),
				height: this.element.outerHeight(),
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			} );

			this.helper
				.appendTo( "body" )
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function( event, dx ) {
			return { width: this.originalSize.width + dx };
		},
		w: function( event, dx ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function( event, dx, dy ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function( event, dx, dy ) {
			return { height: this.originalSize.height + dy };
		},
		se: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		sw: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		},
		ne: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		nw: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		}
	},

	_propagate: function( n, event ) {
		$.ui.plugin.call( this, n, [ event, this.ui() ] );
		if ( n !== "resize" ) {
			this._trigger( n, event, this.ui() );
		}
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

} );

/*
 * Resizable Extensions
 */

$.ui.plugin.add( "resizable", "animate", {

	stop: function( event ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName ),
			soffseth = ista && that._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = {
				width: ( that.size.width - soffsetw ),
				height: ( that.size.height - soffseth )
			},
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null,
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

		that.element.animate(
			$.extend( style, top && left ? { top: top, left: left } : {} ), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseFloat( that.element.css( "width" ) ),
						height: parseFloat( that.element.css( "height" ) ),
						top: parseFloat( that.element.css( "top" ) ),
						left: parseFloat( that.element.css( "left" ) )
					};

					if ( pr && pr.length ) {
						$( pr[ 0 ] ).css( { width: data.width, height: data.height } );
					}

					// Propagating resize, and updating values for each animation step
					that._updateCache( data );
					that._propagate( "resize", event );

				}
			}
		);
	}

} );

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ?
				oc.get( 0 ) :
				( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$( [ "Top", "Right", "Left", "Bottom" ] ).each( function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			} );

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll( ce ) ? ce.scrollHeight : ch );

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			( that._helper ?
				that.offset.left - cop.left :
				( that.offset.left - co.left ) ) );

		hoset = Math.abs( that.sizeDiff.height +
			( that._helper ?
				that.offset.top - cop.top :
				( that.offset.top - co.top ) ) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}
	}
} );

$.ui.plugin.add( "resizable", "alsoResize", {

	start: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options;

		$( o.alsoResize ).each( function() {
			var el = $( this );
			el.data( "ui-resizable-alsoresize", {
				width: parseFloat( el.width() ), height: parseFloat( el.height() ),
				left: parseFloat( el.css( "left" ) ), top: parseFloat( el.css( "top" ) )
			} );
		} );
	},

	resize: function( event, ui ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: ( that.size.height - os.height ) || 0,
				width: ( that.size.width - os.width ) || 0,
				top: ( that.position.top - op.top ) || 0,
				left: ( that.position.left - op.left ) || 0
			};

			$( o.alsoResize ).each( function() {
				var el = $( this ), start = $( this ).data( "ui-resizable-alsoresize" ), style = {},
					css = el.parents( ui.originalElement[ 0 ] ).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each( css, function( i, prop ) {
					var sum = ( start[ prop ] || 0 ) + ( delta[ prop ] || 0 );
					if ( sum && sum >= 0 ) {
						style[ prop ] = sum || null;
					}
				} );

				el.css( style );
			} );
	},

	stop: function() {
		$( this ).removeData( "ui-resizable-alsoresize" );
	}
} );

$.ui.plugin.add( "resizable", "ghost", {

	start: function() {

		var that = $( this ).resizable( "instance" ), cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost.css( {
			opacity: 0.25,
			display: "block",
			position: "relative",
			height: cs.height,
			width: cs.width,
			margin: 0,
			left: 0,
			top: 0
		} );

		that._addClass( that.ghost, "ui-resizable-ghost" );

		// DEPRECATED
		// TODO: remove after 1.12
		if ( $.uiBackCompat !== false && typeof that.options.ghost === "string" ) {

			// Ghost option
			that.ghost.addClass( this.options.ghost );
		}

		that.ghost.appendTo( that.helper );

	},

	resize: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost ) {
			that.ghost.css( {
				position: "relative",
				height: that.size.height,
				width: that.size.width
			} );
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost && that.helper ) {
			that.helper.get( 0 ).removeChild( that.ghost.get( 0 ) );
		}
	}

} );

$.ui.plugin.add( "resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = ( grid[ 0 ] || 1 ),
			gridY = ( grid[ 1 ] || 1 ),
			ox = Math.round( ( cs.width - os.width ) / gridX ) * gridX,
			oy = Math.round( ( cs.height - os.height ) / gridY ) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && ( o.maxWidth < newWidth ),
			isMaxHeight = o.maxHeight && ( o.maxHeight < newHeight ),
			isMinWidth = o.minWidth && ( o.minWidth > newWidth ),
			isMinHeight = o.minHeight && ( o.minHeight > newHeight );

		o.grid = grid;

		if ( isMinWidth ) {
			newWidth += gridX;
		}
		if ( isMinHeight ) {
			newHeight += gridY;
		}
		if ( isMaxWidth ) {
			newWidth -= gridX;
		}
		if ( isMaxHeight ) {
			newHeight -= gridY;
		}

		if ( /^(se|s|e)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if ( /^(ne)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if ( /^(sw)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0 ) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

} );

return $.ui.resizable;

} );














/*!
 * jQuery UI Dialog 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Dialog
//>>group: Widgets
//>>description: Displays customizable dialog windows.
//>>docs: http://api.jqueryui.com/dialog/
//>>demos: http://jqueryui.com/dialog/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/dialog.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./button",
			"./draggable",
			"./mouse",
			"./resizable",
			"../focusable",
			"../keycode",
			"../position",
			"../safe-active-element",
			"../safe-blur",
			"../tabbable",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.dialog", {
	version: "1.13.0",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		classes: {
			"ui-dialog": "ui-corner-all",
			"ui-dialog-titlebar": "ui-corner-all"
		},
		closeOnEscape: true,
		closeText: "Close",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",

			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// Callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		if ( this.options.title == null && this.originalTitle != null ) {
			this.options.title = this.originalTitle;
		}

		// Dialogs can't be disabled
		if ( this.options.disabled ) {
			this.options.disabled = false;
		}

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.appendTo( this.uiDialog );

		this._addClass( "ui-dialog-content", "ui-widget-content" );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && ( element.jquery || element.nodeType ) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.css( this.originalCss )

			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );

		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).trigger( "focus" ).length ) {

			// Hiding a focused element doesn't trigger blur in WebKit
			// so in case we have nothing to focus on, explicitly blur the active element
			// https://bugs.webkit.org/show_bug.cgi?id=47182
			$.ui.safeBlur( $.ui.safeActiveElement( this.document[ 0 ] ) );
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		} );
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map( function() {
				return +$( this ).css( "z-index" );
			} ).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( $.ui.safeActiveElement( this.document[ 0 ] ) );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		} );

		// Track the dialog immediately upon opening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {

		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).trigger( "focus" );
	},

	_restoreTabbableFocus: function() {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			isActive = this.uiDialog[ 0 ] === activeElement ||
				$.contains( this.uiDialog[ 0 ], activeElement );
		if ( !isActive ) {
			this._focusTabbable();
		}
	},

	_keepFocus: function( event ) {
		event.preventDefault();
		this._restoreTabbableFocus();

		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( this._restoreTabbableFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $( "<div>" )
			.hide()
			.attr( {

				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			} )
			.appendTo( this._appendTo() );

		this._addClass( this.uiDialog, "ui-dialog", "ui-widget ui-widget-content ui-front" );
		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// Prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.first(),
					last = tabbables.last();

				if ( ( event.target === last[ 0 ] || event.target === this.uiDialog[ 0 ] ) &&
						!event.shiftKey ) {
					this._delay( function() {
						first.trigger( "focus" );
					} );
					event.preventDefault();
				} else if ( ( event.target === first[ 0 ] ||
						event.target === this.uiDialog[ 0 ] ) && event.shiftKey ) {
					this._delay( function() {
						last.trigger( "focus" );
					} );
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		} );

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr( {
				"aria-describedby": this.element.uniqueId().attr( "id" )
			} );
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" );
		this._addClass( this.uiDialogTitlebar,
			"ui-dialog-titlebar", "ui-widget-header ui-helper-clearfix" );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {

				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {

					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.trigger( "focus" );
				}
			}
		} );

		// Support: IE
		// Use type="button" to prevent enter keypresses in textboxes from closing the
		// dialog in IE (#9312)
		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button( {
				label: $( "<a>" ).text( this.options.closeText ).html(),
				icon: "ui-icon-closethick",
				showLabel: false
			} )
			.appendTo( this.uiDialogTitlebar );

		this._addClass( this.uiDialogTitlebarClose, "ui-dialog-titlebar-close" );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		} );

		uiDialogTitle = $( "<span>" ).uniqueId().prependTo( this.uiDialogTitlebar );
		this._addClass( uiDialogTitle, "ui-dialog-title" );
		this._title( uiDialogTitle );

		this.uiDialogTitlebar.prependTo( this.uiDialog );

		this.uiDialog.attr( {
			"aria-labelledby": uiDialogTitle.attr( "id" )
		} );
	},

	_title: function( title ) {
		if ( this.options.title ) {
			title.text( this.options.title );
		} else {
			title.html( "&#160;" );
		}
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" );
		this._addClass( this.uiDialogButtonPane, "ui-dialog-buttonpane",
			"ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.appendTo( this.uiDialogButtonPane );
		this._addClass( this.uiButtonSet, "ui-dialog-buttonset" );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// If we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ( Array.isArray( buttons ) && !buttons.length ) ) {
			this._removeClass( this.uiDialog, "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = typeof props === "function" ?
				{ click: props, text: name } :
				props;

			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );

			// Change the context for the click callback to be the main element
			click = props.click;
			buttonOptions = {
				icon: props.icon,
				iconPosition: props.iconPosition,
				showLabel: props.showLabel,

				// Deprecated options
				icons: props.icons,
				text: props.text
			};

			delete props.click;
			delete props.icon;
			delete props.iconPosition;
			delete props.showLabel;

			// Deprecated options
			delete props.icons;
			if ( typeof props.text === "boolean" ) {
				delete props.text;
			}

			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet )
				.on( "click", function() {
					click.apply( that.element[ 0 ], arguments );
				} );
		} );
		this._addClass( this.uiDialog, "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable( {
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		} );
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,

			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css( "position" ),
			resizeHandles = typeof handles === "string" ?
				handles :
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable( {
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		} )
			.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		} );
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {

		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		} );

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button( {

				// Ensure that we always pass a string
				label: $( "<a>" ).text( "" + this.options.closeText ).html()
			} );
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {

			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// Currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// Currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

	_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 jqMinor = $.fn.jquery.substring( 0, 4 );

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay( function() {
			isOpening = false;
		} );

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// This doesn't use `_on()` because it is a shared event handler
			// across all open modal dialogs.
			this.document.on( "focusin.ui-dialog", function( event ) {
				if ( isOpening ) {
					return;
				}

				var instance = this._trackingInstances()[ 0 ];
				if ( !instance._allowInteraction( event ) ) {
					event.preventDefault();
					instance._focusTabbable();

					// Support: jQuery >=3.4 <3.6 only
					// Focus re-triggering in jQuery 3.4/3.5 makes the original element
					// have its focus event propagated last, breaking the re-targeting.
					// Trigger focus in a delay in addition if needed to avoid the issue
					// See https://github.com/jquery/jquery/issues/4382
					if ( jqMinor === "3.4." || jqMinor === "3.5." ) {
						instance._delay( instance._restoreTabbableFocus );
					}
				}
			}.bind( this ) );
		}

		this.overlay = $( "<div>" )
			.appendTo( this._appendTo() );

		this._addClass( this.overlay, null, "ui-widget-overlay ui-front" );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		} );
		this.document.data( "ui-dialog-overlays",
			( this.document.data( "ui-dialog-overlays" ) || 0 ) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this.document.off( "focusin.ui-dialog" );
				this.document.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for dialogClass option
	$.widget( "ui.dialog", $.ui.dialog, {
		options: {
			dialogClass: ""
		},
		_createWrapper: function() {
			this._super();
			this.uiDialog.addClass( this.options.dialogClass );
		},
		_setOption: function( key, value ) {
			if ( key === "dialogClass" ) {
				this.uiDialog
					.removeClass( this.options.dialogClass )
					.addClass( value );
			}
			this._superApply( arguments );
		}
	} );
}

return $.ui.dialog;

} );





/*!
 * jQuery UI Droppable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Droppable
//>>group: Interactions
//>>description: Enables drop targets for draggable elements.
//>>docs: http://api.jqueryui.com/droppable/
//>>demos: http://jqueryui.com/droppable/

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./draggable",
			"./mouse",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.droppable", {
	version: "1.13.0",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		addClasses: true,
		greedy: false,
		scope: "default",
		tolerance: "intersect",

		// Callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var proportions,
			o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = typeof accept === "function" ? accept : function( d ) {
			return d.is( accept );
		};

		this.proportions = function( /* valueToWrite */ ) {
			if ( arguments.length ) {

				// Store the droppable's proportions
				proportions = arguments[ 0 ];
			} else {

				// Retrieve or derive the droppable's proportions
				return proportions ?
					proportions :
					proportions = {
						width: this.element[ 0 ].offsetWidth,
						height: this.element[ 0 ].offsetHeight
					};
			}
		};

		this._addToManager( o.scope );

		if ( o.addClasses ) {
			this._addClass( "ui-droppable" );
		}

	},

	_addToManager: function( scope ) {

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
		$.ui.ddmanager.droppables[ scope ].push( this );
	},

	_splice: function( drop ) {
		var i = 0;
		for ( ; i < drop.length; i++ ) {
			if ( drop[ i ] === this ) {
				drop.splice( i, 1 );
			}
		}
	},

	_destroy: function() {
		var drop = $.ui.ddmanager.droppables[ this.options.scope ];

		this._splice( drop );
	},

	_setOption: function( key, value ) {

		if ( key === "accept" ) {
			this.accept = typeof value === "function" ? value : function( d ) {
				return d.is( value );
			};
		} else if ( key === "scope" ) {
			var drop = $.ui.ddmanager.droppables[ this.options.scope ];

			this._splice( drop );
			this._addToManager( value );
		}

		this._super( key, value );
	},

	_activate: function( event ) {
		var draggable = $.ui.ddmanager.current;

		this._addActiveClass();
		if ( draggable ) {
			this._trigger( "activate", event, this.ui( draggable ) );
		}
	},

	_deactivate: function( event ) {
		var draggable = $.ui.ddmanager.current;

		this._removeActiveClass();
		if ( draggable ) {
			this._trigger( "deactivate", event, this.ui( draggable ) );
		}
	},

	_over: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
				draggable.element ) ) ) {
			this._addHoverClass();
			this._trigger( "over", event, this.ui( draggable ) );
		}

	},

	_out: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
				draggable.element ) ) ) {
			this._removeHoverClass();
			this._trigger( "out", event, this.ui( draggable ) );
		}

	},

	_drop: function( event, custom ) {

		var draggable = custom || $.ui.ddmanager.current,
			childrenIntersection = false;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem ||
				draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return false;
		}

		this.element
			.find( ":data(ui-droppable)" )
			.not( ".ui-draggable-dragging" )
			.each( function() {
				var inst = $( this ).droppable( "instance" );
				if (
					inst.options.greedy &&
					!inst.options.disabled &&
					inst.options.scope === draggable.options.scope &&
					inst.accept.call(
						inst.element[ 0 ], ( draggable.currentItem || draggable.element )
					) &&
					$.ui.intersect(
						draggable,
						$.extend( inst, { offset: inst.element.offset() } ),
						inst.options.tolerance, event
					)
				) {
					childrenIntersection = true;
					return false;
				}
			} );
		if ( childrenIntersection ) {
			return false;
		}

		if ( this.accept.call( this.element[ 0 ],
				( draggable.currentItem || draggable.element ) ) ) {
			this._removeActiveClass();
			this._removeHoverClass();

			this._trigger( "drop", event, this.ui( draggable ) );
			return this.element;
		}

		return false;

	},

	ui: function( c ) {
		return {
			draggable: ( c.currentItem || c.element ),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	},

	// Extension points just to make backcompat sane and avoid duplicating logic
	// TODO: Remove in 1.14 along with call to it below
	_addHoverClass: function() {
		this._addClass( "ui-droppable-hover" );
	},

	_removeHoverClass: function() {
		this._removeClass( "ui-droppable-hover" );
	},

	_addActiveClass: function() {
		this._addClass( "ui-droppable-active" );
	},

	_removeActiveClass: function() {
		this._removeClass( "ui-droppable-active" );
	}
} );

$.ui.intersect = ( function() {
	function isOverAxis( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	}

	return function( draggable, droppable, toleranceMode, event ) {

		if ( !droppable.offset ) {
			return false;
		}

		var x1 = ( draggable.positionAbs ||
				draggable.position.absolute ).left + draggable.margins.left,
			y1 = ( draggable.positionAbs ||
				draggable.position.absolute ).top + draggable.margins.top,
			x2 = x1 + draggable.helperProportions.width,
			y2 = y1 + draggable.helperProportions.height,
			l = droppable.offset.left,
			t = droppable.offset.top,
			r = l + droppable.proportions().width,
			b = t + droppable.proportions().height;

		switch ( toleranceMode ) {
		case "fit":
			return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
		case "intersect":
			return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
				x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
		case "pointer":
			return isOverAxis( event.pageY, t, droppable.proportions().height ) &&
				isOverAxis( event.pageX, l, droppable.proportions().width );
		case "touch":
			return (
				( y1 >= t && y1 <= b ) || // Top edge touching
				( y2 >= t && y2 <= b ) || // Bottom edge touching
				( y1 < t && y2 > b ) // Surrounded vertically
			) && (
				( x1 >= l && x1 <= r ) || // Left edge touching
				( x2 >= l && x2 <= r ) || // Right edge touching
				( x1 < l && x2 > r ) // Surrounded horizontally
			);
		default:
			return false;
		}
	};
} )();

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { "default": [] },
	prepareOffsets: function( t, event ) {

		var i, j,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			type = event ? event.type : null, // workaround for #2317
			list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();

		droppablesLoop: for ( i = 0; i < m.length; i++ ) {

			// No disabled and non-accepted
			if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ],
					( t.currentItem || t.element ) ) ) ) {
				continue;
			}

			// Filter out elements in the current dragged item
			for ( j = 0; j < list.length; j++ ) {
				if ( list[ j ] === m[ i ].element[ 0 ] ) {
					m[ i ].proportions().height = 0;
					continue droppablesLoop;
				}
			}

			m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
			if ( !m[ i ].visible ) {
				continue;
			}

			// Activate the droppable if used directly from draggables
			if ( type === "mousedown" ) {
				m[ i ]._activate.call( m[ i ], event );
			}

			m[ i ].offset = m[ i ].element.offset();
			m[ i ].proportions( {
				width: m[ i ].element[ 0 ].offsetWidth,
				height: m[ i ].element[ 0 ].offsetHeight
			} );

		}

	},
	drop: function( draggable, event ) {

		var dropped = false;

		// Create a copy of the droppables in case the list changes during the drop (#9116)
		$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {

			if ( !this.options ) {
				return;
			}
			if ( !this.options.disabled && this.visible &&
					$.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
				dropped = this._drop.call( this, event ) || dropped;
			}

			if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ],
					( draggable.currentItem || draggable.element ) ) ) {
				this.isout = true;
				this.isover = false;
				this._deactivate.call( this, event );
			}

		} );
		return dropped;

	},
	dragStart: function( draggable, event ) {

		// Listen for scrolling so that if the dragging causes scrolling the position of the
		// droppables can be recalculated (see #5003)
		draggable.element.parentsUntil( "body" ).on( "scroll.droppable", function() {
			if ( !draggable.options.refreshPositions ) {
				$.ui.ddmanager.prepareOffsets( draggable, event );
			}
		} );
	},
	drag: function( draggable, event ) {

		// If you have a highly dynamic page, you might try this option. It renders positions
		// every time you move the mouse.
		if ( draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}

		// Run through all droppables and check their positions based on specific tolerance options
		$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {

			if ( this.options.disabled || this.greedyChild || !this.visible ) {
				return;
			}

			var parentInstance, scope, parent,
				intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
				c = !intersects && this.isover ?
					"isout" :
					( intersects && !this.isover ? "isover" : null );
			if ( !c ) {
				return;
			}

			if ( this.options.greedy ) {

				// find droppable parents with same scope
				scope = this.options.scope;
				parent = this.element.parents( ":data(ui-droppable)" ).filter( function() {
					return $( this ).droppable( "instance" ).options.scope === scope;
				} );

				if ( parent.length ) {
					parentInstance = $( parent[ 0 ] ).droppable( "instance" );
					parentInstance.greedyChild = ( c === "isover" );
				}
			}

			// We just moved into a greedy child
			if ( parentInstance && c === "isover" ) {
				parentInstance.isover = false;
				parentInstance.isout = true;
				parentInstance._out.call( parentInstance, event );
			}

			this[ c ] = true;
			this[ c === "isout" ? "isover" : "isout" ] = false;
			this[ c === "isover" ? "_over" : "_out" ].call( this, event );

			// We just moved out of a greedy child
			if ( parentInstance && c === "isout" ) {
				parentInstance.isout = false;
				parentInstance.isover = true;
				parentInstance._over.call( parentInstance, event );
			}
		} );

	},
	dragStop: function( draggable, event ) {
		draggable.element.parentsUntil( "body" ).off( "scroll.droppable" );

		// Call prepareOffsets one final time since IE does not fire return scroll events when
		// overflow was caused by drag (see #5003)
		if ( !draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}
	}
};

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for activeClass and hoverClass options
	$.widget( "ui.droppable", $.ui.droppable, {
		options: {
			hoverClass: false,
			activeClass: false
		},
		_addActiveClass: function() {
			this._super();
			if ( this.options.activeClass ) {
				this.element.addClass( this.options.activeClass );
			}
		},
		_removeActiveClass: function() {
			this._super();
			if ( this.options.activeClass ) {
				this.element.removeClass( this.options.activeClass );
			}
		},
		_addHoverClass: function() {
			this._super();
			if ( this.options.hoverClass ) {
				this.element.addClass( this.options.hoverClass );
			}
		},
		_removeHoverClass: function() {
			this._super();
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
		}
	} );
}

return $.ui.droppable;

} );



/*!
 * jQuery UI Progressbar 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Progressbar
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Displays a status indicator for loading state, standard percentage, and other progress indicators.
/* eslint-enable max-len */
//>>docs: http://api.jqueryui.com/progressbar/
//>>demos: http://jqueryui.com/progressbar/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/progressbar.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.progressbar", {
	version: "1.13.0",
	options: {
		classes: {
			"ui-progressbar": "ui-corner-all",
			"ui-progressbar-value": "ui-corner-left",
			"ui-progressbar-complete": "ui-corner-right"
		},
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {

		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element.attr( {

			// Only set static values; aria-valuenow and aria-valuemax are
			// set inside _refreshValue()
			role: "progressbar",
			"aria-valuemin": this.min
		} );
		this._addClass( "ui-progressbar", "ui-widget ui-widget-content" );

		this.valueDiv = $( "<div>" ).appendTo( this.element );
		this._addClass( this.valueDiv, "ui-progressbar-value", "ui-widget-header" );
		this._refreshValue();
	},

	_destroy: function() {
		this.element.removeAttr( "role aria-valuemin aria-valuemax aria-valuenow" );

		this.valueDiv.remove();
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this.options.value;
		}

		this.options.value = this._constrainedValue( newValue );
		this._refreshValue();
	},

	_constrainedValue: function( newValue ) {
		if ( newValue === undefined ) {
			newValue = this.options.value;
		}

		this.indeterminate = newValue === false;

		// Sanitize value
		if ( typeof newValue !== "number" ) {
			newValue = 0;
		}

		return this.indeterminate ? false :
			Math.min( this.options.max, Math.max( this.min, newValue ) );
	},

	_setOptions: function( options ) {

		// Ensure "value" option is set after other values (like max)
		var value = options.value;
		delete options.value;

		this._super( options );

		this.options.value = this._constrainedValue( value );
		this._refreshValue();
	},

	_setOption: function( key, value ) {
		if ( key === "max" ) {

			// Don't allow a max less than min
			value = Math.max( this.min, value );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", value );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	_percentage: function() {
		return this.indeterminate ?
			100 :
			100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
	},

	_refreshValue: function() {
		var value = this.options.value,
			percentage = this._percentage();

		this.valueDiv
			.toggle( this.indeterminate || value > this.min )
			.width( percentage.toFixed( 0 ) + "%" );

		this
			._toggleClass( this.valueDiv, "ui-progressbar-complete", null,
				value === this.options.max )
			._toggleClass( "ui-progressbar-indeterminate", null, this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div>" ).appendTo( this.valueDiv );
				this._addClass( this.overlayDiv, "ui-progressbar-overlay" );
			}
		} else {
			this.element.attr( {
				"aria-valuemax": this.options.max,
				"aria-valuenow": value
			} );
			if ( this.overlayDiv ) {
				this.overlayDiv.remove();
				this.overlayDiv = null;
			}
		}

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}
		if ( value === this.options.max ) {
			this._trigger( "complete" );
		}
	}
} );

} );




/*!
 * jQuery UI Selectable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Selectable
//>>group: Interactions
//>>description: Allows groups of elements to be selected with the mouse.
//>>docs: http://api.jqueryui.com/selectable/
//>>demos: http://jqueryui.com/selectable/
//>>css.structure: ../../themes/base/selectable.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./mouse",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.selectable", $.ui.mouse, {
	version: "1.13.0",
	options: {
		appendTo: "body",
		autoRefresh: true,
		distance: 0,
		filter: "*",
		tolerance: "touch",

		// Callbacks
		selected: null,
		selecting: null,
		start: null,
		stop: null,
		unselected: null,
		unselecting: null
	},
	_create: function() {
		var that = this;

		this._addClass( "ui-selectable" );

		this.dragged = false;

		// Cache selectee children based on filter
		this.refresh = function() {
			that.elementPos = $( that.element[ 0 ] ).offset();
			that.selectees = $( that.options.filter, that.element[ 0 ] );
			that._addClass( that.selectees, "ui-selectee" );
			that.selectees.each( function() {
				var $this = $( this ),
					selecteeOffset = $this.offset(),
					pos = {
						left: selecteeOffset.left - that.elementPos.left,
						top: selecteeOffset.top - that.elementPos.top
					};
				$.data( this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass( "ui-selected" ),
					selecting: $this.hasClass( "ui-selecting" ),
					unselecting: $this.hasClass( "ui-unselecting" )
				} );
			} );
		};
		this.refresh();

		this._mouseInit();

		this.helper = $( "<div>" );
		this._addClass( this.helper, "ui-selectable-helper" );
	},

	_destroy: function() {
		this.selectees.removeData( "selectable-item" );
		this._mouseDestroy();
	},

	_mouseStart: function( event ) {
		var that = this,
			options = this.options;

		this.opos = [ event.pageX, event.pageY ];
		this.elementPos = $( this.element[ 0 ] ).offset();

		if ( this.options.disabled ) {
			return;
		}

		this.selectees = $( options.filter, this.element[ 0 ] );

		this._trigger( "start", event );

		$( options.appendTo ).append( this.helper );

		// position helper (lasso)
		this.helper.css( {
			"left": event.pageX,
			"top": event.pageY,
			"width": 0,
			"height": 0
		} );

		if ( options.autoRefresh ) {
			this.refresh();
		}

		this.selectees.filter( ".ui-selected" ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			selectee.startselected = true;
			if ( !event.metaKey && !event.ctrlKey ) {
				that._removeClass( selectee.$element, "ui-selected" );
				selectee.selected = false;
				that._addClass( selectee.$element, "ui-unselecting" );
				selectee.unselecting = true;

				// selectable UNSELECTING callback
				that._trigger( "unselecting", event, {
					unselecting: selectee.element
				} );
			}
		} );

		$( event.target ).parents().addBack().each( function() {
			var doSelect,
				selectee = $.data( this, "selectable-item" );
			if ( selectee ) {
				doSelect = ( !event.metaKey && !event.ctrlKey ) ||
					!selectee.$element.hasClass( "ui-selected" );
				that._removeClass( selectee.$element, doSelect ? "ui-unselecting" : "ui-selected" )
					._addClass( selectee.$element, doSelect ? "ui-selecting" : "ui-unselecting" );
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;

				// selectable (UN)SELECTING callback
				if ( doSelect ) {
					that._trigger( "selecting", event, {
						selecting: selectee.element
					} );
				} else {
					that._trigger( "unselecting", event, {
						unselecting: selectee.element
					} );
				}
				return false;
			}
		} );

	},

	_mouseDrag: function( event ) {

		this.dragged = true;

		if ( this.options.disabled ) {
			return;
		}

		var tmp,
			that = this,
			options = this.options,
			x1 = this.opos[ 0 ],
			y1 = this.opos[ 1 ],
			x2 = event.pageX,
			y2 = event.pageY;

		if ( x1 > x2 ) {
			tmp = x2; x2 = x1; x1 = tmp;
		}
		if ( y1 > y2 ) {
			tmp = y2; y2 = y1; y1 = tmp;
		}
		this.helper.css( { left: x1, top: y1, width: x2 - x1, height: y2 - y1 } );

		this.selectees.each( function() {
			var selectee = $.data( this, "selectable-item" ),
				hit = false,
				offset = {};

			//prevent helper from being selected if appendTo: selectable
			if ( !selectee || selectee.element === that.element[ 0 ] ) {
				return;
			}

			offset.left   = selectee.left   + that.elementPos.left;
			offset.right  = selectee.right  + that.elementPos.left;
			offset.top    = selectee.top    + that.elementPos.top;
			offset.bottom = selectee.bottom + that.elementPos.top;

			if ( options.tolerance === "touch" ) {
				hit = ( !( offset.left > x2 || offset.right < x1 || offset.top > y2 ||
                    offset.bottom < y1 ) );
			} else if ( options.tolerance === "fit" ) {
				hit = ( offset.left > x1 && offset.right < x2 && offset.top > y1 &&
                    offset.bottom < y2 );
			}

			if ( hit ) {

				// SELECT
				if ( selectee.selected ) {
					that._removeClass( selectee.$element, "ui-selected" );
					selectee.selected = false;
				}
				if ( selectee.unselecting ) {
					that._removeClass( selectee.$element, "ui-unselecting" );
					selectee.unselecting = false;
				}
				if ( !selectee.selecting ) {
					that._addClass( selectee.$element, "ui-selecting" );
					selectee.selecting = true;

					// selectable SELECTING callback
					that._trigger( "selecting", event, {
						selecting: selectee.element
					} );
				}
			} else {

				// UNSELECT
				if ( selectee.selecting ) {
					if ( ( event.metaKey || event.ctrlKey ) && selectee.startselected ) {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						that._addClass( selectee.$element, "ui-selected" );
						selectee.selected = true;
					} else {
						that._removeClass( selectee.$element, "ui-selecting" );
						selectee.selecting = false;
						if ( selectee.startselected ) {
							that._addClass( selectee.$element, "ui-unselecting" );
							selectee.unselecting = true;
						}

						// selectable UNSELECTING callback
						that._trigger( "unselecting", event, {
							unselecting: selectee.element
						} );
					}
				}
				if ( selectee.selected ) {
					if ( !event.metaKey && !event.ctrlKey && !selectee.startselected ) {
						that._removeClass( selectee.$element, "ui-selected" );
						selectee.selected = false;

						that._addClass( selectee.$element, "ui-unselecting" );
						selectee.unselecting = true;

						// selectable UNSELECTING callback
						that._trigger( "unselecting", event, {
							unselecting: selectee.element
						} );
					}
				}
			}
		} );

		return false;
	},

	_mouseStop: function( event ) {
		var that = this;

		this.dragged = false;

		$( ".ui-unselecting", this.element[ 0 ] ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			that._removeClass( selectee.$element, "ui-unselecting" );
			selectee.unselecting = false;
			selectee.startselected = false;
			that._trigger( "unselected", event, {
				unselected: selectee.element
			} );
		} );
		$( ".ui-selecting", this.element[ 0 ] ).each( function() {
			var selectee = $.data( this, "selectable-item" );
			that._removeClass( selectee.$element, "ui-selecting" )
				._addClass( selectee.$element, "ui-selected" );
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			that._trigger( "selected", event, {
				selected: selectee.element
			} );
		} );
		this._trigger( "stop", event );

		this.helper.remove();

		return false;
	}

} );

} );









/*!
 * jQuery UI Selectmenu 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Selectmenu
//>>group: Widgets
/* eslint-disable max-len */
//>>description: Duplicates and extends the functionality of a native HTML select element, allowing it to be customizable in behavior and appearance far beyond the limitations of a native select.
/* eslint-enable max-len */
//>>docs: http://api.jqueryui.com/selectmenu/
//>>demos: http://jqueryui.com/selectmenu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/selectmenu.css, ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./menu",
			"../form-reset-mixin",
			"../keycode",
			"../labels",
			"../position",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.selectmenu", [ $.ui.formResetMixin, {
	version: "1.13.0",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		classes: {
			"ui-selectmenu-button-open": "ui-corner-top",
			"ui-selectmenu-button-closed": "ui-corner-all"
		},
		disabled: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		width: false,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();
		this._bindFormResetHandler();

		this._rendered = false;
		this.menuItems = $();
	},

	_drawButton: function() {
		var icon,
			that = this,
			item = this._parseOption(
				this.element.find( "option:selected" ),
				this.element[ 0 ].selectedIndex
			);

		// Associate existing label with the new button
		this.labels = this.element.labels().attr( "for", this.ids.button );
		this._on( this.labels, {
			click: function( event ) {
				this.button.trigger( "focus" );
				event.preventDefault();
			}
		} );

		// Hide original select element
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			tabindex: this.options.disabled ? -1 : 0,
			id: this.ids.button,
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true",
			title: this.element.attr( "title" )
		} )
			.insertAfter( this.element );

		this._addClass( this.button, "ui-selectmenu-button ui-selectmenu-button-closed",
			"ui-button ui-widget" );

		icon = $( "<span>" ).appendTo( this.button );
		this._addClass( icon, "ui-selectmenu-icon", "ui-icon " + this.options.icons.button );
		this.buttonItem = this._renderButtonItem( item )
			.appendTo( this.button );

		if ( this.options.width !== false ) {
			this._resizeButton();
		}

		this._on( this.button, this._buttonEvents );
		this.button.one( "focusin", function() {

			// Delay rendering the menu items until the button receives focus.
			// The menu may have already been rendered via a programmatic open.
			if ( !that._rendered ) {
				that._refreshMenu();
			}
		} );
	},

	_drawMenu: function() {
		var that = this;

		// Create menu
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		} );

		// Wrap menu
		this.menuWrap = $( "<div>" ).append( this.menu );
		this._addClass( this.menuWrap, "ui-selectmenu-menu", "ui-front" );
		this.menuWrap.appendTo( this._appendTo() );

		// Initialize menu widget
		this.menuInstance = this.menu
			.menu( {
				classes: {
					"ui-menu": "ui-corner-bottom"
				},
				role: "listbox",
				select: function( event, ui ) {
					event.preventDefault();

					// Support: IE8
					// If the item was selected via a click, the text selection
					// will be destroyed in IE
					that._setSelection();

					that._select( ui.item.data( "ui-selectmenu-item" ), event );
				},
				focus: function( event, ui ) {
					var item = ui.item.data( "ui-selectmenu-item" );

					// Prevent inital focus from firing and check if its a newly focused item
					if ( that.focusIndex != null && item.index !== that.focusIndex ) {
						that._trigger( "focus", event, { item: item } );
						if ( !that.isOpen ) {
							that._select( item, event );
						}
					}
					that.focusIndex = item.index;

					that.button.attr( "aria-activedescendant",
						that.menuItems.eq( item.index ).attr( "id" ) );
				}
			} )
			.menu( "instance" );

		// Don't close the menu on mouseleave
		this.menuInstance._off( this.menu, "mouseleave" );

		// Cancel the menu's collapseAll on document click
		this.menuInstance._closeOnDocumentClick = function() {
			return false;
		};

		// Selects often contain empty items, but never contain dividers
		this.menuInstance._isDivider = function() {
			return false;
		};
	},

	refresh: function() {
		this._refreshMenu();
		this.buttonItem.replaceWith(
			this.buttonItem = this._renderButtonItem(

				// Fall back to an empty object in case there are no options
				this._getSelectedItem().data( "ui-selectmenu-item" ) || {}
			)
		);
		if ( this.options.width === null ) {
			this._resizeButton();
		}
	},

	_refreshMenu: function() {
		var item,
			options = this.element.find( "option" );

		this.menu.empty();

		this._parseOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menuInstance.refresh();
		this.menuItems = this.menu.find( "li" )
			.not( ".ui-selectmenu-optgroup" )
				.find( ".ui-menu-item-wrapper" );

		this._rendered = true;

		if ( !options.length ) {
			return;
		}

		item = this._getSelectedItem();

		// Update the menu to have the correct item focused
		this.menuInstance.focus( null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}

		// If this is the first time the menu is being opened, render the items
		if ( !this._rendered ) {
			this._refreshMenu();
		} else {

			// Menu clears focus on close, reset focus to selected item
			this._removeClass( this.menu.find( ".ui-state-active" ), null, "ui-state-active" );
			this.menuInstance.focus( null, this._getSelectedItem() );
		}

		// If there are no options, don't open the menu
		if ( !this.menuItems.length ) {
			return;
		}

		this.isOpen = true;
		this._toggleAttr();
		this._resizeMenu();
		this._position();

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	_position: function() {
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		this.range = null;
		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderButtonItem: function( item ) {
		var buttonItem = $( "<span>" );

		this._setText( buttonItem, item.label );
		this._addClass( buttonItem, "ui-selectmenu-text" );

		return buttonItem;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			var li;

			if ( item.optgroup !== currentOptgroup ) {
				li = $( "<li>", {
					text: item.optgroup
				} );
				that._addClass( li, "ui-selectmenu-optgroup", "ui-menu-divider" +
					( item.element.parent( "optgroup" ).prop( "disabled" ) ?
						" ui-state-disabled" :
						"" ) );

				li.appendTo( ul );

				currentOptgroup = item.optgroup;
			}

			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ),
			wrapper = $( "<div>", {
				title: item.element.attr( "title" )
			} );

		if ( item.disabled ) {
			this._addClass( li, null, "ui-state-disabled" );
		}
		this._setText( wrapper, item.label );

		return li.append( wrapper ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( "&#160;" );
		}
	},

	_move: function( direction, event ) {
		var item, next,
			filter = ".ui-menu-item";

		if ( this.isOpen ) {
			item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		} else {
			item = this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
			filter += ":not(.ui-state-disabled)";
		}

		if ( direction === "first" || direction === "last" ) {
			next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
		} else {
			next = item[ direction + "All" ]( filter ).eq( 0 );
		}

		if ( next.length ) {
			this.menuInstance.focus( event, next );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		this[ this.isOpen ? "close" : "open" ]( event );
	},

	_setSelection: function() {
		var selection;

		if ( !this.range ) {
			return;
		}

		if ( window.getSelection ) {
			selection = window.getSelection();
			selection.removeAllRanges();
			selection.addRange( this.range );

		// Support: IE8
		} else {
			this.range.select();
		}

		// Support: IE
		// Setting the text selection kills the button focus in IE, but
		// restoring the focus doesn't kill the selection.
		this.button.focus();
	},

	_documentClick: {
		mousedown: function( event ) {
			if ( !this.isOpen ) {
				return;
			}

			if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" +
				$.escapeSelector( this.ids.button ) ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {

		// Prevent text selection from being reset when interacting with the selectmenu (#10144)
		mousedown: function() {
			var selection;

			if ( window.getSelection ) {
				selection = window.getSelection();
				if ( selection.rangeCount ) {
					this.range = selection.getRangeAt( 0 );
				}

			// Support: IE8
			} else {
				this.range = document.selection.createRange();
			}
		},

		click: function( event ) {
			this._setSelection();
			this._toggle( event );
		},

		keydown: function( event ) {
			var preventDefault = true;
			switch ( event.keyCode ) {
			case $.ui.keyCode.TAB:
			case $.ui.keyCode.ESCAPE:
				this.close( event );
				preventDefault = false;
				break;
			case $.ui.keyCode.ENTER:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				}
				break;
			case $.ui.keyCode.UP:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "prev", event );
				}
				break;
			case $.ui.keyCode.DOWN:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "next", event );
				}
				break;
			case $.ui.keyCode.SPACE:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				} else {
					this._toggle( event );
				}
				break;
			case $.ui.keyCode.LEFT:
				this._move( "prev", event );
				break;
			case $.ui.keyCode.RIGHT:
				this._move( "next", event );
				break;
			case $.ui.keyCode.HOME:
			case $.ui.keyCode.PAGE_UP:
				this._move( "first", event );
				break;
			case $.ui.keyCode.END:
			case $.ui.keyCode.PAGE_DOWN:
				this._move( "last", event );
				break;
			default:
				this.menu.trigger( event );
				preventDefault = false;
			}

			if ( preventDefault ) {
				event.preventDefault();
			}
		}
	},

	_selectFocusedItem: function( event ) {
		var item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		if ( !item.hasClass( "ui-state-disabled" ) ) {
			this._select( item.data( "ui-selectmenu-item" ), event );
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;

		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this.buttonItem.replaceWith( this.buttonItem = this._renderButtonItem( item ) );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}

		this.close( event );
	},

	_setAria: function( item ) {
		var id = this.menuItems.eq( item.index ).attr( "id" );

		this.button.attr( {
			"aria-labelledby": id,
			"aria-activedescendant": id
		} );
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icon = this.button.find( "span.ui-icon" );
			this._removeClass( icon, null, this.options.icons.button )
				._addClass( icon, null, value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}

		if ( key === "width" ) {
			this._resizeButton();
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.menuInstance.option( "disabled", value );
		this.button.attr( "aria-disabled", value );
		this._toggleClass( this.button, null, "ui-state-disabled", value );

		this.element.prop( "disabled", value );
		if ( value ) {
			this.button.attr( "tabindex", -1 );
			this.close();
		} else {
			this.button.attr( "tabindex", 0 );
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function() {
		this.button.attr( "aria-expanded", this.isOpen );

		// We can't use two _toggleClass() calls here, because we need to make sure
		// we always remove classes first and add them second, otherwise if both classes have the
		// same theme class, it will be removed after we add it.
		this._removeClass( this.button, "ui-selectmenu-button-" +
			( this.isOpen ? "closed" : "open" ) )
			._addClass( this.button, "ui-selectmenu-button-" +
				( this.isOpen ? "open" : "closed" ) )
			._toggleClass( this.menuWrap, "ui-selectmenu-open", null, this.isOpen );

		this.menu.attr( "aria-hidden", !this.isOpen );
	},

	_resizeButton: function() {
		var width = this.options.width;

		// For `width: false`, just remove inline style and stop
		if ( width === false ) {
			this.button.css( "width", "" );
			return;
		}

		// For `width: null`, match the width of the original element
		if ( width === null ) {
			width = this.element.show().outerWidth();
			this.element.hide();
		}

		this.button.outerWidth( width );
	},

	_resizeMenu: function() {
		this.menu.outerWidth( Math.max(
			this.button.outerWidth(),

			// Support: IE10
			// IE10 wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping
			this.menu.width( "" ).outerWidth() + 1
		) );
	},

	_getCreateOptions: function() {
		var options = this._super();

		options.disabled = this.element.prop( "disabled" );

		return options;
	},

	_parseOptions: function( options ) {
		var that = this,
			data = [];
		options.each( function( index, item ) {
			if ( item.hidden ) {
				return;
			}

			data.push( that._parseOption( $( item ), index ) );
		} );
		this.items = data;
	},

	_parseOption: function( option, index ) {
		var optgroup = option.parent( "optgroup" );

		return {
			element: option,
			index: index,
			value: option.val(),
			label: option.text(),
			optgroup: optgroup.attr( "label" ) || "",
			disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
		};
	},

	_destroy: function() {
		this._unbindFormResetHandler();
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.labels.attr( "for", this.ids.element );
	}
} ] );

} );





/*!
 * jQuery UI Slider 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: http://api.jqueryui.com/slider/
//>>demos: http://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./mouse",
			"../keycode",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.slider", $.ui.mouse, {
	version: "1.13.0",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this )
				.data( "ui-slider-handle-index", i )
				.attr( "tabIndex", 0 );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( Array.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( Array.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( Array.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );

} );







/*!
 * jQuery UI Sortable 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Sortable
//>>group: Interactions
//>>description: Enables items in a list to be sorted using the mouse.
//>>docs: http://api.jqueryui.com/sortable/
//>>demos: http://jqueryui.com/sortable/
//>>css.structure: ../../themes/base/sortable.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./mouse",
			"../data",
			"../ie",
			"../scroll-parent",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.widget( "ui.sortable", $.ui.mouse, {
	version: "1.13.0",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// Callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return ( /left|right/ ).test( item.css( "float" ) ) ||
			( /inline|table-cell/ ).test( item.css( "display" ) );
	},

	_create: function() {
		this.containerCache = {};
		this._addClass( "ui-sortable" );

		//Get the items
		this.refresh();

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		var that = this;
		this._removeClass( this.element.find( ".ui-sortable-handle" ), "ui-sortable-handle" );
		$.each( this.items, function() {
			that._addClass(
				this.instance.options.handle ?
					this.item.find( this.instance.options.handle ) :
					this.item,
				"ui-sortable-handle"
			);
		} );
	},

	_destroy: function() {
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[ i ].item.removeData( this.widgetName + "-item" );
		}

		return this;
	},

	_mouseCapture: function( event, overrideHandle ) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if ( this.reverting ) {
			return false;
		}

		if ( this.options.disabled || this.options.type === "static" ) {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems( event );

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$( event.target ).parents().each( function() {
			if ( $.data( this, that.widgetName + "-item" ) === that ) {
				currentItem = $( this );
				return false;
			}
		} );
		if ( $.data( event.target, that.widgetName + "-item" ) === that ) {
			currentItem = $( event.target );
		}

		if ( !currentItem ) {
			return false;
		}
		if ( this.options.handle && !overrideHandle ) {
			$( this.options.handle, currentItem ).find( "*" ).addBack().each( function() {
				if ( this === event.target ) {
					validHandle = true;
				}
			} );
			if ( !validHandle ) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function( event, overrideHandle, noActivation ) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to
		// mouseCapture
		this.refreshPositions();

		//Prepare the dragged items parent
		this.appendTo = $( o.appendTo !== "parent" ?
				o.appendTo :
				this.currentItem.parent() );

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend( this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},

			// This is a relative to absolute position minus the actual position calculation -
			// only used for relative positioned helper
			relative: this._getRelativeOffset()
		} );

		// After we get the helper offset, but before we get the parent offset we can
		// change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css( "position", "absolute" );
		this.cssPosition = this.helper.css( "position" );

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		if ( o.cursorAt ) {
			this._adjustOffsetFromHelper( o.cursorAt );
		}

		//Cache the former DOM position
		this.domPosition = {
			prev: this.currentItem.prev()[ 0 ],
			parent: this.currentItem.parent()[ 0 ]
		};

		// If the helper is not the original, hide the original so it's not playing any role during
		// the drag, won't cause anything bad this way
		if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Get the next scrolling parent
		this.scrollParent = this.placeholder.scrollParent();

		$.extend( this.offset, {
			parent: this._getParentOffset()
		} );

		//Set a containment if given in the options
		if ( o.containment ) {
			this._setContainment();
		}

		if ( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			// Support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet =
				$( "<style>*{ cursor: " + o.cursor + " !important; }</style>" ).appendTo( body );
		}

		// We need to make sure to grab the zIndex before setting the
		// opacity, because setting the opacity to anything lower than 1
		// causes the zIndex to change from "auto" to 0.
		if ( o.zIndex ) { // zIndex option
			if ( this.helper.css( "zIndex" ) ) {
				this._storedZIndex = this.helper.css( "zIndex" );
			}
			this.helper.css( "zIndex", o.zIndex );
		}

		if ( o.opacity ) { // opacity option
			if ( this.helper.css( "opacity" ) ) {
				this._storedOpacity = this.helper.css( "opacity" );
			}
			this.helper.css( "opacity", o.opacity );
		}

		//Prepare scrolling
		if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ].tagName !== "HTML" ) {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger( "start", event, this._uiHash() );

		//Recache the helper size
		if ( !this._preserveHelperProportions ) {
			this._cacheHelperProportions();
		}

		//Post "activate" events to possible containers
		if ( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		this.dragging = true;

		this._addClass( this.helper, "ui-sortable-helper" );

		//Move the helper, if needed
		if ( !this.helper.parent().is( this.appendTo ) ) {
			this.helper.detach().appendTo( this.appendTo );

			//Update position
			this.offset.parent = this._getParentOffset();
		}

		//Generate the original position
		this.position = this.originalPosition = this._generatePosition( event );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;
		this.lastPositionAbs = this.positionAbs = this._convertPositionTo( "absolute" );

		this._mouseDrag( event );

		return true;

	},

	_scroll: function( event ) {
		var o = this.options,
			scrolled = false;

		if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ].tagName !== "HTML" ) {

			if ( ( this.overflowOffset.top + this.scrollParent[ 0 ].offsetHeight ) -
					event.pageY < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollTop =
					scrolled = this.scrollParent[ 0 ].scrollTop + o.scrollSpeed;
			} else if ( event.pageY - this.overflowOffset.top < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollTop =
					scrolled = this.scrollParent[ 0 ].scrollTop - o.scrollSpeed;
			}

			if ( ( this.overflowOffset.left + this.scrollParent[ 0 ].offsetWidth ) -
					event.pageX < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollLeft = scrolled =
					this.scrollParent[ 0 ].scrollLeft + o.scrollSpeed;
			} else if ( event.pageX - this.overflowOffset.left < o.scrollSensitivity ) {
				this.scrollParent[ 0 ].scrollLeft = scrolled =
					this.scrollParent[ 0 ].scrollLeft - o.scrollSpeed;
			}

		} else {

			if ( event.pageY - this.document.scrollTop() < o.scrollSensitivity ) {
				scrolled = this.document.scrollTop( this.document.scrollTop() - o.scrollSpeed );
			} else if ( this.window.height() - ( event.pageY - this.document.scrollTop() ) <
					o.scrollSensitivity ) {
				scrolled = this.document.scrollTop( this.document.scrollTop() + o.scrollSpeed );
			}

			if ( event.pageX - this.document.scrollLeft() < o.scrollSensitivity ) {
				scrolled = this.document.scrollLeft(
					this.document.scrollLeft() - o.scrollSpeed
				);
			} else if ( this.window.width() - ( event.pageX - this.document.scrollLeft() ) <
					o.scrollSensitivity ) {
				scrolled = this.document.scrollLeft(
					this.document.scrollLeft() + o.scrollSpeed
				);
			}

		}

		return scrolled;
	},

	_mouseDrag: function( event ) {
		var i, item, itemElement, intersection,
			o = this.options;

		//Compute the helpers position
		this.position = this._generatePosition( event );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Set the helper position
		if ( !this.options.axis || this.options.axis !== "y" ) {
			this.helper[ 0 ].style.left = this.position.left + "px";
		}
		if ( !this.options.axis || this.options.axis !== "x" ) {
			this.helper[ 0 ].style.top = this.position.top + "px";
		}

		//Post events to containers
		this._contactContainers( event );

		if ( this.innermostContainer !== null ) {

			//Do scrolling
			if ( o.scroll ) {
				if ( this._scroll( event ) !== false ) {

					//Update item positions used in position checks
					this._refreshItemPositions( true );

					if ( $.ui.ddmanager && !o.dropBehaviour ) {
						$.ui.ddmanager.prepareOffsets( this, event );
					}
				}
			}

			this.dragDirection = {
				vertical: this._getDragVerticalDirection(),
				horizontal: this._getDragHorizontalDirection()
			};

			//Rearrange
			for ( i = this.items.length - 1; i >= 0; i-- ) {

				//Cache variables and intersection, continue if no intersection
				item = this.items[ i ];
				itemElement = item.item[ 0 ];
				intersection = this._intersectsWithPointer( item );
				if ( !intersection ) {
					continue;
				}

				// Only put the placeholder inside the current Container, skip all
				// items from other containers. This works because when moving
				// an item from one container to another the
				// currentContainer is switched before the placeholder is moved.
				//
				// Without this, moving items in "sub-sortables" can cause
				// the placeholder to jitter between the outer and inner container.
				if ( item.instance !== this.currentContainer ) {
					continue;
				}

				// Cannot intersect with itself
				// no useless actions that have been done before
				// no action if the item moved is the parent of the item checked
				if ( itemElement !== this.currentItem[ 0 ] &&
					this.placeholder[ intersection === 1 ?
					"next" : "prev" ]()[ 0 ] !== itemElement &&
					!$.contains( this.placeholder[ 0 ], itemElement ) &&
					( this.options.type === "semi-dynamic" ?
						!$.contains( this.element[ 0 ], itemElement ) :
						true
					)
				) {

					this.direction = intersection === 1 ? "down" : "up";

					if ( this.options.tolerance === "pointer" ||
							this._intersectsWithSides( item ) ) {
						this._rearrange( event, item );
					} else {
						break;
					}

					this._trigger( "change", event, this._uiHash() );
					break;
				}
			}
		}

		//Interconnect with droppables
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		//Call callbacks
		this._trigger( "sort", event, this._uiHash() );

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function( event, noPropagation ) {

		if ( !event ) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			$.ui.ddmanager.drop( this, event );
		}

		if ( this.options.revert ) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollLeft
					);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top +
					( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
						0 :
						this.offsetParent[ 0 ].scrollTop
					);
			}
			this.reverting = true;
			$( this.helper ).animate(
				animation,
				parseInt( this.options.revert, 10 ) || 500,
				function() {
					that._clear( event );
				}
			);
		} else {
			this._clear( event, noPropagation );
		}

		return false;

	},

	cancel: function() {

		if ( this.dragging ) {

			this._mouseUp( new $.Event( "mouseup", { target: null } ) );

			if ( this.options.helper === "original" ) {
				this.currentItem.css( this._storedCSS );
				this._removeClass( this.currentItem, "ui-sortable-helper" );
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for ( var i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "deactivate", null, this._uiHash( this ) );
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", null, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		if ( this.placeholder ) {

			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
			// it unbinds ALL events from the original node!
			if ( this.placeholder[ 0 ].parentNode ) {
				this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );
			}
			if ( this.options.helper !== "original" && this.helper &&
					this.helper[ 0 ].parentNode ) {
				this.helper.remove();
			}

			$.extend( this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			} );

			if ( this.domPosition.prev ) {
				$( this.domPosition.prev ).after( this.currentItem );
			} else {
				$( this.domPosition.parent ).prepend( this.currentItem );
			}
		}

		return this;

	},

	serialize: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			str = [];
		o = o || {};

		$( items ).each( function() {
			var res = ( $( o.item || this ).attr( o.attribute || "id" ) || "" )
				.match( o.expression || ( /(.+)[\-=_](.+)/ ) );
			if ( res ) {
				str.push(
					( o.key || res[ 1 ] + "[]" ) +
					"=" + ( o.key && o.expression ? res[ 1 ] : res[ 2 ] ) );
			}
		} );

		if ( !str.length && o.key ) {
			str.push( o.key + "=" );
		}

		return str.join( "&" );

	},

	toArray: function( o ) {

		var items = this._getItemsAsjQuery( o && o.connected ),
			ret = [];

		o = o || {};

		items.each( function() {
			ret.push( $( o.item || this ).attr( o.attribute || "id" ) || "" );
		} );
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function( item ) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t &&
				( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l &&
				( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			( this.options.tolerance !== "pointer" &&
				this.helperProportions[ this.floating ? "width" : "height" ] >
				item[ this.floating ? "width" : "height" ] )
		) {
			return isOverElement;
		} else {

			return ( l < x1 + ( this.helperProportions.width / 2 ) && // Right Half
				x2 - ( this.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( this.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( this.helperProportions.height / 2 ) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function( item ) {
		var verticalDirection, horizontalDirection,
			isOverElementHeight = ( this.options.axis === "x" ) ||
				this._isOverAxis(
					this.positionAbs.top + this.offset.click.top, item.top, item.height ),
			isOverElementWidth = ( this.options.axis === "y" ) ||
				this._isOverAxis(
					this.positionAbs.left + this.offset.click.left, item.left, item.width ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( !isOverElement ) {
			return false;
		}

		verticalDirection = this.dragDirection.vertical;
		horizontalDirection = this.dragDirection.horizontal;

		return this.floating ?
			( ( horizontalDirection === "right" || verticalDirection === "down" ) ? 2 : 1 ) :
			( verticalDirection && ( verticalDirection === "down" ? 2 : 1 ) );

	},

	_intersectsWithSides: function( item ) {

		var isOverBottomHalf = this._isOverAxis( this.positionAbs.top +
				this.offset.click.top, item.top + ( item.height / 2 ), item.height ),
			isOverRightHalf = this._isOverAxis( this.positionAbs.left +
				this.offset.click.left, item.left + ( item.width / 2 ), item.width ),
			verticalDirection = this.dragDirection.vertical,
			horizontalDirection = this.dragDirection.horizontal;

		if ( this.floating && horizontalDirection ) {
			return ( ( horizontalDirection === "right" && isOverRightHalf ) ||
				( horizontalDirection === "left" && !isOverRightHalf ) );
		} else {
			return verticalDirection && ( ( verticalDirection === "down" && isOverBottomHalf ) ||
				( verticalDirection === "up" && !isOverBottomHalf ) );
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && ( delta > 0 ? "down" : "up" );
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && ( delta > 0 ? "right" : "left" );
	},

	refresh: function( event ) {
		this._refreshItems( event );
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ?
			[ options.connectWith ] :
			options.connectWith;
	},

	_getItemsAsjQuery: function( connected ) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if ( connectWith && connected ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ typeof inst.options.items === "function" ?
							inst.options.items.call( inst.element ) :
							$( inst.options.items, inst.element )
								.not( ".ui-sortable-helper" )
								.not( ".ui-sortable-placeholder" ), inst ] );
					}
				}
			}
		}

		queries.push( [ typeof this.options.items === "function" ?
			this.options.items
				.call( this.element, null, { options: this.options, item: this.currentItem } ) :
			$( this.options.items, this.element )
				.not( ".ui-sortable-helper" )
				.not( ".ui-sortable-placeholder" ), this ] );

		function addItems() {
			items.push( this );
		}
		for ( i = queries.length - 1; i >= 0; i-- ) {
			queries[ i ][ 0 ].each( addItems );
		}

		return $( items );

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find( ":data(" + this.widgetName + "-item)" );

		this.items = $.grep( this.items, function( item ) {
			for ( var j = 0; j < list.length; j++ ) {
				if ( list[ j ] === item.item[ 0 ] ) {
					return false;
				}
			}
			return true;
		} );

	},

	_refreshItems: function( event ) {

		this.items = [];
		this.containers = [ this ];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [ [ typeof this.options.items === "function" ?
				this.options.items.call( this.element[ 0 ], event, { item: this.currentItem } ) :
				$( this.options.items, this.element ), this ] ],
			connectWith = this._connectWith();

		//Shouldn't be run the first time through due to massive slow-down
		if ( connectWith && this.ready ) {
			for ( i = connectWith.length - 1; i >= 0; i-- ) {
				cur = $( connectWith[ i ], this.document[ 0 ] );
				for ( j = cur.length - 1; j >= 0; j-- ) {
					inst = $.data( cur[ j ], this.widgetFullName );
					if ( inst && inst !== this && !inst.options.disabled ) {
						queries.push( [ typeof inst.options.items === "function" ?
							inst.options.items
								.call( inst.element[ 0 ], event, { item: this.currentItem } ) :
							$( inst.options.items, inst.element ), inst ] );
						this.containers.push( inst );
					}
				}
			}
		}

		for ( i = queries.length - 1; i >= 0; i-- ) {
			targetData = queries[ i ][ 1 ];
			_queries = queries[ i ][ 0 ];

			for ( j = 0, queriesLength = _queries.length; j < queriesLength; j++ ) {
				item = $( _queries[ j ] );

				// Data for target checking (mouse manager)
				item.data( this.widgetName + "-item", targetData );

				items.push( {
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				} );
			}
		}

	},

	_refreshItemPositions: function( fast ) {
		var i, item, t, p;

		for ( i = this.items.length - 1; i >= 0; i-- ) {
			item = this.items[ i ];

			//We ignore calculating positions of all connected containers when we're not over them
			if ( this.currentContainer && item.instance !== this.currentContainer &&
					item.item[ 0 ] !== this.currentItem[ 0 ] ) {
				continue;
			}

			t = this.options.toleranceElement ?
				$( this.options.toleranceElement, item.item ) :
				item.item;

			if ( !fast ) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}
	},

	refreshPositions: function( fast ) {

		// Determine whether items are being displayed horizontally
		this.floating = this.items.length ?
			this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
			false;

		if ( this.innermostContainer !== null ) {
			this._refreshItemPositions( fast );
		}

		var i, p;

		if ( this.options.custom && this.options.custom.refreshContainers ) {
			this.options.custom.refreshContainers.call( this );
		} else {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				p = this.containers[ i ].element.offset();
				this.containers[ i ].containerCache.left = p.left;
				this.containers[ i ].containerCache.top = p.top;
				this.containers[ i ].containerCache.width =
					this.containers[ i ].element.outerWidth();
				this.containers[ i ].containerCache.height =
					this.containers[ i ].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function( that ) {
		that = that || this;
		var className, nodeName,
			o = that.options;

		if ( !o.placeholder || o.placeholder.constructor === String ) {
			className = o.placeholder;
			nodeName = that.currentItem[ 0 ].nodeName.toLowerCase();
			o.placeholder = {
				element: function() {

					var element = $( "<" + nodeName + ">", that.document[ 0 ] );

					that._addClass( element, "ui-sortable-placeholder",
							className || that.currentItem[ 0 ].className )
						._removeClass( element, "ui-sortable-helper" );

					if ( nodeName === "tbody" ) {
						that._createTrPlaceholder(
							that.currentItem.find( "tr" ).eq( 0 ),
							$( "<tr>", that.document[ 0 ] ).appendTo( element )
						);
					} else if ( nodeName === "tr" ) {
						that._createTrPlaceholder( that.currentItem, element );
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function( container, p ) {

					// 1. If a className is set as 'placeholder option, we don't force sizes -
					// the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a
					// class name is specified
					if ( className && !o.forcePlaceholderSize ) {
						return;
					}

					// If the element doesn't have a actual height or width by itself (without
					// styles coming from a stylesheet), it receives the inline height and width
					// from the dragged item. Or, if it's a tbody or tr, it's going to have a height
					// anyway since we're populating them with <td>s above, but they're unlikely to
					// be the correct height on their own if the row heights are dynamic, so we'll
					// always assign the height of the dragged item given forcePlaceholderSize
					// is true.
					if ( !p.height() || ( o.forcePlaceholderSize &&
							( nodeName === "tbody" || nodeName === "tr" ) ) ) {
						p.height(
							that.currentItem.innerHeight() -
							parseInt( that.currentItem.css( "paddingTop" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingBottom" ) || 0, 10 ) );
					}
					if ( !p.width() ) {
						p.width(
							that.currentItem.innerWidth() -
							parseInt( that.currentItem.css( "paddingLeft" ) || 0, 10 ) -
							parseInt( that.currentItem.css( "paddingRight" ) || 0, 10 ) );
					}
				}
			};
		}

		//Create the placeholder
		that.placeholder = $( o.placeholder.element.call( that.element, that.currentItem ) );

		//Append it after the actual current item
		that.currentItem.after( that.placeholder );

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update( that, that.placeholder );

	},

	_createTrPlaceholder: function( sourceTr, targetTr ) {
		var that = this;

		sourceTr.children().each( function() {
			$( "<td>&#160;</td>", that.document[ 0 ] )
				.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
				.appendTo( targetTr );
		} );
	},

	_contactContainers: function( event ) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom,
			floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// Get innermost container that intersects with item
		for ( i = this.containers.length - 1; i >= 0; i-- ) {

			// Never consider a container that's located within the item itself
			if ( $.contains( this.currentItem[ 0 ], this.containers[ i ].element[ 0 ] ) ) {
				continue;
			}

			if ( this._intersectsWith( this.containers[ i ].containerCache ) ) {

				// If we've already found a container and it's more "inner" than this, then continue
				if ( innermostContainer &&
						$.contains(
							this.containers[ i ].element[ 0 ],
							innermostContainer.element[ 0 ] ) ) {
					continue;
				}

				innermostContainer = this.containers[ i ];
				innermostIndex = i;

			} else {

				// container doesn't intersect. trigger "out" event if necessary
				if ( this.containers[ i ].containerCache.over ) {
					this.containers[ i ]._trigger( "out", event, this._uiHash( this ) );
					this.containers[ i ].containerCache.over = 0;
				}
			}

		}

		this.innermostContainer = innermostContainer;

		// If no intersecting containers found, return
		if ( !innermostContainer ) {
			return;
		}

		// Move the item into the container if it's not there already
		if ( this.containers.length === 1 ) {
			if ( !this.containers[ innermostIndex ].containerCache.over ) {
				this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
				this.containers[ innermostIndex ].containerCache.over = 1;
			}
		} else {

			// When entering a new container, we will find the item with the least distance and
			// append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating( this.currentItem );
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "pageX" : "pageY";

			for ( j = this.items.length - 1; j >= 0; j-- ) {
				if ( !$.contains(
						this.containers[ innermostIndex ].element[ 0 ], this.items[ j ].item[ 0 ] )
				) {
					continue;
				}
				if ( this.items[ j ].item[ 0 ] === this.currentItem[ 0 ] ) {
					continue;
				}

				cur = this.items[ j ].item.offset()[ posProperty ];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up" : "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if ( !itemWithLeastDistance && !this.options.dropOnEmpty ) {
				return;
			}

			if ( this.currentContainer === this.containers[ innermostIndex ] ) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			if ( itemWithLeastDistance ) {
				this._rearrange( event, itemWithLeastDistance, null, true );
			} else {
				this._rearrange( event, null, this.containers[ innermostIndex ].element, true );
			}
			this._trigger( "change", event, this._uiHash() );
			this.containers[ innermostIndex ]._trigger( "change", event, this._uiHash( this ) );
			this.currentContainer = this.containers[ innermostIndex ];

			//Update the placeholder
			this.options.placeholder.update( this.currentContainer, this.placeholder );

			//Update scrollParent
			this.scrollParent = this.placeholder.scrollParent();

			//Update overflowOffset
			if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
					this.scrollParent[ 0 ].tagName !== "HTML" ) {
				this.overflowOffset = this.scrollParent.offset();
			}

			this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
			this.containers[ innermostIndex ].containerCache.over = 1;
		}

	},

	_createHelper: function( event ) {

		var o = this.options,
			helper = typeof o.helper === "function" ?
				$( o.helper.apply( this.element[ 0 ], [ event, this.currentItem ] ) ) :
				( o.helper === "clone" ? this.currentItem.clone() : this.currentItem );

		//Add the helper to the DOM if that didn't happen already
		if ( !helper.parents( "body" ).length ) {
			this.appendTo[ 0 ].appendChild( helper[ 0 ] );
		}

		if ( helper[ 0 ] === this.currentItem[ 0 ] ) {
			this._storedCSS = {
				width: this.currentItem[ 0 ].style.width,
				height: this.currentItem[ 0 ].style.height,
				position: this.currentItem.css( "position" ),
				top: this.currentItem.css( "top" ),
				left: this.currentItem.css( "left" )
			};
		}

		if ( !helper[ 0 ].style.width || o.forceHelperSize ) {
			helper.width( this.currentItem.width() );
		}
		if ( !helper[ 0 ].style.height || o.forceHelperSize ) {
			helper.height( this.currentItem.height() );
		}

		return helper;

	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( Array.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes this
		// information with an ugly IE fix
		if ( this.offsetParent[ 0 ] === this.document[ 0 ].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" ?
					this.document.width() :
					this.window.width() - this.helperProportions.width - this.margins.left,
				( o.containment === "document" ?
					( this.document.height() || document.body.parentNode.scrollHeight ) :
					this.window.height() || this.document[ 0 ].body.parentNode.scrollHeight
				) - this.helperProportions.height - this.margins.top
			];
		}

		if ( !( /^(document|window|parent)$/ ).test( o.containment ) ) {
			ce = $( o.containment )[ 0 ];
			co = $( o.containment ).offset();
			over = ( $( ce ).css( "overflow" ) !== "hidden" );

			this.containment = [
				co.left + ( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingLeft" ), 10 ) || 0 ) - this.margins.left,
				co.top + ( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) +
					( parseInt( $( ce ).css( "paddingTop" ), 10 ) || 0 ) - this.margins.top,
				co.left + ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
					( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingRight" ), 10 ) || 0 ) -
					this.helperProportions.width - this.margins.left,
				co.top + ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
					( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) -
					( parseInt( $( ce ).css( "paddingBottom" ), 10 ) || 0 ) -
					this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
			scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 :
					scroll.scrollLeft() ) * mod )
			)
		};

	},

	_generatePosition: function( event ) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" &&
				!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
					this.offsetParent :
					this.scrollParent,
				scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if ( this.cssPosition === "relative" && !( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
				this.scrollParent[ 0 ] !== this.offsetParent[ 0 ] ) ) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if ( this.originalPosition ) { //If we are not dragging yet, we won't check for options

			if ( this.containment ) {
				if ( event.pageX - this.offset.click.left < this.containment[ 0 ] ) {
					pageX = this.containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < this.containment[ 1 ] ) {
					pageY = this.containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > this.containment[ 2 ] ) {
					pageX = this.containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > this.containment[ 3 ] ) {
					pageY = this.containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {
				top = this.originalPageY + Math.round( ( pageY - this.originalPageY ) /
					o.grid[ 1 ] ) * o.grid[ 1 ];
				pageY = this.containment ?
					( ( top - this.offset.click.top >= this.containment[ 1 ] &&
						top - this.offset.click.top <= this.containment[ 3 ] ) ?
							top :
							( ( top - this.offset.click.top >= this.containment[ 1 ] ) ?
								top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) :
								top;

				left = this.originalPageX + Math.round( ( pageX - this.originalPageX ) /
					o.grid[ 0 ] ) * o.grid[ 0 ];
				pageX = this.containment ?
					( ( left - this.offset.click.left >= this.containment[ 0 ] &&
						left - this.offset.click.left <= this.containment[ 2 ] ) ?
							left :
							( ( left - this.offset.click.left >= this.containment[ 0 ] ) ?
								left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) :
								left;
			}

		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollTop() :
					( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( ( this.cssPosition === "fixed" ?
					-this.scrollParent.scrollLeft() :
					scrollIsRootNode ? 0 : scroll.scrollLeft() ) )
			)
		};

	},

	_rearrange: function( event, i, a, hardRefresh ) {

		if ( a ) {
			a[ 0 ].appendChild( this.placeholder[ 0 ] );
		} else {
			i.item[ 0 ].parentNode.insertBefore( this.placeholder[ 0 ],
				( this.direction === "down" ? i.item[ 0 ] : i.item[ 0 ].nextSibling ) );
		}

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout,
		// if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay( function() {
			if ( counter === this.counter ) {

				//Precompute after each DOM insertion, NOT on mousemove
				this.refreshPositions( !hardRefresh );
			}
		} );

	},

	_clear: function( event, noPropagation ) {

		this.reverting = false;

		// We delay all events that have to be triggered to after the point where the placeholder
		// has been removed and everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets
		// reappended (see #4088)
		if ( !this._noFinalSort && this.currentItem.parent().length ) {
			this.placeholder.before( this.currentItem );
		}
		this._noFinalSort = null;

		if ( this.helper[ 0 ] === this.currentItem[ 0 ] ) {
			for ( i in this._storedCSS ) {
				if ( this._storedCSS[ i ] === "auto" || this._storedCSS[ i ] === "static" ) {
					this._storedCSS[ i ] = "";
				}
			}
			this.currentItem.css( this._storedCSS );
			this._removeClass( this.currentItem, "ui-sortable-helper" );
		} else {
			this.currentItem.show();
		}

		if ( this.fromOutside && !noPropagation ) {
			delayedTriggers.push( function( event ) {
				this._trigger( "receive", event, this._uiHash( this.fromOutside ) );
			} );
		}
		if ( ( this.fromOutside ||
				this.domPosition.prev !==
				this.currentItem.prev().not( ".ui-sortable-helper" )[ 0 ] ||
				this.domPosition.parent !== this.currentItem.parent()[ 0 ] ) && !noPropagation ) {

			// Trigger update callback if the DOM position has changed
			delayedTriggers.push( function( event ) {
				this._trigger( "update", event, this._uiHash() );
			} );
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if ( this !== this.currentContainer ) {
			if ( !noPropagation ) {
				delayedTriggers.push( function( event ) {
					this._trigger( "remove", event, this._uiHash() );
				} );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "receive", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
				delayedTriggers.push( ( function( c ) {
					return function( event ) {
						c._trigger( "update", event, this._uiHash( this ) );
					};
				} ).call( this, this.currentContainer ) );
			}
		}

		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for ( i = this.containers.length - 1; i >= 0; i-- ) {
			if ( !noPropagation ) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if ( this.containers[ i ].containerCache.over ) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[ i ].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.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 ( !noPropagation ) {
			this._trigger( "beforeStop", event, this._uiHash() );
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
		// it unbinds ALL events from the original node!
		this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if ( !noPropagation ) {
			for ( i = 0; i < delayedTriggers.length; i++ ) {

				// Trigger all delayed events
				delayedTriggers[ i ].call( this, event );
			}
			this._trigger( "stop", event, this._uiHash() );
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ( $.Widget.prototype._trigger.apply( this, arguments ) === false ) {
			this.cancel();
		}
	},

	_uiHash: function( _inst ) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $( [] ),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

} );

} );






/*!
 * jQuery UI Spinner 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Spinner
//>>group: Widgets
//>>description: Displays buttons to easily input numbers via the keyboard or mouse.
//>>docs: http://api.jqueryui.com/spinner/
//>>demos: http://jqueryui.com/spinner/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/spinner.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./button",
			"../version",
			"../keycode",
			"../safe-active-element",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

function spinnerModifier( fn ) {
	return function() {
		var previous = this.element.val();
		fn.apply( this, arguments );
		this._refresh();
		if ( previous !== this.element.val() ) {
			this._trigger( "change" );
		}
	};
}

$.widget( "ui.spinner", {
	version: "1.13.0",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		classes: {
			"ui-spinner": "ui-corner-all",
			"ui-spinner-down": "ui-corner-br",
			"ui-spinner-up": "ui-corner-tr"
		},
		culture: null,
		icons: {
			down: "ui-icon-triangle-1-s",
			up: "ui-icon-triangle-1-n"
		},
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: 1,

		change: null,
		spin: null,
		start: null,
		stop: null
	},

	_create: function() {

		// handle string values that need to be parsed
		this._setOption( "max", this.options.max );
		this._setOption( "min", this.options.min );
		this._setOption( "step", this.options.step );

		// Only format if there is a value, prevents the field from being marked
		// as invalid in Firefox, see #9573.
		if ( this.value() !== "" ) {

			// Format the value, but don't constrain.
			this._value( this.element.val(), true );
		}

		this._draw();
		this._on( this._events );
		this._refresh();

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_getCreateOptions: function() {
		var options = this._super();
		var element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value != null && value.length ) {
				options[ option ] = value;
			}
		} );

		return options;
	},

	_events: {
		keydown: function( event ) {
			if ( this._start( event ) && this._keydown( event ) ) {
				event.preventDefault();
			}
		},
		keyup: "_stop",
		focus: function() {
			this.previous = this.element.val();
		},
		blur: function( event ) {
			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 ) {
			var activeElement = $.ui.safeActiveElement( this.document[ 0 ] );
			var isActive = this.element[ 0 ] === activeElement;

			if ( !isActive || !delta ) {
				return;
			}

			if ( !this.spinning && !this._start( event ) ) {
				return false;
			}

			this._spin( ( delta > 0 ? 1 : -1 ) * this.options.step, event );
			clearTimeout( this.mousewheelTimer );
			this.mousewheelTimer = this._delay( function() {
				if ( this.spinning ) {
					this._stop( event );
				}
			}, 100 );
			event.preventDefault();
		},
		"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 ] === $.ui.safeActiveElement( this.document[ 0 ] ) ?
				this.previous : this.element.val();
			function checkFocus() {
				var isActive = this.element[ 0 ] === $.ui.safeActiveElement( this.document[ 0 ] );
				if ( !isActive ) {
					this.element.trigger( "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"
	},

	// Support mobile enhanced option and make backcompat more sane
	_enhance: function() {
		this.uiSpinner = this.element
			.attr( "autocomplete", "off" )
			.wrap( "<span>" )
			.parent()

				// Add buttons
				.append(
					"<a></a><a></a>"
				);
	},

	_draw: function() {
		this._enhance();

		this._addClass( this.uiSpinner, "ui-spinner", "ui-widget ui-widget-content" );
		this._addClass( "ui-spinner-input" );

		this.element.attr( "role", "spinbutton" );

		// Button bindings
		this.buttons = this.uiSpinner.children( "a" )
			.attr( "tabIndex", -1 )
			.attr( "aria-hidden", true )
			.button( {
				classes: {
					"ui-button": ""
				}
			} );

		// TODO: Right now button does not support classes this is already updated in button PR
		this._removeClass( this.buttons, "ui-corner-all" );

		this._addClass( this.buttons.first(), "ui-spinner-button ui-spinner-up" );
		this._addClass( this.buttons.last(), "ui-spinner-button ui-spinner-down" );
		this.buttons.first().button( {
			"icon": this.options.icons.up,
			"showLabel": false
		} );
		this.buttons.last().button( {
			"icon": this.options.icons.down,
			"showLabel": false
		} );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( this.uiSpinner.height() * 0.5 ) &&
				this.uiSpinner.height() > 0 ) {
			this.uiSpinner.height( this.uiSpinner.height() );
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return true;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return true;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return true;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return true;
		}

		return false;
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = this._delay( function() {
			this._repeat( 40, steps, event );
		}, i );

		this._spin( steps * this.options.step, event );
	},

	_spin: function( step, event ) {
		var value = this.value() || 0;

		if ( !this.counter ) {
			this.counter = 1;
		}

		value = this._adjustValue( value + step * this._increment( this.counter ) );

		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false ) {
			this._value( value );
			this.counter++;
		}
	},

	_increment: function( i ) {
		var incremental = this.options.incremental;

		if ( incremental ) {
			return typeof incremental === "function" ?
				incremental( i ) :
				Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
		}

		return 1;
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_adjustValue: function( value ) {
		var base, aboveMin,
			options = this.options;

		// Make sure we're at a valid step
		// - find out where we are relative to the base (min or 0)
		base = options.min !== null ? options.min : 0;
		aboveMin = value - base;

		// - round to the nearest step
		aboveMin = Math.round( aboveMin / options.step ) * options.step;

		// - rounding is based on 0, so adjust back to our base
		value = base + aboveMin;

		// Fix precision from bad JS floating point math
		value = parseFloat( value.toFixed( this._precision() ) );

		// Clamp the value
		if ( options.max !== null && value > options.max ) {
			return options.max;
		}
		if ( options.min !== null && value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		if ( !this.spinning ) {
			return;
		}

		clearTimeout( this.timer );
		clearTimeout( this.mousewheelTimer );
		this.counter = 0;
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_setOption: function( key, value ) {
		var prevValue, first, last;

		if ( key === "culture" || key === "numberFormat" ) {
			prevValue = this._parse( this.element.val() );
			this.options[ key ] = value;
			this.element.val( this._format( prevValue ) );
			return;
		}

		if ( key === "max" || key === "min" || key === "step" ) {
			if ( typeof value === "string" ) {
				value = this._parse( value );
			}
		}
		if ( key === "icons" ) {
			first = this.buttons.first().find( ".ui-icon" );
			this._removeClass( first, null, this.options.icons.up );
			this._addClass( first, null, value.up );
			last = this.buttons.last().find( ".ui-icon" );
			this._removeClass( last, null, this.options.icons.down );
			this._addClass( last, null, value.down );
		}

		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( this.uiSpinner, null, "ui-state-disabled", !!value );
		this.element.prop( "disabled", !!value );
		this.buttons.button( value ? "disable" : "enable" );
	},

	_setOptions: spinnerModifier( function( options ) {
		this._super( options );
	} ),

	_parse: function( val ) {
		if ( typeof val === "string" && val !== "" ) {
			val = window.Globalize && this.options.numberFormat ?
				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
		}
		return val === "" || isNaN( val ) ? null : val;
	},

	_format: function( value ) {
		if ( value === "" ) {
			return "";
		}
		return window.Globalize && this.options.numberFormat ?
			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
			value;
	},

	_refresh: function() {
		this.element.attr( {
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,

			// TODO: what should we do with values that can't be parsed?
			"aria-valuenow": this._parse( this.element.val() )
		} );
	},

	isValid: function() {
		var value = this.value();

		// Null is invalid
		if ( value === null ) {
			return false;
		}

		// If value gets adjusted, it's invalid
		return value === this._adjustValue( value );
	},

	// Update the value without triggering change
	_value: function( value, allowAny ) {
		var parsed;
		if ( value !== "" ) {
			parsed = this._parse( value );
			if ( parsed !== null ) {
				if ( !allowAny ) {
					parsed = this._adjustValue( parsed );
				}
				value = this._format( parsed );
			}
		}
		this.element.val( value );
		this._refresh();
	},

	_destroy: function() {
		this.element
			.prop( "disabled", false )
			.removeAttr( "autocomplete role aria-valuemin aria-valuemax aria-valuenow" );

		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: spinnerModifier( function( steps ) {
		this._stepUp( steps );
	} ),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( ( steps || 1 ) * this.options.step );
			this._stop();
		}
	},

	stepDown: spinnerModifier( function( steps ) {
		this._stepDown( steps );
	} ),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( ( steps || 1 ) * -this.options.step );
			this._stop();
		}
	},

	pageUp: spinnerModifier( function( pages ) {
		this._stepUp( ( pages || 1 ) * this.options.page );
	} ),

	pageDown: spinnerModifier( function( pages ) {
		this._stepDown( ( pages || 1 ) * this.options.page );
	} ),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		spinnerModifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for spinner html extension points
	$.widget( "ui.spinner", $.ui.spinner, {
		_enhance: function() {
			this.uiSpinner = this.element
				.attr( "autocomplete", "off" )
				.wrap( this._uiSpinnerHtml() )
				.parent()

					// Add buttons
					.append( this._buttonHtml() );
		},
		_uiSpinnerHtml: function() {
			return "<span>";
		},

		_buttonHtml: function() {
			return "<a></a><a></a>";
		}
	} );
}

return $.ui.spinner;

} );






/*!
 * jQuery UI Tabs 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Tabs
//>>group: Widgets
//>>description: Transforms a set of container elements into a tab structure.
//>>docs: http://api.jqueryui.com/tabs/
//>>demos: http://jqueryui.com/tabs/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tabs.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../keycode",
			"../safe-active-element",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.tabs", {
	version: "1.13.0",
	delay: 300,
	options: {
		active: null,
		classes: {
			"ui-tabs": "ui-corner-all",
			"ui-tabs-nav": "ui-corner-all",
			"ui-tabs-panel": "ui-corner-bottom",
			"ui-tabs-tab": "ui-corner-top"
		},
		collapsible: false,
		event: "click",
		heightStyle: "content",
		hide: null,
		show: null,

		// Callbacks
		activate: null,
		beforeActivate: null,
		beforeLoad: null,
		load: null
	},

	_isLocal: ( function() {
		var rhash = /#.*$/;

		return function( anchor ) {
			var anchorUrl, locationUrl;

			anchorUrl = anchor.href.replace( rhash, "" );
			locationUrl = location.href.replace( rhash, "" );

			// Decoding may throw an error if the URL isn't UTF-8 (#9518)
			try {
				anchorUrl = decodeURIComponent( anchorUrl );
			} catch ( error ) {}
			try {
				locationUrl = decodeURIComponent( locationUrl );
			} catch ( error ) {}

			return anchor.hash.length > 1 && anchorUrl === locationUrl;
		};
	} )(),

	_create: function() {
		var that = this,
			options = this.options;

		this.running = false;

		this._addClass( "ui-tabs", "ui-widget ui-widget-content" );
		this._toggleClass( "ui-tabs-collapsible", null, options.collapsible );

		this._processTabs();
		options.active = this._initialActive();

		// Take disabling tabs via class attribute from HTML
		// into account and update option properly.
		if ( Array.isArray( options.disabled ) ) {
			options.disabled = $.uniqueSort( options.disabled.concat(
				$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
					return that.tabs.index( li );
				} )
			) ).sort();
		}

		// Check for length avoids error when initializing empty list
		if ( this.options.active !== false && this.anchors.length ) {
			this.active = this._findActive( options.active );
		} else {
			this.active = $();
		}

		this._refresh();

		if ( this.active.length ) {
			this.load( options.active );
		}
	},

	_initialActive: function() {
		var active = this.options.active,
			collapsible = this.options.collapsible,
			locationHash = location.hash.substring( 1 );

		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 ) {
		var focusedTab = $( $.ui.safeActiveElement( this.document[ 0 ] ) ).closest( "li" ),
			selectedIndex = this.tabs.index( focusedTab ),
			goingForward = true;

		if ( this._handlePageNav( event ) ) {
			return;
		}

		switch ( event.keyCode ) {
		case $.ui.keyCode.RIGHT:
		case $.ui.keyCode.DOWN:
			selectedIndex++;
			break;
		case $.ui.keyCode.UP:
		case $.ui.keyCode.LEFT:
			goingForward = false;
			selectedIndex--;
			break;
		case $.ui.keyCode.END:
			selectedIndex = this.anchors.length - 1;
			break;
		case $.ui.keyCode.HOME:
			selectedIndex = 0;
			break;
		case $.ui.keyCode.SPACE:

			// Activate only, no collapsing
			event.preventDefault();
			clearTimeout( this.activating );
			this._activate( selectedIndex );
			return;
		case $.ui.keyCode.ENTER:

			// Toggle (cancel delayed activation, allow collapsing)
			event.preventDefault();
			clearTimeout( this.activating );

			// Determine if we should collapse or activate
			this._activate( selectedIndex === this.options.active ? false : selectedIndex );
			return;
		default:
			return;
		}

		// Focus the appropriate tab, based on which key was pressed
		event.preventDefault();
		clearTimeout( this.activating );
		selectedIndex = this._focusNextTab( selectedIndex, goingForward );

		// Navigating with control/command key will prevent automatic activation
		if ( !event.ctrlKey && !event.metaKey ) {

			// Update aria-selected immediately so that AT think the tab is already selected.
			// Otherwise AT may confuse the user by stating that they need to activate the tab,
			// but the tab will already be activated by the time the announcement finishes.
			focusedTab.attr( "aria-selected", "false" );
			this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );

			this.activating = this._delay( function() {
				this.option( "active", selectedIndex );
			}, this.delay );
		}
	},

	_panelKeydown: function( event ) {
		if ( this._handlePageNav( event ) ) {
			return;
		}

		// Ctrl+up moves focus to the current tab
		if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
			event.preventDefault();
			this.active.trigger( "focus" );
		}
	},

	// Alt+page up/down moves focus to the previous/next tab (and activates)
	_handlePageNav: function( event ) {
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
			this._activate( this._focusNextTab( this.options.active - 1, false ) );
			return true;
		}
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
			this._activate( this._focusNextTab( this.options.active + 1, true ) );
			return true;
		}
	},

	_findNextTab: function( index, goingForward ) {
		var lastTabIndex = this.tabs.length - 1;

		function constrain() {
			if ( index > lastTabIndex ) {
				index = 0;
			}
			if ( index < 0 ) {
				index = lastTabIndex;
			}
			return index;
		}

		while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
			index = goingForward ? index + 1 : index - 1;
		}

		return index;
	},

	_focusNextTab: function( index, goingForward ) {
		index = this._findNextTab( index, goingForward );
		this.tabs.eq( index ).trigger( "focus" );
		return index;
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {

			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		this._super( key, value );

		if ( key === "collapsible" ) {
			this._toggleClass( "ui-tabs-collapsible", null, value );

			// Setting collapsible: false while collapsed; open first panel
			if ( !value && this.options.active === false ) {
				this._activate( 0 );
			}
		}

		if ( key === "event" ) {
			this._setupEvents( value );
		}

		if ( key === "heightStyle" ) {
			this._setupHeightStyle( value );
		}
	},

	_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._setOptionDisabled( this.options.disabled );
		this._setupEvents( this.options.event );
		this._setupHeightStyle( this.options.heightStyle );

		this.tabs.not( this.active ).attr( {
			"aria-selected": "false",
			"aria-expanded": "false",
			tabIndex: -1
		} );
		this.panels.not( this._getPanelForTab( this.active ) )
			.hide()
			.attr( {
				"aria-hidden": "true"
			} );

		// Make sure one tab is in the tab order
		if ( !this.active.length ) {
			this.tabs.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active
				.attr( {
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				} );
			this._addClass( this.active, "ui-tabs-active", "ui-state-active" );
			this._getPanelForTab( this.active )
				.show()
				.attr( {
					"aria-hidden": "false"
				} );
		}
	},

	_processTabs: function() {
		var that = this,
			prevTabs = this.tabs,
			prevAnchors = this.anchors,
			prevPanels = this.panels;

		this.tablist = this._getList().attr( "role", "tablist" );
		this._addClass( this.tablist, "ui-tabs-nav",
			"ui-helper-reset ui-helper-clearfix ui-widget-header" );

		// Prevent users from focusing disabled tabs via click
		this.tablist
			.on( "mousedown" + this.eventNamespace, "> li", function( event ) {
				if ( $( this ).is( ".ui-state-disabled" ) ) {
					event.preventDefault();
				}
			} )

			// 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.
			.on( "focus" + this.eventNamespace, ".ui-tabs-anchor", function() {
				if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
					this.blur();
				}
			} );

		this.tabs = this.tablist.find( "> li:has(a[href])" )
			.attr( {
				role: "tab",
				tabIndex: -1
			} );
		this._addClass( this.tabs, "ui-tabs-tab", "ui-state-default" );

		this.anchors = this.tabs.map( function() {
			return $( "a", this )[ 0 ];
		} )
			.attr( {
				tabIndex: -1
			} );
		this._addClass( this.anchors, "ui-tabs-anchor" );

		this.panels = $();

		this.anchors.each( function( i, anchor ) {
			var selector, panel, panelId,
				anchorId = $( anchor ).uniqueId().attr( "id" ),
				tab = $( anchor ).closest( "li" ),
				originalAriaControls = tab.attr( "aria-controls" );

			// Inline tab
			if ( that._isLocal( anchor ) ) {
				selector = anchor.hash;
				panelId = selector.substring( 1 );
				panel = that.element.find( that._sanitizeSelector( selector ) );

			// remote tab
			} else {

				// If the tab doesn't already have aria-controls,
				// generate an id by using a throw-away element
				panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id;
				selector = "#" + panelId;
				panel = that.element.find( selector );
				if ( !panel.length ) {
					panel = that._createPanel( panelId );
					panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
				}
				panel.attr( "aria-live", "polite" );
			}

			if ( panel.length ) {
				that.panels = that.panels.add( panel );
			}
			if ( originalAriaControls ) {
				tab.data( "ui-tabs-aria-controls", originalAriaControls );
			}
			tab.attr( {
				"aria-controls": panelId,
				"aria-labelledby": anchorId
			} );
			panel.attr( "aria-labelledby", anchorId );
		} );

		this.panels.attr( "role", "tabpanel" );
		this._addClass( this.panels, "ui-tabs-panel", "ui-widget-content" );

		// Avoid memory leaks (#10056)
		if ( prevTabs ) {
			this._off( prevTabs.not( this.tabs ) );
			this._off( prevAnchors.not( this.anchors ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	// Allow overriding how to find the list for rare usage scenarios (#7715)
	_getList: function() {
		return this.tablist || this.element.find( "ol, ul" ).eq( 0 );
	},

	_createPanel: function( id ) {
		return $( "<div>" )
			.attr( "id", id )
			.data( "ui-tabs-destroy", true );
	},

	_setOptionDisabled: function( disabled ) {
		var currentItem, li, i;

		if ( Array.isArray( disabled ) ) {
			if ( !disabled.length ) {
				disabled = false;
			} else if ( disabled.length === this.anchors.length ) {
				disabled = true;
			}
		}

		// Disable tabs
		for ( i = 0; ( li = this.tabs[ i ] ); i++ ) {
			currentItem = $( li );
			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
				currentItem.attr( "aria-disabled", "true" );
				this._addClass( currentItem, null, "ui-state-disabled" );
			} else {
				currentItem.removeAttr( "aria-disabled" );
				this._removeClass( currentItem, null, "ui-state-disabled" );
			}
		}

		this.options.disabled = disabled;

		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null,
			disabled === true );
	},

	_setupEvents: function( event ) {
		var events = {};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			} );
		}

		this._off( this.anchors.add( this.tabs ).add( this.panels ) );

		// Always prevent the default action, even when disabled
		this._on( true, this.anchors, {
			click: function( event ) {
				event.preventDefault();
			}
		} );
		this._on( this.anchors, events );
		this._on( this.tabs, { keydown: "_tabKeydown" } );
		this._on( this.panels, { keydown: "_panelKeydown" } );

		this._focusable( this.tabs );
		this._hoverable( this.tabs );
	},

	_setupHeightStyle: function( heightStyle ) {
		var maxHeight,
			parent = this.element.parent();

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			maxHeight -= this.element.outerHeight() - this.element.height();

			this.element.siblings( ":visible" ).each( function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			} );

			this.element.children().not( this.panels ).each( function() {
				maxHeight -= $( this ).outerHeight( true );
			} );

			this.panels.each( function() {
				$( this ).height( Math.max( 0, maxHeight -
					$( this ).innerHeight() + $( this ).height() ) );
			} )
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.panels.each( function() {
				maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
			} ).height( maxHeight );
		}
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			anchor = $( event.currentTarget ),
			tab = anchor.closest( "li" ),
			clickedIsActive = tab[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : this._getPanelForTab( tab ),
			toHide = !active.length ? $() : this._getPanelForTab( active ),
			eventData = {
				oldTab: active,
				oldPanel: toHide,
				newTab: collapsing ? $() : tab,
				newPanel: toShow
			};

		event.preventDefault();

		if ( tab.hasClass( "ui-state-disabled" ) ||

				// tab is already loading
				tab.hasClass( "ui-tabs-loading" ) ||

				// can't switch durning an animation
				this.running ||

				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||

				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.tabs.index( tab );

		this.active = clickedIsActive ? $() : tab;
		if ( this.xhr ) {
			this.xhr.abort();
		}

		if ( !toHide.length && !toShow.length ) {
			$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
		}

		if ( toShow.length ) {
			this.load( this.tabs.index( tab ), event );
		}
		this._toggle( event, eventData );
	},

	// Handles show/hide for selecting tabs
	_toggle: function( event, eventData ) {
		var that = this,
			toShow = eventData.newPanel,
			toHide = eventData.oldPanel;

		this.running = true;

		function complete() {
			that.running = false;
			that._trigger( "activate", event, eventData );
		}

		function show() {
			that._addClass( eventData.newTab.closest( "li" ), "ui-tabs-active", "ui-state-active" );

			if ( toShow.length && that.options.show ) {
				that._show( toShow, that.options.show, complete );
			} else {
				toShow.show();
				complete();
			}
		}

		// Start out by hiding, then showing, then completing
		if ( toHide.length && this.options.hide ) {
			this._hide( toHide, this.options.hide, function() {
				that._removeClass( eventData.oldTab.closest( "li" ),
					"ui-tabs-active", "ui-state-active" );
				show();
			} );
		} else {
			this._removeClass( eventData.oldTab.closest( "li" ),
				"ui-tabs-active", "ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr( "aria-hidden", "true" );
		eventData.oldTab.attr( {
			"aria-selected": "false",
			"aria-expanded": "false"
		} );

		// If we're switching tabs, remove the old tab from the tab order.
		// If we're opening from collapsed state, remove the previous tab from the tab order.
		// If we're collapsing, then keep the collapsing tab in the tab order.
		if ( toShow.length && toHide.length ) {
			eventData.oldTab.attr( "tabIndex", -1 );
		} else if ( toShow.length ) {
			this.tabs.filter( function() {
				return $( this ).attr( "tabIndex" ) === 0;
			} )
				.attr( "tabIndex", -1 );
		}

		toShow.attr( "aria-hidden", "false" );
		eventData.newTab.attr( {
			"aria-selected": "true",
			"aria-expanded": "true",
			tabIndex: 0
		} );
	},

	_activate: function( index ) {
		var anchor,
			active = this._findActive( index );

		// Trying to activate the already active panel
		if ( active[ 0 ] === this.active[ 0 ] ) {
			return;
		}

		// Trying to collapse, simulate a click on the current active header
		if ( !active.length ) {
			active = this.active;
		}

		anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
		this._eventHandler( {
			target: anchor,
			currentTarget: anchor,
			preventDefault: $.noop
		} );
	},

	_findActive: function( index ) {
		return index === false ? $() : this.tabs.eq( index );
	},

	_getIndex: function( index ) {

		// meta-function to give users option to provide a href string instead of a numerical index.
		if ( typeof index === "string" ) {
			index = this.anchors.index( this.anchors.filter( "[href$='" +
				$.escapeSelector( index ) + "']" ) );
		}

		return index;
	},

	_destroy: function() {
		if ( this.xhr ) {
			this.xhr.abort();
		}

		this.tablist
			.removeAttr( "role" )
			.off( this.eventNamespace );

		this.anchors
			.removeAttr( "role tabIndex" )
			.removeUniqueId();

		this.tabs.add( this.panels ).each( function() {
			if ( $.data( this, "ui-tabs-destroy" ) ) {
				$( this ).remove();
			} else {
				$( this ).removeAttr( "role tabIndex " +
					"aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded" );
			}
		} );

		this.tabs.each( function() {
			var li = $( this ),
				prev = li.data( "ui-tabs-aria-controls" );
			if ( prev ) {
				li
					.attr( "aria-controls", prev )
					.removeData( "ui-tabs-aria-controls" );
			} else {
				li.removeAttr( "aria-controls" );
			}
		} );

		this.panels.show();

		if ( this.options.heightStyle !== "content" ) {
			this.panels.css( "height", "" );
		}
	},

	enable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === false ) {
			return;
		}

		if ( index === undefined ) {
			disabled = false;
		} else {
			index = this._getIndex( index );
			if ( Array.isArray( disabled ) ) {
				disabled = $.map( disabled, function( num ) {
					return num !== index ? num : null;
				} );
			} else {
				disabled = $.map( this.tabs, function( li, num ) {
					return num !== index ? num : null;
				} );
			}
		}
		this._setOptionDisabled( disabled );
	},

	disable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === true ) {
			return;
		}

		if ( index === undefined ) {
			disabled = true;
		} else {
			index = this._getIndex( index );
			if ( $.inArray( index, disabled ) !== -1 ) {
				return;
			}
			if ( Array.isArray( disabled ) ) {
				disabled = $.merge( [ index ], disabled ).sort();
			} else {
				disabled = [ index ];
			}
		}
		this._setOptionDisabled( disabled );
	},

	load: function( index, event ) {
		index = this._getIndex( index );
		var that = this,
			tab = this.tabs.eq( index ),
			anchor = tab.find( ".ui-tabs-anchor" ),
			panel = this._getPanelForTab( tab ),
			eventData = {
				tab: tab,
				panel: panel
			},
			complete = function( jqXHR, status ) {
				if ( status === "abort" ) {
					that.panels.stop( false, true );
				}

				that._removeClass( tab, "ui-tabs-loading" );
				panel.removeAttr( "aria-busy" );

				if ( jqXHR === that.xhr ) {
					delete that.xhr;
				}
			};

		// Not remote
		if ( this._isLocal( anchor[ 0 ] ) ) {
			return;
		}

		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );

		// 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" ) {
			this._addClass( tab, "ui-tabs-loading" );
			panel.attr( "aria-busy", "true" );

			this.xhr
				.done( function( response, status, jqXHR ) {

					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout( function() {
						panel.html( response );
						that._trigger( "load", event, eventData );

						complete( jqXHR, status );
					}, 1 );
				} )
				.fail( function( jqXHR, status ) {

					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout( function() {
						complete( jqXHR, status );
					}, 1 );
				} );
		}
	},

	_ajaxSettings: function( anchor, event, eventData ) {
		var that = this;
		return {

			// Support: IE <11 only
			// Strip any hash that exists to prevent errors with the Ajax request
			url: anchor.attr( "href" ).replace( /#.*$/, "" ),
			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 ) );
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for ui-tab class (now ui-tabs-tab)
	$.widget( "ui.tabs", $.ui.tabs, {
		_processTabs: function() {
			this._superApply( arguments );
			this._addClass( this.tabs, "ui-tab" );
		}
	} );
}

return $.ui.tabs;

} );






/*!
 * jQuery UI Tooltip 1.13.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Tooltip
//>>group: Widgets
//>>description: Shows additional information for any element on hover or focus.
//>>docs: http://api.jqueryui.com/tooltip/
//>>demos: http://jqueryui.com/tooltip/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tooltip.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../keycode",
			"../position",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.tooltip", {
	version: "1.13.0",
	options: {
		classes: {
			"ui-tooltip": "ui-corner-all ui-widget-shadow"
		},
		content: function() {
			var title = $( this ).attr( "title" );

			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,

		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		track: false,

		// Callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", String.prototype.trim.call( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = String.prototype.trim.call( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on( {
			mouseover: "open",
			focusin: "open"
		} );

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr( {
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			} )
			.appendTo( this.document[ 0 ].body );
		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		this.disabledTitles = $( [] );
	},

	_setOption: function( key, value ) {
		var that = this;

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			} );
		}
	},

	_setOptionDisabled: function( value ) {
		this[ value ? "_disable" : "_enable" ]();
	},

	_disable: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		} );

		// Remove title attributes to prevent native tooltips
		this.disabledTitles = this.disabledTitles.add(
			this.element.find( this.options.items ).addBack()
				.filter( function() {
					var element = $( this );
					if ( element.is( "[title]" ) ) {
						return element
							.data( "ui-tooltip-title", element.attr( "title" ) )
							.removeAttr( "title" );
					}
				} )
		);
	},

	_enable: function() {

		// restore title attributes
		this.disabledTitles.each( function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		} );
		this.disabledTitles = $( [] );
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )

				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// Kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each( function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			} );
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" || contentOption.nodeType ||
				contentOption.jquery ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[ 0 ], function( response ) {

			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay( function() {

				// Ignore async response if tooltip was closed already
				if ( !target.data( "ui-tooltip-open" ) ) {
					return;
				}

				// JQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			} );
		} );
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// If we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		a11yContent = $( "<div>" ).html( tooltip.find( ".ui-tooltip-content" ).html() );
		a11yContent.removeAttr( "name" ).find( "[name]" ).removeAttr( "name" );
		a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		a11yContent.appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			} );

			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend( {
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );

		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		// Adds the check to add the timers only when both delay and track options are set (#14682)
		if ( this.options.track && this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval( function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, 13 );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event( event );
					fakeEvent.currentTarget = target[ 0 ];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				this._removeTooltip( this._find( target ).tooltip );
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// Disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// Only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		} );

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			} );
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" ).attr( "role", "tooltip" ),
			content = $( "<div>" ).appendTo( tooltip ),
			id = tooltip.uniqueId().attr( "id" );

		this._addClass( content, "ui-tooltip-content" );
		this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );

		tooltip.appendTo( this._appendTo( element ) );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_appendTo: function( target ) {
		var element = target.closest( ".ui-front, dialog" );

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_destroy: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {

			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {

				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		} );
		this.liveRegion.remove();
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for tooltipClass option
	$.widget( "ui.tooltip", $.ui.tooltip, {
		options: {
			tooltipClass: null
		},
		_tooltip: function() {
			var tooltipData = this._superApply( arguments );
			if ( this.options.tooltipClass ) {
				tooltipData.tooltip.addClass( this.options.tooltipClass );
			}
			return tooltipData;
		}
	} );
}

return $.ui.tooltip;

} );

























































(function($, undefined) {

/**
 * Unobtrusive scripting adapter for jQuery
 * https://github.com/rails/jquery-ujs
 *
 * Requires jQuery 1.8.0 or later.
 *
 * Released under the MIT license
 *
 */

  // Cut down on the number of issues from people inadvertently including jquery_ujs twice
  // by detecting and raising an error when it happens.
  'use strict';

  if ( $.rails !== undefined ) {
    $.error('jquery-ujs has already been loaded!');
  }

  // Shorthand to make it a little easier to call public rails functions from within rails.js
  var rails;
  var $document = $(document);

  $.rails = rails = {
    // Link elements bound by jquery-ujs
    linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',

    // Button elements bound by jquery-ujs
    buttonClickSelector: 'button[data-remote]:not([form]):not(form button), button[data-confirm]:not([form]):not(form button)',

    // Select elements bound by jquery-ujs
    inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',

    // Form elements bound by jquery-ujs
    formSubmitSelector: 'form',

    // Form input elements bound by jquery-ujs
    formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',

    // Form input elements disabled during form submission
    disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',

    // Form input elements re-enabled after form submission
    enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',

    // Form required input elements
    requiredInputSelector: 'input[name][required]:not([disabled]), textarea[name][required]:not([disabled])',

    // Form file input elements
    fileInputSelector: 'input[name][type=file]:not([disabled])',

    // Link onClick disable selector with possible reenable after remote submission
    linkDisableSelector: 'a[data-disable-with], a[data-disable]',

    // Button onClick disable selector with possible reenable after remote submission
    buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',

    // Up-to-date Cross-Site Request Forgery token
    csrfToken: function() {
     return $('meta[name=csrf-token]').attr('content');
    },

    // URL param that must contain the CSRF token
    csrfParam: function() {
     return $('meta[name=csrf-param]').attr('content');
    },

    // Make sure that every Ajax request sends the CSRF token
    CSRFProtection: function(xhr) {
      var token = rails.csrfToken();
      if (token) xhr.setRequestHeader('X-CSRF-Token', token);
    },

    // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
    refreshCSRFTokens: function(){
      $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken());
    },

    // Triggers an event on an element and returns false if the event result is false
    fire: function(obj, name, data) {
      var event = $.Event(name);
      obj.trigger(event, data);
      return event.result !== false;
    },

    // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
    confirm: function(message) {
      return confirm(message);
    },

    // Default ajax function, may be overridden with custom function in $.rails.ajax
    ajax: function(options) {
      return $.ajax(options);
    },

    // Default way to get an element's href. May be overridden at $.rails.href.
    href: function(element) {
      return element[0].href;
    },

    // Checks "data-remote" if true to handle the request through a XHR request.
    isRemote: function(element) {
      return element.data('remote') !== undefined && element.data('remote') !== false;
    },

    // Submits "remote" forms and links with ajax
    handleRemote: function(element) {
      var method, url, data, withCredentials, dataType, options;

      if (rails.fire(element, 'ajax:before')) {
        withCredentials = element.data('with-credentials') || null;
        dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);

        if (element.is('form')) {
          method = element.data('ujs:submit-button-formmethod') || element.attr('method');
          url = element.data('ujs:submit-button-formaction') || element.attr('action');
          data = $(element[0]).serializeArray();
          // memoized value from clicked submit button
          var button = element.data('ujs:submit-button');
          if (button) {
            data.push(button);
            element.data('ujs:submit-button', null);
          }
          element.data('ujs:submit-button-formmethod', null);
          element.data('ujs:submit-button-formaction', null);
        } else if (element.is(rails.inputChangeSelector)) {
          method = element.data('method');
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&' + element.data('params');
        } else if (element.is(rails.buttonClickSelector)) {
          method = element.data('method') || 'get';
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&' + element.data('params');
        } else {
          method = element.data('method');
          url = rails.href(element);
          data = element.data('params') || null;
        }

        options = {
          type: method || 'GET', data: data, dataType: dataType,
          // stopping the "ajax:beforeSend" event will cancel the ajax request
          beforeSend: function(xhr, settings) {
            if (settings.dataType === undefined) {
              xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
            }
            if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
              element.trigger('ajax:send', xhr);
            } else {
              return false;
            }
          },
          success: function(data, status, xhr) {
            element.trigger('ajax:success', [data, status, xhr]);
          },
          complete: function(xhr, status) {
            element.trigger('ajax:complete', [xhr, status]);
          },
          error: function(xhr, status, error) {
            element.trigger('ajax:error', [xhr, status, error]);
          },
          crossDomain: rails.isCrossDomain(url)
        };

        // There is no withCredentials for IE6-8 when
        // "Enable native XMLHTTP support" is disabled
        if (withCredentials) {
          options.xhrFields = {
            withCredentials: withCredentials
          };
        }

        // Only pass url to `ajax` options if not blank
        if (url) { options.url = url; }

        return rails.ajax(options);
      } else {
        return false;
      }
    },

    // Determines if the request is a cross domain request.
    isCrossDomain: function(url) {
      var originAnchor = document.createElement('a');
      originAnchor.href = location.href;
      var urlAnchor = document.createElement('a');

      try {
        urlAnchor.href = url;
        // This is a workaround to a IE bug.
        urlAnchor.href = urlAnchor.href;

        // If URL protocol is false or is a string containing a single colon
        // *and* host are false, assume it is not a cross-domain request
        // (should only be the case for IE7 and IE compatibility mode).
        // Otherwise, evaluate protocol and host of the URL against the origin
        // protocol and host.
        return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) ||
          (originAnchor.protocol + '//' + originAnchor.host ===
            urlAnchor.protocol + '//' + urlAnchor.host));
      } catch (e) {
        // If there is an error parsing the URL, assume it is crossDomain.
        return true;
      }
    },

    // Handles "data-method" on links such as:
    // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
    handleMethod: function(link) {
      var href = rails.href(link),
        method = link.data('method'),
        target = link.attr('target'),
        csrfToken = rails.csrfToken(),
        csrfParam = rails.csrfParam(),
        form = $('<form method="post" action="' + href + '"></form>'),
        metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';

      if (csrfParam !== undefined && csrfToken !== undefined && !rails.isCrossDomain(href)) {
        metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
      }

      if (target) { form.attr('target', target); }

      form.hide().append(metadataInput).appendTo('body');
      form.submit();
    },

    // Helper function that returns form elements that match the specified CSS selector
    // If form is actually a "form" element this will return associated elements outside the from that have
    // the html form attribute set
    formElements: function(form, selector) {
      return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
    },

    /* Disables form elements:
      - Caches element value in 'ujs:enable-with' data store
      - Replaces element text with value of 'data-disable-with' attribute
      - Sets disabled property to true
    */
    disableFormElements: function(form) {
      rails.formElements(form, rails.disableSelector).each(function() {
        rails.disableFormElement($(this));
      });
    },

    disableFormElement: function(element) {
      var method, replacement;

      method = element.is('button') ? 'html' : 'val';
      replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element[method]());
        element[method](replacement);
      }

      element.prop('disabled', true);
      element.data('ujs:disabled', true);
    },

    /* Re-enables disabled form elements:
      - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
      - Sets disabled property to false
    */
    enableFormElements: function(form) {
      rails.formElements(form, rails.enableSelector).each(function() {
        rails.enableFormElement($(this));
      });
    },

    enableFormElement: function(element) {
      var method = element.is('button') ? 'html' : 'val';
      if (element.data('ujs:enable-with') !== undefined) {
        element[method](element.data('ujs:enable-with'));
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.prop('disabled', false);
      element.removeData('ujs:disabled');
    },

   /* For 'data-confirm' attribute:
      - Fires `confirm` event
      - Shows the confirmation dialog
      - Fires the `confirm:complete` event

      Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
      Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
      Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
      return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
   */
    allowAction: function(element) {
      var message = element.data('confirm'),
          answer = false, callback;
      if (!message) { return true; }

      if (rails.fire(element, 'confirm')) {
        try {
          answer = rails.confirm(message);
        } catch (e) {
          (console.error || console.log).call(console, e.stack || e);
        }
        callback = rails.fire(element, 'confirm:complete', [answer]);
      }
      return answer && callback;
    },

    // Helper function which checks for blank inputs in a form that match the specified CSS selector
    blankInputs: function(form, specifiedSelector, nonBlank) {
      var foundInputs = $(),
        input,
        valueToCheck,
        radiosForNameWithNoneSelected,
        radioName,
        selector = specifiedSelector || 'input,textarea',
        requiredInputs = form.find(selector),
        checkedRadioButtonNames = {};

      requiredInputs.each(function() {
        input = $(this);
        if (input.is('input[type=radio]')) {

          // Don't count unchecked required radio as blank if other radio with same name is checked,
          // regardless of whether same-name radio input has required attribute or not. The spec
          // states https://www.w3.org/TR/html5/forms.html#the-required-attribute
          radioName = input.attr('name');

          // Skip if we've already seen the radio with this name.
          if (!checkedRadioButtonNames[radioName]) {

            // If none checked
            if (form.find('input[type=radio]:checked[name="' + radioName + '"]').length === 0) {
              radiosForNameWithNoneSelected = form.find(
                'input[type=radio][name="' + radioName + '"]');
              foundInputs = foundInputs.add(radiosForNameWithNoneSelected);
            }

            // We only need to check each name once.
            checkedRadioButtonNames[radioName] = radioName;
          }
        } else {
          valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val();
          if (valueToCheck === nonBlank) {
            foundInputs = foundInputs.add(input);
          }
        }
      });
      return foundInputs.length ? foundInputs : false;
    },

    // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
    nonBlankInputs: function(form, specifiedSelector) {
      return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
    },

    // Helper function, needed to provide consistent behavior in IE
    stopEverything: function(e) {
      $(e.target).trigger('ujs:everythingStopped');
      e.stopImmediatePropagation();
      return false;
    },

    //  Replace element's html with the 'data-disable-with' after storing original html
    //  and prevent clicking on it
    disableElement: function(element) {
      var replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element.html()); // store enabled state
        element.html(replacement);
      }

      element.bind('click.railsDisable', function(e) { // prevent further clicking
        return rails.stopEverything(e);
      });
      element.data('ujs:disabled', true);
    },

    // Restore element to its original state which was disabled by 'disableElement' above
    enableElement: function(element) {
      if (element.data('ujs:enable-with') !== undefined) {
        element.html(element.data('ujs:enable-with')); // set to old enabled state
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.unbind('click.railsDisable'); // enable element
      element.removeData('ujs:disabled');
    }
  };

  if (rails.fire($document, 'rails:attachBindings')) {

    $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});

    // This event works the same as the load event, except that it fires every
    // time the page is loaded.
    //
    // See https://github.com/rails/jquery-ujs/issues/357
    // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
    $(window).on('pageshow.rails', function () {
      $($.rails.enableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableFormElement(element);
        }
      });

      $($.rails.linkDisableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableElement(element);
        }
      });
    });

    $document.on('ajax:complete', rails.linkDisableSelector, function() {
        rails.enableElement($(this));
    });

    $document.on('ajax:complete', rails.buttonDisableSelector, function() {
        rails.enableFormElement($(this));
    });

    $document.on('click.rails', rails.linkClickSelector, function(e) {
      var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
      if (!rails.allowAction(link)) return rails.stopEverything(e);

      if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link);

      if (rails.isRemote(link)) {
        if (metaClick && (!method || method === 'GET') && !data) { return true; }

        var handleRemote = rails.handleRemote(link);
        // Response from rails.handleRemote() will either be false or a deferred object promise.
        if (handleRemote === false) {
          rails.enableElement(link);
        } else {
          handleRemote.fail( function() { rails.enableElement(link); } );
        }
        return false;

      } else if (method) {
        rails.handleMethod(link);
        return false;
      }
    });

    $document.on('click.rails', rails.buttonClickSelector, function(e) {
      var button = $(this);

      if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e);

      if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);

      var handleRemote = rails.handleRemote(button);
      // Response from rails.handleRemote() will either be false or a deferred object promise.
      if (handleRemote === false) {
        rails.enableFormElement(button);
      } else {
        handleRemote.fail( function() { rails.enableFormElement(button); } );
      }
      return false;
    });

    $document.on('change.rails', rails.inputChangeSelector, function(e) {
      var link = $(this);
      if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e);

      rails.handleRemote(link);
      return false;
    });

    $document.on('submit.rails', rails.formSubmitSelector, function(e) {
      var form = $(this),
        remote = rails.isRemote(form),
        blankRequiredInputs,
        nonBlankFileInputs;

      if (!rails.allowAction(form)) return rails.stopEverything(e);

      // Skip other logic when required values are missing or file upload is present
      if (form.attr('novalidate') === undefined) {
        if (form.data('ujs:formnovalidate-button') === undefined) {
          blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false);
          if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
            return rails.stopEverything(e);
          }
        } else {
          // Clear the formnovalidate in case the next button click is not on a formnovalidate button
          // Not strictly necessary to do here, since it is also reset on each button click, but just to be certain
          form.data('ujs:formnovalidate-button', undefined);
        }
      }

      if (remote) {
        nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
        if (nonBlankFileInputs) {
          // Slight timeout so that the submit button gets properly serialized
          // (make it easy for event handler to serialize form without disabled values)
          setTimeout(function(){ rails.disableFormElements(form); }, 13);
          var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);

          // Re-enable form elements if event bindings return false (canceling normal form submission)
          if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); }

          return aborted;
        }

        rails.handleRemote(form);
        return false;

      } else {
        // Slight timeout so that the submit button gets properly serialized
        setTimeout(function(){ rails.disableFormElements(form); }, 13);
      }
    });

    $document.on('click.rails', rails.formInputClickSelector, function(event) {
      var button = $(this);

      if (!rails.allowAction(button)) return rails.stopEverything(event);

      // Register the pressed submit button
      var name = button.attr('name'),
        data = name ? {name:name, value:button.val()} : null;

      var form = button.closest('form');
      if (form.length === 0) {
        form = $('#' + button.attr('form'));
      }
      form.data('ujs:submit-button', data);

      // Save attributes from button
      form.data('ujs:formnovalidate-button', button.attr('formnovalidate'));
      form.data('ujs:submit-button-formaction', button.attr('formaction'));
      form.data('ujs:submit-button-formmethod', button.attr('formmethod'));
    });

    $document.on('ajax:send.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.disableFormElements($(this));
    });

    $document.on('ajax:complete.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.enableFormElements($(this));
    });

    $(function(){
      rails.refreshCSRFTokens();
    });
  }

})( jQuery );
function setUpDateSearch(date_container_id, jq_grid_id, search_column, calendar_html, link_id) {
  $(document).ready(function () {
    $('#' + date_container_id).jqGrid('filterGrid', '#' + jq_grid_id,
      {
        gridModel: false,
        filterModel: [
          {
            label: 'Date Filter&nbsp;&nbsp;&nbsp;&nbsp;From:',
            name: search_column + '_min',
            stype: 'text',
            sopt: {
              id: 'begin_date_' + jq_grid_id
            }
          },
          {
            label: 'To:',
            name: search_column + '_max',
            stype: 'text',
            sopt: {
              id: 'end_date_' + jq_grid_id
            }
          }
        ],
        enableSearch: true,
        searchButton: 'Go'
      }
    );
    $('#' + date_container_id + ' input[name="' + search_column + '_min"]')
      .datepicker({ dateFormat: 'yy/mm/dd', changeYear: true });
    $('#' + date_container_id + ' input[name="' + search_column + '_max"]')
      .datepicker({ dateFormat: 'yy/mm/dd', changeYear: true });

    $('#' + jq_grid_id + '_calendar_search').append(calendar_html);
    $('#' + link_id).click(function (e) {
      $('#' + date_container_id).toggle();
      e.preventDefault();
    });
  });
};
;(function($) {
  var Backstop = window.Backstop || {};
  if( window.Backstop === undefined ) {
    window.Backstop = Backstop;
  }

  /* Protect ourselves from IE */
  if( window.console === undefined ) {
    window.console = {};
    window.console.log = function() {};
  }

  Backstop.redirect = function( url ) {
    if( typeof window.location.assign === "function" ) {
      window.location.assign( url );
    } else {
      window.location.href = url;
    }
  };

  Backstop.isnull = function( value ) {
    return typeof value == "undefined" || value === null;
  };
}(jQuery));
/*
 * jquery.layout 1.2.0
 *
 * Copyright (c) 2008
 *   Fabrizio Balliano (http://www.fabrizioballiano.net)
 *   Kevin Dalman (http://allpro.net)
 *
 * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
 * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
 *
 * $Date: 2008-12-27 02:17:22 +0100 (sab, 27 dic 2008) $
 * $Rev: 203 $
 *
 * NOTE: For best code readability, view this with a fixed-space font and tabs equal to 4-chars
 */
(function($){$.fn.layout=function(opts){var
prefix="ui-layout-",defaults={paneClass:prefix+"pane",resizerClass:prefix+"resizer",togglerClass:prefix+"toggler",togglerInnerClass:prefix+"",buttonClass:prefix+"button",contentSelector:"."+prefix+"content",contentIgnoreSelector:"."+prefix+"ignore"};var options={name:"",scrollToBookmarkOnLoad:true,defaults:{applyDefaultStyles:false,closable:true,resizable:true,slidable:true,contentSelector:defaults.contentSelector,contentIgnoreSelector:defaults.contentIgnoreSelector,paneClass:defaults.paneClass,resizerClass:defaults.resizerClass,togglerClass:defaults.togglerClass,buttonClass:defaults.buttonClass,resizerDragOpacity:1,maskIframesOnResize:true,minSize:0,maxSize:0,spacing_open:6,spacing_closed:6,togglerLength_open:50,togglerLength_closed:50,togglerAlign_open:"center",togglerAlign_closed:"center",togglerTip_open:"Close",togglerTip_closed:"Open",resizerTip:"Resize",sliderTip:"Slide Open",sliderCursor:"pointer",slideTrigger_open:"click",slideTrigger_close:"mouseout",hideTogglerOnSlide:false,togglerContent_open:"",togglerContent_closed:"",showOverflowOnHover:false,enableCursorHotkey:true,customHotkeyModifier:"SHIFT",fxName:"slide",fxSpeed:null,fxSettings:{},initClosed:false,initHidden:false},north:{paneSelector:"."+prefix+"north",size:"auto",resizerCursor:"n-resize"},south:{paneSelector:"."+prefix+"south",size:"auto",resizerCursor:"s-resize"},east:{paneSelector:"."+prefix+"east",size:200,resizerCursor:"e-resize"},west:{paneSelector:"."+prefix+"west",size:200,resizerCursor:"w-resize"},center:{paneSelector:"."+prefix+"center"}};var effects={slide:{all:{duration:"fast"},north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},drop:{all:{duration:"slow"},north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},scale:{all:{duration:"fast"}}};var config={allPanes:"north,south,east,west,center",borderPanes:"north,south,east,west",zIndex:{resizer_normal:1,pane_normal:2,mask:4,sliding:100,resizing:10000,animation:10000},resizers:{cssReq:{position:"absolute",padding:0,margin:0,fontSize:"1px",textAlign:"left",overflow:"hidden",zIndex:1},cssDef:{background:"#DDD",border:"none"}},togglers:{cssReq:{position:"absolute",display:"block",padding:0,margin:0,overflow:"hidden",textAlign:"center",fontSize:"1px",cursor:"pointer",zIndex:1},cssDef:{background:"#AAA"}},content:{cssReq:{overflow:"auto"},cssDef:{}},defaults:{cssReq:{position:"absolute",margin:0,zIndex:2},cssDef:{padding:"10px",background:"#FFF",border:"1px solid #BBB",overflow:"auto"}},north:{edge:"top",sizeType:"height",dir:"horz",cssReq:{top:0,bottom:"auto",left:0,right:0,width:"auto"}},south:{edge:"bottom",sizeType:"height",dir:"horz",cssReq:{top:"auto",bottom:0,left:0,right:0,width:"auto"}},east:{edge:"right",sizeType:"width",dir:"vert",cssReq:{left:"auto",right:0,top:"auto",bottom:"auto",height:"auto"}},west:{edge:"left",sizeType:"width",dir:"vert",cssReq:{left:0,right:"auto",top:"auto",bottom:"auto",height:"auto"}},center:{dir:"center",cssReq:{left:"auto",right:"auto",top:"auto",bottom:"auto",height:"auto",width:"auto"}}};var state={id:Math.floor(Math.random()*10000),container:{},north:{},south:{},east:{},west:{},center:{}};var
altEdge={top:"bottom",bottom:"top",left:"right",right:"left"},altSide={north:"south",south:"north",east:"west",west:"east"};var isStr=function(o){if(typeof o=="string")return true;else if(typeof o=="object"){try{var match=o.constructor.toString().match(/string/i);return(match!==null);}catch(e){}}return false;};var str=function(o){if(typeof o=="string"||isStr(o))return $.trim(o);else return o;};var min=function(x,y){return Math.min(x,y);};var max=function(x,y){return Math.max(x,y);};var transformData=function(d){var json={defaults:{fxSettings:{}},north:{fxSettings:{}},south:{fxSettings:{}},east:{fxSettings:{}},west:{fxSettings:{}},center:{fxSettings:{}}};d=d||{};if(d.effects||d.defaults||d.north||d.south||d.west||d.east||d.center)json=$.extend(json,d);else
$.each(d,function(key,val){a=key.split("__");json[a[1]?a[0]:"defaults"][a[1]?a[1]:a[0]]=val;});return json;};var setFlowCallback=function(action,pane,param){var
cb=action+","+pane+","+(param?1:0),cP,cbPane;$.each(c.borderPanes.split(","),function(i,p){if(c[p].isMoving){bindCallback(p);return false;}});function bindCallback(p,test){cP=c[p];if(!cP.doCallback){cP.doCallback=true;cP.callback=cb;}else{cpPane=cP.callback.split(",")[1];if(cpPane!=p&&cpPane!=pane)bindCallback(cpPane,true);}}};var execFlowCallback=function(pane){var cP=c[pane];c.isLayoutBusy=false;delete cP.isMoving;if(!cP.doCallback||!cP.callback)return;cP.doCallback=false;var
cb=cP.callback.split(","),param=(cb[2]>0?true:false);if(cb[0]=="open")open(cb[1],param);else if(cb[0]=="close")close(cb[1],param);if(!cP.doCallback)cP.callback=null;};var execUserCallback=function(pane,v_fn){if(!v_fn)return;var fn;try{if(typeof v_fn=="function")fn=v_fn;else if(typeof v_fn!="string")return;else if(v_fn.indexOf(",")>0){var
args=v_fn.split(","),fn=eval(args[0]);if(typeof fn=="function"&&args.length>1)return fn(args[1]);}else
fn=eval(v_fn);if(typeof fn=="function")return fn(pane,$Ps[pane],$.extend({},state[pane]),$.extend({},options[pane]),options.name);}catch(ex){}};var cssNum=function($E,prop){var
val=0,hidden=false,visibility="";if(!$.browser.msie){if($.curCSS($E[0],"display",true)=="none"){hidden=true;visibility=$.curCSS($E[0],"visibility",true);$E.css({display:"block",visibility:"hidden"});}}val=parseInt($.curCSS($E[0],prop,true),10)||0;if(hidden){$E.css({display:"none"});if(visibility&&visibility!="hidden")$E.css({visibility:visibility});}return val;};var cssW=function(e,outerWidth){var $E;if(isStr(e)){e=str(e);$E=$Ps[e];}else
$E=$(e);if(outerWidth<=0)return 0;else if(!(outerWidth>0))outerWidth=isStr(e)?getPaneSize(e):$E.outerWidth();if(!$.boxModel)return outerWidth;else
return outerWidth
-cssNum($E,"paddingLeft")-cssNum($E,"paddingRight")-($.curCSS($E[0],"borderLeftStyle",true)=="none"?0:cssNum($E,"borderLeftWidth"))-($.curCSS($E[0],"borderRightStyle",true)=="none"?0:cssNum($E,"borderRightWidth"));};var cssH=function(e,outerHeight){var $E;if(isStr(e)){e=str(e);$E=$Ps[e];}else
$E=$(e);if(outerHeight<=0)return 0;else if(!(outerHeight>0))outerHeight=(isStr(e))?getPaneSize(e):$E.outerHeight();if(!$.boxModel)return outerHeight;else
return outerHeight
-cssNum($E,"paddingTop")-cssNum($E,"paddingBottom")-($.curCSS($E[0],"borderTopStyle",true)=="none"?0:cssNum($E,"borderTopWidth"))-($.curCSS($E[0],"borderBottomStyle",true)=="none"?0:cssNum($E,"borderBottomWidth"));};var cssSize=function(pane,outerSize){if(c[pane].dir=="horz")return cssH(pane,outerSize);else
return cssW(pane,outerSize);};var getPaneSize=function(pane,inclSpace){var
$P=$Ps[pane],o=options[pane],s=state[pane],oSp=(inclSpace?o.spacing_open:0),cSp=(inclSpace?o.spacing_closed:0);if(!$P||s.isHidden)return 0;else if(s.isClosed||(s.isSliding&&inclSpace))return cSp;else if(c[pane].dir=="horz")return $P.outerHeight()+oSp;else
return $P.outerWidth()+oSp;};var setPaneMinMaxSizes=function(pane){var
d=cDims,edge=c[pane].edge,dir=c[pane].dir,o=options[pane],s=state[pane],$P=$Ps[pane],$altPane=$Ps[altSide[pane]],paneSpacing=o.spacing_open,altPaneSpacing=options[altSide[pane]].spacing_open,altPaneSize=(!$altPane?0:(dir=="horz"?$altPane.outerHeight():$altPane.outerWidth())),containerSize=(dir=="horz"?d.innerHeight:d.innerWidth),limitSize=containerSize-paneSpacing-altPaneSize-altPaneSpacing,minSize=s.minSize||0,maxSize=Math.min(s.maxSize||9999,limitSize),minPos,maxPos;switch(pane){case"north":minPos=d.offsetTop+minSize;maxPos=d.offsetTop+maxSize;break;case"west":minPos=d.offsetLeft+minSize;maxPos=d.offsetLeft+maxSize;break;case"south":minPos=d.offsetTop+d.innerHeight-maxSize;maxPos=d.offsetTop+d.innerHeight-minSize;break;case"east":minPos=d.offsetLeft+d.innerWidth-maxSize;maxPos=d.offsetLeft+d.innerWidth-minSize;break;}$.extend(s,{minSize:minSize,maxSize:maxSize,minPosition:minPos,maxPosition:maxPos});};var getPaneDims=function(){var d={top:getPaneSize("north",true),bottom:getPaneSize("south",true),left:getPaneSize("west",true),right:getPaneSize("east",true),width:0,height:0};with(d){width=cDims.innerWidth-left-right;height=cDims.innerHeight-bottom-top;top+=cDims.top;bottom+=cDims.bottom;left+=cDims.left;right+=cDims.right;}return d;};var getElemDims=function($E){var
d={},e,b,p;$.each("Left,Right,Top,Bottom".split(","),function(){e=str(this);b=d["border"+e]=cssNum($E,"border"+e+"Width");p=d["padding"+e]=cssNum($E,"padding"+e);d["offset"+e]=b+p;if($E==$Container)d[e.toLowerCase()]=($.boxModel?p:0);});d.innerWidth=d.outerWidth=$E.outerWidth();d.innerHeight=d.outerHeight=$E.outerHeight();if($.boxModel){d.innerWidth-=(d.offsetLeft+d.offsetRight);d.innerHeight-=(d.offsetTop+d.offsetBottom);}return d;};var setTimer=function(pane,action,fn,ms){var
Layout=window.layout=window.layout||{},Timers=Layout.timers=Layout.timers||{},name="layout_"+state.id+"_"+pane+"_"+action;if(Timers[name])return;else Timers[name]=setTimeout(fn,ms);};var clearTimer=function(pane,action){var
Layout=window.layout=window.layout||{},Timers=Layout.timers=Layout.timers||{},name="layout_"+state.id+"_"+pane+"_"+action;if(Timers[name]){clearTimeout(Timers[name]);delete Timers[name];return true;}else
return false;};var create=function(){initOptions();initContainer();initPanes();initHandles();initResizable();sizeContent("all");if(options.scrollToBookmarkOnLoad)with(self.location)if(hash)replace(hash);initHotkeys();$(window).resize(function(){var timerID="timerLayout_"+state.id;if(window[timerID])clearTimeout(window[timerID]);window[timerID]=null;if(true||$.browser.msie)window[timerID]=setTimeout(resizeAll,100);else
resizeAll();});};var initContainer=function(){try{if($Container[0].tagName=="BODY"){$("html").css({height:"100%",overflow:"hidden"});$("body").css({position:"relative",height:"100%",overflow:"hidden",margin:0,padding:0,border:"none"});}else{var
CSS={overflow:"hidden"},p=$Container.css("position"),h=$Container.css("height");if(!$Container.hasClass("ui-layout-pane")){if(!p||"fixed,absolute,relative".indexOf(p)<0)CSS.position="relative";if(!h||h=="auto")CSS.height="100%";}$Container.css(CSS);}}catch(ex){}cDims=state.container=getElemDims($Container);};var initHotkeys=function(){$.each(c.borderPanes.split(","),function(i,pane){var o=options[pane];if(o.enableCursorHotkey||o.customHotkey){$(document).keydown(keyDown);return false;}});};var initOptions=function(){opts=transformData(opts);if(opts.effects){$.extend(effects,opts.effects);delete opts.effects;}$.each("name,scrollToBookmarkOnLoad".split(","),function(idx,key){if(opts[key]!==undefined)options[key]=opts[key];else if(opts.defaults[key]!==undefined){options[key]=opts.defaults[key];delete opts.defaults[key];}});$.each("paneSelector,resizerCursor,customHotkey".split(","),function(idx,key){delete opts.defaults[key];});$.extend(options.defaults,opts.defaults);c.center=$.extend(true,{},c.defaults,c.center);$.extend(options.center,opts.center);var o_Center=$.extend(true,{},options.defaults,opts.defaults,options.center);$.each("paneClass,contentSelector,contentIgnoreSelector,applyDefaultStyles,showOverflowOnHover".split(","),function(idx,key){options.center[key]=o_Center[key];});var defs=options.defaults;$.each(c.borderPanes.split(","),function(i,pane){c[pane]=$.extend(true,{},c.defaults,c[pane]);o=options[pane]=$.extend(true,{},options.defaults,options[pane],opts.defaults,opts[pane]);if(!o.paneClass)o.paneClass=defaults.paneClass;if(!o.resizerClass)o.resizerClass=defaults.resizerClass;if(!o.togglerClass)o.togglerClass=defaults.togglerClass;$.each(["_open","_close",""],function(i,n){var
sName="fxName"+n,sSpeed="fxSpeed"+n,sSettings="fxSettings"+n;o[sName]=opts[pane][sName]||opts[pane].fxName||opts.defaults[sName]||opts.defaults.fxName||o[sName]||o.fxName||defs[sName]||defs.fxName||"none";var fxName=o[sName];if(fxName=="none"||!$.effects||!$.effects[fxName]||(!effects[fxName]&&!o[sSettings]&&!o.fxSettings))fxName=o[sName]="none";var
fx=effects[fxName]||{},fx_all=fx.all||{},fx_pane=fx[pane]||{};o[sSettings]=$.extend({},fx_all,fx_pane,defs.fxSettings||{},defs[sSettings]||{},o.fxSettings,o[sSettings],opts.defaults.fxSettings,opts.defaults[sSettings]||{},opts[pane].fxSettings,opts[pane][sSettings]||{});o[sSpeed]=opts[pane][sSpeed]||opts[pane].fxSpeed||opts.defaults[sSpeed]||opts.defaults.fxSpeed||o[sSpeed]||o[sSettings].duration||o.fxSpeed||o.fxSettings.duration||defs.fxSpeed||defs.fxSettings.duration||fx_pane.duration||fx_all.duration||"normal";});});};var initPanes=function(){$.each(c.allPanes.split(","),function(){var
pane=str(this),o=options[pane],s=state[pane],fx=s.fx,dir=c[pane].dir,size=o.size=="auto"||isNaN(o.size)?0:o.size,minSize=o.minSize||1,maxSize=o.maxSize||9999,spacing=o.spacing_open||0,sel=o.paneSelector,isIE6=($.browser.msie&&$.browser.version<7),CSS={},$P,$C;$Cs[pane]=false;if(sel.substr(0,1)==="#")$P=$Ps[pane]=$Container.find(sel+":first");else{$P=$Ps[pane]=$Container.children(sel+":first");if(!$P.length)$P=$Ps[pane]=$Container.children("form:first").children(sel+":first");}if(!$P.length){$Ps[pane]=false;return true;}$P.attr("pane",pane).addClass(o.paneClass+" "+o.paneClass+"-"+pane);if(pane!="center"){s.isClosed=false;s.isSliding=false;s.isResizing=false;s.isHidden=false;s.noRoom=false;c[pane].pins=[];}CSS=$.extend({visibility:"visible",display:"block"},c.defaults.cssReq,c[pane].cssReq);if(o.applyDefaultStyles)$.extend(CSS,c.defaults.cssDef,c[pane].cssDef);$P.css(CSS);CSS={};switch(pane){case"north":CSS.top=cDims.top;CSS.left=cDims.left;CSS.right=cDims.right;break;case"south":CSS.bottom=cDims.bottom;CSS.left=cDims.left;CSS.right=cDims.right;break;case"west":CSS.left=cDims.left;break;case"east":CSS.right=cDims.right;break;case"center":}if(dir=="horz"){if(size===0||size=="auto"){$P.css({height:"auto"});size=$P.outerHeight();}size=max(size,minSize);size=min(size,maxSize);size=min(size,cDims.innerHeight-spacing);CSS.height=max(1,cssH(pane,size));s.size=size;s.maxSize=maxSize;s.minSize=max(minSize,size-CSS.height+1);$P.css(CSS);}else if(dir=="vert"){if(size===0||size=="auto"){$P.css({width:"auto",float:"left"});size=$P.outerWidth();$P.css({float:"none"});}size=max(size,minSize);size=min(size,maxSize);size=min(size,cDims.innerWidth-spacing);CSS.width=max(1,cssW(pane,size));s.size=size;s.maxSize=maxSize;s.minSize=max(minSize,size-CSS.width+1);$P.css(CSS);sizeMidPanes(pane,null,true);}else if(pane=="center"){$P.css(CSS);sizeMidPanes("center",null,true);}if(o.initClosed&&o.closable){$P.hide().addClass("closed");s.isClosed=true;}else if(o.initHidden||o.initClosed){hide(pane,true);s.isHidden=true;}else
$P.addClass("open");if(o.showOverflowOnHover)$P.hover(allowOverflow,resetOverflow);if(o.contentSelector){$C=$Cs[pane]=$P.children(o.contentSelector+":first");if(!$C.length){$Cs[pane]=false;return true;}$C.css(c.content.cssReq);if(o.applyDefaultStyles)$C.css(c.content.cssDef);$P.css({overflow:"hidden"});}});};var initHandles=function(){$.each(c.borderPanes.split(","),function(){var
pane=str(this),o=options[pane],s=state[pane],rClass=o.resizerClass,tClass=o.togglerClass,$P=$Ps[pane];$Rs[pane]=false;$Ts[pane]=false;if(!$P||(!o.closable&&!o.resizable))return;var
edge=c[pane].edge,isOpen=$P.is(":visible"),spacing=(isOpen?o.spacing_open:o.spacing_closed),_pane="-"+pane,_state=(isOpen?"-open":"-closed"),$R,$T;$R=$Rs[pane]=$("<span></span>");if(isOpen&&o.resizable);else if(!isOpen&&o.slidable)$R.attr("title",o.sliderTip).css("cursor",o.sliderCursor);$R.attr("id",(o.paneSelector.substr(0,1)=="#"?o.paneSelector.substr(1)+"-resizer":"")).attr("resizer",pane).css(c.resizers.cssReq).css(edge,cDims[edge]+getPaneSize(pane)).addClass(rClass+" "+rClass+_pane+" "+rClass+_state+" "+rClass+_pane+_state).appendTo($Container);if(o.applyDefaultStyles)$R.css(c.resizers.cssDef);if(o.closable){$T=$Ts[pane]=$("<div></div>");$T.attr("id",(o.paneSelector.substr(0,1)=="#"?o.paneSelector.substr(1)+"-toggler":"")).css(c.togglers.cssReq).attr("title",(isOpen?o.togglerTip_open:o.togglerTip_closed)).click(function(evt){toggle(pane);evt.stopPropagation();}).mouseover(function(evt){evt.stopPropagation();}).addClass(tClass+" "+tClass+_pane+" "+tClass+_state+" "+tClass+_pane+_state).appendTo($R);if(o.togglerContent_open)$("<span>"+o.togglerContent_open+"</span>").addClass("content content-open").css("display",s.isClosed?"none":"block").appendTo($T);if(o.togglerContent_closed)$("<span>"+o.togglerContent_closed+"</span>").addClass("content content-closed").css("display",s.isClosed?"block":"none").appendTo($T);if(o.applyDefaultStyles)$T.css(c.togglers.cssDef);if(!isOpen)bindStartSlidingEvent(pane,true);}});sizeHandles("all",true);};var initResizable=function(){var
draggingAvailable=(typeof $.fn.draggable=="function"),minPosition,maxPosition,edge;$.each(c.borderPanes.split(","),function(){var
pane=str(this),o=options[pane],s=state[pane];if(!draggingAvailable||!$Ps[pane]||!o.resizable){o.resizable=false;return true;}var
rClass=o.resizerClass,dragClass=rClass+"-drag",dragPaneClass=rClass+"-"+pane+"-drag",draggingClass=rClass+"-dragging",draggingPaneClass=rClass+"-"+pane+"-dragging",draggingClassSet=false,$P=$Ps[pane],$R=$Rs[pane];if(!s.isClosed)$R.attr("title",o.resizerTip).css("cursor",o.resizerCursor);$R.draggable({containment:$Container[0],axis:(c[pane].dir=="horz"?"y":"x"),delay:200,distance:1,helper:"clone",opacity:o.resizerDragOpacity,zIndex:c.zIndex.resizing,start:function(e,ui){if(false===execUserCallback(pane,o.onresize_start))return false;s.isResizing=true;clearTimer(pane,"closeSlider");$R.addClass(dragClass+" "+dragPaneClass);draggingClassSet=false;var resizerWidth=(pane=="east"||pane=="south"?o.spacing_open:0);setPaneMinMaxSizes(pane);s.minPosition-=resizerWidth;s.maxPosition-=resizerWidth;edge=(c[pane].dir=="horz"?"top":"left");$(o.maskIframesOnResize===true?"iframe":o.maskIframesOnResize).each(function(){$('<div class="ui-layout-mask"/>').css({background:"#fff",opacity:"0.001",zIndex:9,position:"absolute",width:this.offsetWidth+"px",height:this.offsetHeight+"px"}).css($(this).offset()).appendTo(this.parentNode);});},drag:function(e,ui){if(!draggingClassSet){$(".ui-draggable-dragging").addClass(draggingClass+" "+draggingPaneClass).children().css("visibility","hidden");draggingClassSet=true;if(s.isSliding)$Ps[pane].css("zIndex",c.zIndex.sliding);}if(ui.position[edge]<s.minPosition)ui.position[edge]=s.minPosition;else if(ui.position[edge]>s.maxPosition)ui.position[edge]=s.maxPosition;},stop:function(e,ui){var
dragPos=ui.position,resizerPos,newSize;$R.removeClass(dragClass+" "+dragPaneClass);switch(pane){case"north":resizerPos=dragPos.top;break;case"west":resizerPos=dragPos.left;break;case"south":resizerPos=cDims.outerHeight-dragPos.top-$R.outerHeight();break;case"east":resizerPos=cDims.outerWidth-dragPos.left-$R.outerWidth();break;}newSize=resizerPos-cDims[c[pane].edge];sizePane(pane,newSize);$("div.ui-layout-mask").remove();s.isResizing=false;}});});};var hide=function(pane,onInit){var
o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];if(!$P||s.isHidden)return;if(false===execUserCallback(pane,o.onhide_start))return;s.isSliding=false;if($R)$R.hide();if(onInit||s.isClosed){s.isClosed=true;s.isHidden=true;$P.hide();sizeMidPanes(c[pane].dir=="horz"?"all":"center");execUserCallback(pane,o.onhide_end||o.onhide);}else{s.isHiding=true;close(pane,false);}};var show=function(pane,openPane){var
o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];if(!$P||!s.isHidden)return;if(false===execUserCallback(pane,o.onshow_start))return;s.isSliding=false;s.isShowing=true;if($R&&o.spacing_open>0)$R.show();if(openPane===false)close(pane,true);else
open(pane);};var toggle=function(pane){var s=state[pane];if(s.isHidden)show(pane);else if(s.isClosed)open(pane);else
close(pane);};var close=function(pane,force,noAnimation){var
$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane],o=options[pane],s=state[pane],doFX=!noAnimation&&!s.isClosed&&(o.fxName_close!="none"),edge=c[pane].edge,rClass=o.resizerClass,tClass=o.togglerClass,_pane="-"+pane,_open="-open",_sliding="-sliding",_closed="-closed",isShowing=s.isShowing,isHiding=s.isHiding;delete s.isShowing;delete s.isHiding;if(!$P||(!o.resizable&&!o.closable))return;else if(!force&&s.isClosed&&!isShowing)return;if(c.isLayoutBusy){setFlowCallback("close",pane,force);return;}if(!isShowing&&false===execUserCallback(pane,o.onclose_start))return;c[pane].isMoving=true;c.isLayoutBusy=true;s.isClosed=true;if(isHiding)s.isHidden=true;else if(isShowing)s.isHidden=false;syncPinBtns(pane,false);if(!s.isSliding)sizeMidPanes(c[pane].dir=="horz"?"all":"center");if($R){$R.css(edge,cDims[edge]).removeClass(rClass+_open+" "+rClass+_pane+_open).removeClass(rClass+_sliding+" "+rClass+_pane+_sliding).addClass(rClass+_closed+" "+rClass+_pane+_closed);if(o.resizable)$R.draggable("disable").css("cursor","default").attr("title","");if($T){$T.removeClass(tClass+_open+" "+tClass+_pane+_open).addClass(tClass+_closed+" "+tClass+_pane+_closed).attr("title",o.togglerTip_closed);}sizeHandles();}if(doFX){lockPaneForFX(pane,true);$P.hide(o.fxName_close,o.fxSettings_close,o.fxSpeed_close,function(){lockPaneForFX(pane,false);if(!s.isClosed)return;close_2();});}else{$P.hide();close_2();}function close_2(){bindStartSlidingEvent(pane,true);if(!isShowing)execUserCallback(pane,o.onclose_end||o.onclose);if(isShowing)execUserCallback(pane,o.onshow_end||o.onshow);if(isHiding)execUserCallback(pane,o.onhide_end||o.onhide);execFlowCallback(pane);}};var open=function(pane,slide,noAnimation){var
$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane],o=options[pane],s=state[pane],doFX=!noAnimation&&s.isClosed&&(o.fxName_open!="none"),edge=c[pane].edge,rClass=o.resizerClass,tClass=o.togglerClass,_pane="-"+pane,_open="-open",_closed="-closed",_sliding="-sliding",isShowing=s.isShowing;delete s.isShowing;if(!$P||(!o.resizable&&!o.closable))return;else if(!s.isClosed&&!s.isSliding)return;if(s.isHidden&&!isShowing){show(pane,true);return;}if(c.isLayoutBusy){setFlowCallback("open",pane,slide);return;}if(false===execUserCallback(pane,o.onopen_start))return;c[pane].isMoving=true;c.isLayoutBusy=true;if(s.isSliding&&!slide)bindStopSlidingEvents(pane,false);s.isClosed=false;if(isShowing)s.isHidden=false;setPaneMinMaxSizes(pane);if(s.size>s.maxSize)$P.css(c[pane].sizeType,max(1,cssSize(pane,s.maxSize)));bindStartSlidingEvent(pane,false);if(doFX){lockPaneForFX(pane,true);$P.show(o.fxName_open,o.fxSettings_open,o.fxSpeed_open,function(){lockPaneForFX(pane,false);if(s.isClosed)return;open_2();});}else{$P.show();open_2();}function open_2(){if(!s.isSliding)sizeMidPanes(c[pane].dir=="vert"?"center":"all");if($R){$R.css(edge,cDims[edge]+getPaneSize(pane)).removeClass(rClass+_closed+" "+rClass+_pane+_closed).addClass(rClass+_open+" "+rClass+_pane+_open).addClass(!s.isSliding?"":rClass+_sliding+" "+rClass+_pane+_sliding);if(o.resizable)$R.draggable("enable").css("cursor",o.resizerCursor).attr("title",o.resizerTip);else
$R.css("cursor","default");if($T){$T.removeClass(tClass+_closed+" "+tClass+_pane+_closed).addClass(tClass+_open+" "+tClass+_pane+_open).attr("title",o.togglerTip_open);}sizeHandles("all");}sizeContent(pane);syncPinBtns(pane,!s.isSliding);execUserCallback(pane,o.onopen_end||o.onopen);if(isShowing)execUserCallback(pane,o.onshow_end||o.onshow);execFlowCallback(pane);}};var lockPaneForFX=function(pane,doLock){var $P=$Ps[pane];if(doLock){$P.css({zIndex:c.zIndex.animation});if(pane=="south")$P.css({top:cDims.top+cDims.innerHeight-$P.outerHeight()});else if(pane=="east")$P.css({left:cDims.left+cDims.innerWidth-$P.outerWidth()});}else{if(!state[pane].isSliding)$P.css({zIndex:c.zIndex.pane_normal});if(pane=="south")$P.css({top:"auto"});else if(pane=="east")$P.css({left:"auto"});}};var bindStartSlidingEvent=function(pane,enable){var
o=options[pane],$R=$Rs[pane],trigger=o.slideTrigger_open;if(!$R||!o.slidable)return;if(trigger!="click"&&trigger!="dblclick"&&trigger!="mouseover")trigger="click";$R
[enable?"bind":"unbind"](trigger,slideOpen).css("cursor",(enable?o.sliderCursor:"default")).attr("title",(enable?o.sliderTip:""));};var bindStopSlidingEvents=function(pane,enable){var
o=options[pane],s=state[pane],trigger=o.slideTrigger_close,action=(enable?"bind":"unbind"),$P=$Ps[pane],$R=$Rs[pane];s.isSliding=enable;clearTimer(pane,"closeSlider");$P.css({zIndex:(enable?c.zIndex.sliding:c.zIndex.pane_normal)});$R.css({zIndex:(enable?c.zIndex.sliding:c.zIndex.resizer_normal)});if(trigger!="click"&&trigger!="mouseout")trigger="mouseout";if(enable){$P.bind(trigger,slideClosed);$R.bind(trigger,slideClosed);if(trigger="mouseout"){$P.bind("mouseover",cancelMouseOut);$R.bind("mouseover",cancelMouseOut);}}else{$P.unbind(trigger);$R.unbind(trigger);if(trigger="mouseout"){$P.unbind("mouseover");$R.unbind("mouseover");clearTimer(pane,"closeSlider");}}function cancelMouseOut(evt){clearTimer(pane,"closeSlider");evt.stopPropagation();}};var slideOpen=function(){var pane=$(this).attr("resizer");if(state[pane].isClosed){bindStopSlidingEvents(pane,true);open(pane,true);}};var slideClosed=function(){var
$E=$(this),pane=$E.attr("pane")||$E.attr("resizer"),o=options[pane],s=state[pane];if(s.isClosed||s.isResizing)return;else if(o.slideTrigger_close=="click")close_NOW();else
setTimer(pane,"closeSlider",close_NOW,300);function close_NOW(){bindStopSlidingEvents(pane,false);if(!s.isClosed)close(pane);}};var sizePane=function(pane,size){var
edge=c[pane].edge,dir=c[pane].dir,o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];setPaneMinMaxSizes(pane);s.minSize=max(s.minSize,o.minSize);if(o.maxSize>0)s.maxSize=min(s.maxSize,o.maxSize);size=max(size,s.minSize);size=min(size,s.maxSize);s.size=size;$R.css(edge,size+cDims[edge]);$P.css(c[pane].sizeType,max(1,cssSize(pane,size)));if(!s.isSliding)sizeMidPanes(dir=="horz"?"all":"center");sizeHandles();sizeContent(pane);execUserCallback(pane,o.onresize_end||o.onresize);};var sizeMidPanes=function(panes,overrideDims,onInit){if(!panes||panes=="all")panes="east,west,center";var d=getPaneDims();if(overrideDims)$.extend(d,overrideDims);$.each(panes.split(","),function(){if(!$Ps[this])return;var
pane=str(this),o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane],hasRoom=true,CSS={};if(pane=="center"){d=getPaneDims();CSS=$.extend({},d);CSS.width=max(1,cssW(pane,CSS.width));CSS.height=max(1,cssH(pane,CSS.height));hasRoom=(CSS.width>1&&CSS.height>1);if($.browser.msie&&(!$.boxModel||$.browser.version<7)){if($Ps.north)$Ps.north.css({width:cssW($Ps.north,cDims.innerWidth)});if($Ps.south)$Ps.south.css({width:cssW($Ps.south,cDims.innerWidth)});}}else{CSS.top=d.top;CSS.bottom=d.bottom;CSS.height=max(1,cssH(pane,d.height));hasRoom=(CSS.height>1);}if(hasRoom){$P.css(CSS);if(s.noRoom){s.noRoom=false;if(s.isHidden)return;else show(pane,!s.isClosed);}if(!onInit){sizeContent(pane);execUserCallback(pane,o.onresize_end||o.onresize);}}else if(!s.noRoom){s.noRoom=true;if(s.isHidden)return;if(onInit){$P.hide();if($R)$R.hide();}else hide(pane);}});};var sizeContent=function(panes){if(!panes||panes=="all")panes=c.allPanes;$.each(panes.split(","),function(){if(!$Cs[this])return;var
pane=str(this),ignore=options[pane].contentIgnoreSelector,$P=$Ps[pane],$C=$Cs[pane],e_C=$C[0],height=cssH($P);;$P.children().each(function(){if(this==e_C)return;var $E=$(this);if(!ignore||!$E.is(ignore))height-=$E.outerHeight();});if(height>0)height=cssH($C,height);if(height<1)$C.hide();else
$C.css({height:height}).show();});};var sizeHandles=function(panes,onInit){if(!panes||panes=="all")panes=c.borderPanes;$.each(panes.split(","),function(){var
pane=str(this),o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane];if(!$P||!$R||(!o.resizable&&!o.closable))return;var
dir=c[pane].dir,_state=(s.isClosed?"_closed":"_open"),spacing=o["spacing"+_state],togAlign=o["togglerAlign"+_state],togLen=o["togglerLength"+_state],paneLen,offset,CSS={};if(spacing==0){$R.hide();return;}else if(!s.noRoom&&!s.isHidden)$R.show();if(dir=="horz"){paneLen=$P.outerWidth();$R.css({width:max(1,cssW($R,paneLen)),height:max(1,cssH($R,spacing)),left:cssNum($P,"left")});}else{paneLen=$P.outerHeight();$R.css({height:max(1,cssH($R,paneLen)),width:max(1,cssW($R,spacing)),top:cDims.top+getPaneSize("north",true)});}if($T){if(togLen==0||(s.isSliding&&o.hideTogglerOnSlide)){$T.hide();return;}else
$T.show();if(!(togLen>0)||togLen=="100%"||togLen>paneLen){togLen=paneLen;offset=0;}else{if(typeof togAlign=="string"){switch(togAlign){case"top":case"left":offset=0;break;case"bottom":case"right":offset=paneLen-togLen;break;case"middle":case"center":default:offset=Math.floor((paneLen-togLen)/2);}}else{var x=parseInt(togAlign);if(togAlign>=0)offset=x;else offset=paneLen-togLen+x;}}var
$TC_o=(o.togglerContent_open?$T.children(".content-open"):false),$TC_c=(o.togglerContent_closed?$T.children(".content-closed"):false),$TC=(s.isClosed?$TC_c:$TC_o);if($TC_o)$TC_o.css("display",s.isClosed?"none":"block");if($TC_c)$TC_c.css("display",s.isClosed?"block":"none");if(dir=="horz"){var width=cssW($T,togLen);$T.css({width:max(0,width),height:max(1,cssH($T,spacing)),left:offset});if($TC)$TC.css("marginLeft",Math.floor((width-$TC.outerWidth())/2));}else{var height=cssH($T,togLen);$T.css({height:max(0,height),width:max(1,cssW($T,spacing)),top:offset});if($TC)$TC.css("marginTop",Math.floor((height-$TC.outerHeight())/2));}}if(onInit&&o.initHidden){$R.hide();if($T)$T.hide();}});};var resizeAll=function(){var
oldW=cDims.innerWidth,oldH=cDims.innerHeight;cDims=state.container=getElemDims($Container);var
checkH=(cDims.innerHeight<oldH),checkW=(cDims.innerWidth<oldW),s,dir;if(checkH||checkW)$.each(["south","north","east","west"],function(i,pane){s=state[pane];dir=c[pane].dir;if(!s.isClosed&&((checkH&&dir=="horz")||(checkW&&dir=="vert"))){setPaneMinMaxSizes(pane);if(s.size>s.maxSize)sizePane(pane,s.maxSize);}});sizeMidPanes("all");sizeHandles("all");};function keyDown(evt){if(!evt)return true;var code=evt.keyCode;if(code<33)return true;var
PANE={38:"north",40:"south",37:"west",39:"east"},isCursorKey=(code>=37&&code<=40),ALT=evt.altKey,SHIFT=evt.shiftKey,CTRL=evt.ctrlKey,pane=false,s,o,k,m,el;if(!CTRL&&!SHIFT)return true;else if(isCursorKey&&options[PANE[code]].enableCursorHotkey)pane=PANE[code];else
$.each(c.borderPanes.split(","),function(i,p){o=options[p];k=o.customHotkey;m=o.customHotkeyModifier;if((SHIFT&&m=="SHIFT")||(CTRL&&m=="CTRL")||(CTRL&&SHIFT)){if(k&&code==(isNaN(k)||k<=9?k.toUpperCase().charCodeAt(0):k)){pane=p;return false;}}});if(!pane)return true;o=options[pane];s=state[pane];if(!o.enableCursorHotkey||s.isHidden||!$Ps[pane])return true;el=evt.target||evt.srcElement;if(el&&SHIFT&&isCursorKey&&(el.tagName=="TEXTAREA"||(el.tagName=="INPUT"&&(code==37||code==39))))return true;toggle(pane);evt.stopPropagation();evt.returnValue=false;return false;};function allowOverflow(elem){if(this&&this.tagName)elem=this;var $P;if(typeof elem=="string")$P=$Ps[elem];else{if($(elem).attr("pane"))$P=$(elem);else $P=$(elem).parents("div[pane]:first");}if(!$P.length)return;var
pane=$P.attr("pane"),s=state[pane];if(s.cssSaved)resetOverflow(pane);if(s.isSliding||s.isResizing||s.isClosed){s.cssSaved=false;return;}var
newCSS={zIndex:(c.zIndex.pane_normal+1)},curCSS={},of=$P.css("overflow"),ofX=$P.css("overflowX"),ofY=$P.css("overflowY");if(of!="visible"){curCSS.overflow=of;newCSS.overflow="visible";}if(ofX&&ofX!="visible"&&ofX!="auto"){curCSS.overflowX=ofX;newCSS.overflowX="visible";}if(ofY&&ofY!="visible"&&ofY!="auto"){curCSS.overflowY=ofX;newCSS.overflowY="visible";}s.cssSaved=curCSS;$P.css(newCSS);$.each(c.allPanes.split(","),function(i,p){if(p!=pane)resetOverflow(p);});};function resetOverflow(elem){if(this&&this.tagName)elem=this;var $P;if(typeof elem=="string")$P=$Ps[elem];else{if($(elem).hasClass("ui-layout-pane"))$P=$(elem);else $P=$(elem).parents("div[pane]:first");}if(!$P.length)return;var
pane=$P.attr("pane"),s=state[pane],CSS=s.cssSaved||{};if(!s.isSliding&&!s.isResizing)$P.css("zIndex",c.zIndex.pane_normal);$P.css(CSS);s.cssSaved=false;};function getBtn(selector,pane,action){var
$E=$(selector),err="Error Adding Button \n\nInvalid ";if(!$E.length)alert(err+"selector: "+selector);else if(c.borderPanes.indexOf(pane)==-1)alert(err+"pane: "+pane);else{var btn=options[pane].buttonClass+"-"+action;$E.addClass(btn+" "+btn+"-"+pane);return $E;}return false;};function addToggleBtn(selector,pane){var $E=getBtn(selector,pane,"toggle");if($E)$E.attr("title",state[pane].isClosed?"Open":"Close").click(function(evt){toggle(pane);evt.stopPropagation();});};function addOpenBtn(selector,pane){var $E=getBtn(selector,pane,"open");if($E)$E.attr("title","Open").click(function(evt){open(pane);evt.stopPropagation();});};function addCloseBtn(selector,pane){var $E=getBtn(selector,pane,"close");if($E)$E.attr("title","Close").click(function(evt){close(pane);evt.stopPropagation();});};function addPinBtn(selector,pane){var $E=getBtn(selector,pane,"pin");if($E){var s=state[pane];$E.click(function(evt){setPinState($(this),pane,(s.isSliding||s.isClosed));if(s.isSliding||s.isClosed)open(pane);else close(pane);evt.stopPropagation();});setPinState($E,pane,(!s.isClosed&&!s.isSliding));c[pane].pins.push(selector);}};function syncPinBtns(pane,doPin){$.each(c[pane].pins,function(i,selector){setPinState($(selector),pane,doPin);});};function setPinState($Pin,pane,doPin){var updown=$Pin.attr("pin");if(updown&&doPin==(updown=="down"))return;var
root=options[pane].buttonClass,class1=root+"-pin",class2=class1+"-"+pane,UP1=class1+"-up",UP2=class2+"-up",DN1=class1+"-down",DN2=class2+"-down";$Pin.attr("pin",doPin?"down":"up").attr("title",doPin?"Un-Pin":"Pin").removeClass(doPin?UP1:DN1).removeClass(doPin?UP2:DN2).addClass(doPin?DN1:UP1).addClass(doPin?DN2:UP2);};var
$Container=$(this).css({overflow:"hidden"}),$Ps={},$Cs={},$Rs={},$Ts={},c=config,cDims=state.container;create();return{options:options,state:state,panes:$Ps,toggle:toggle,open:open,close:close,hide:hide,show:show,resizeContent:sizeContent,sizePane:sizePane,resizeAll:resizeAll,addToggleBtn:addToggleBtn,addOpenBtn:addOpenBtn,addCloseBtn:addCloseBtn,addPinBtn:addPinBtn,allowOverflow:allowOverflow,resetOverflow:resetOverflow,cssWidth:cssW,cssHeight:cssH};}})(jQuery);
;(function($){
/**
 * jqGrid English Translation
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/ 
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = $.jgrid || {};
$.extend($.jgrid,{
	defaults : {
		recordtext: "View {0} - {1} of {2}",
		emptyrecords: "No records to view",
		loadtext: "Loading...",
		pgtext : "Page {0} of {1}"
	},
	search : {
		caption: "Search...",
		Find: "Find",
		Reset: "Reset",
		odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'],
		groupOps: [	{ op: "AND", text: "all" },	{ op: "OR",  text: "any" }	],
		matchText: " match",
		rulesText: " rules"
	},
	edit : {
		addCaption: "Add Record",
		editCaption: "Edit Record",
		bSubmit: "Submit",
		bCancel: "Cancel",
		bClose: "Close",
		saveData: "Data has been changed! Save changes?",
		bYes : "Yes",
		bNo : "No",
		bExit : "Cancel",
		msg: {
			required:"Field is required",
			number:"Please, enter valid number",
			minValue:"value must be greater than or equal to ",
			maxValue:"value must be less than or equal to",
			email: "is not a valid e-mail",
			integer: "Please, enter valid integer value",
			date: "Please, enter valid date value",
			url: "is not a valid URL. Prefix required ('http://' or 'https://')",
			nodefined : " is not defined!",
			novalue : " return value is required!",
			customarray : "Custom function should return array!",
			customfcheck : "Custom function should be present in case of custom checking!"
			
		}
	},
	view : {
		caption: "View Record",
		bClose: "Close"
	},
	del : {
		caption: "Delete",
		msg: "Delete selected record(s)?",
		bSubmit: "Delete",
		bCancel: "Cancel"
	},
	nav : {
		edittext: "",
		edittitle: "Edit selected row",
		addtext:"",
		addtitle: "Add new row",
		deltext: "",
		deltitle: "Delete selected row",
		searchtext: "",
		searchtitle: "Find records",
		refreshtext: "",
		refreshtitle: "Reload Grid",
		alertcap: "Warning",
		alerttext: "Please, select row",
		viewtext: "",
		viewtitle: "View selected row"
	},
	col : {
		caption: "Select columns",
		bSubmit: "Ok",
		bCancel: "Cancel"
	},
	errors : {
		errcap : "Error",
		nourl : "No url is set",
		norecords: "No records to process",
		model : "Length of colNames <> colModel!"
	},
	formatter : {
		integer : {thousandsSeparator: ",", defaultValue: '0'},
		number : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, defaultValue: '0.00'},
		currency : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
		date : {
			dayNames:   [
				"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
				"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
			],
			monthNames: [
				"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
				"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
			],
			AmPm : ["am","pm","AM","PM"],
			S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th';},
			srcformat: 'Y-m-d',
			newformat: 'n/j/Y',
			masks : {
				// see http://php.net/manual/en/function.date.php for PHP format used in jqGrid
				// and see http://docs.jquery.com/UI/Datepicker/formatDate
				// and https://github.com/jquery/globalize#dates for alternative formats used frequently
				// one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many
				// information about date, time, numbers and currency formats used in different countries
				// one should just convert the information in PHP format
				ISO8601Long:"Y-m-d H:i:s",
				ISO8601Short:"Y-m-d",
				// short date:
				//    n - Numeric representation of a month, without leading zeros
				//    j - Day of the month without leading zeros
				//    Y - A full numeric representation of a year, 4 digits
				// example: 3/1/2012 which means 1 March 2012
				ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy"
				// long date:
				//    l - A full textual representation of the day of the week
				//    F - A full textual representation of a month
				//    d - Day of the month, 2 digits with leading zeros
				//    Y - A full numeric representation of a year, 4 digits
				LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy"
				// long date with long time:
				//    l - A full textual representation of the day of the week
				//    F - A full textual representation of a month
				//    d - Day of the month, 2 digits with leading zeros
				//    Y - A full numeric representation of a year, 4 digits
				//    g - 12-hour format of an hour without leading zeros
				//    i - Minutes with leading zeros
				//    s - Seconds, with leading zeros
				//    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
				FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt"
				// month day:
				//    F - A full textual representation of a month
				//    d - Day of the month, 2 digits with leading zeros
				MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd"
				// short time (without seconds)
				//    g - 12-hour format of an hour without leading zeros
				//    i - Minutes with leading zeros
				//    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
				ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt"
				// long time (with seconds)
				//    g - 12-hour format of an hour without leading zeros
				//    i - Minutes with leading zeros
				//    s - Seconds, with leading zeros
				//    A - Uppercase Ante meridiem and Post meridiem (AM or PM)
				LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt"
				SortableDateTime: "Y-m-d\\TH:i:s",
				UniversalSortableDateTime: "Y-m-d H:i:sO",
				// month with year
				//    Y - A full numeric representation of a year, 4 digits
				//    F - A full textual representation of a month
				YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy"
			},
			reformatAfterEdit : false
		},
		baseLinkUrl: '',
		showAction: '',
		target: '',
		checkbox : {disabled:true},
		idName : 'id'
	}
});
})(jQuery);
/**
 * @license jqGrid  4.4.0-backstop  - jQuery Grid
 * Copyright (c) 2008, Tony Tomov, tony@trirand.com
 * WITH CHANGES MADE BY BACKSTOP TO MAKE IT WORK WITH THE JQUERY UPGRADE
 * Dual licensed under the MIT and GPL licenses
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
 * Date: 2012-06-14
 */
function tableToGrid(e,t){jQuery(e).each(function(){if(!this.grid){jQuery(this).width("99%");var e=jQuery(this).width(),i=jQuery("tr td:first-child input[type=checkbox]:first",jQuery(this)),r=jQuery("tr td:first-child input[type=radio]:first",jQuery(this)),a=i.length>0,o=!a&&r.length>0,s=a||o,n=[],d=[];jQuery("th",jQuery(this)).each(function(){0===n.length&&s?(n.push({name:"__selection__",index:"__selection__",width:0,hidden:!0}),d.push("__selection__")):(n.push({name:jQuery(this).attr("id")||jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(" ").join("_"),index:jQuery(this).attr("id")||jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(" ").join("_"),width:jQuery(this).width()||150}),d.push(jQuery(this).html()))});var l=[],p=[],c=[];jQuery("tbody > tr",jQuery(this)).each(function(){var e={},t=0;jQuery("td",jQuery(this)).each(function(){if(0===t&&s){var i=jQuery("input",jQuery(this)),r=i.attr("value");p.push(r||l.length),i.is(":checked")&&c.push(r),e[n[t].name]=i.attr("value")}else e[n[t].name]=jQuery(this).html();t++}),t>0&&l.push(e)}),jQuery(this).empty(),jQuery(this).addClass("scroll"),jQuery(this).jqGrid(jQuery.extend({datatype:"local",width:e,colNames:d,colModel:n,multiselect:a},t||{}));var u;for(u=0;u<l.length;u++){var h=null;p.length>0&&(h=p[u],h&&h.replace&&(h=encodeURIComponent(h).replace(/[.\-%]/g,"_"))),null===h&&(h=u+1),jQuery(this).jqGrid("addRowData",h,l[u])}for(u=0;u<c.length;u++)jQuery(this).jqGrid("setSelection",c[u])}})}!function($){"use strict";$.jgrid=$.jgrid||{},$.extend($.jgrid,{version:"4.4.0",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,"&"):e},htmlEncode:function(e){return e?String(e).replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):e},format:function(e){var t=$.makeArray(arguments).slice(1);return void 0===e&&(e=""),e.replace(/\{(\d+)\}/g,function(e,i){return t[i]})},getCellIndex:function(e){var t=$(e);return t.is("tr")?-1:(t=(t.is("td")||t.is("th")?t:t.closest("td,th"))[0],$.browser.msie?$.inArray(t,t.parentNode.cells):t.cellIndex)},stripHtml:function(e){e+="";var t=/<("[^"]*"|'[^']*'|[^'">])*>/gi;return e?(e=e.replace(t,""),e&&"&nbsp;"!==e&&"&#160;"!==e?e.replace(/\"/g,"'"):""):e},stripPref:function(e,t){var i=$.type(e);return("string"==i||"number"==i)&&(e=String(e),t=""!==e?String(t).replace(String(e),""):t),t},stringToDoc:function(e){var t;if("string"!=typeof e)return e;try{var i=new DOMParser;t=i.parseFromString(e,"text/xml")}catch(r){t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e)}return t&&t.documentElement&&"parsererror"!=t.documentElement.tagName?t:null},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="{}"),$.jgrid.useJSON===!0&&"object"==typeof JSON&&"function"==typeof JSON.parse?JSON.parse(js):eval("("+js+")")},parseDate:function(e,t){var i,r,a,o={m:1,d:1,y:1970,h:0,i:0,s:0,u:0},s=/[\\\/:_;.,\t\T\s-]/;if(t&&null!=t&&void 0!==t){t=$.trim(t),t=t.split(s),void 0!==$.jgrid.formatter.date.masks[e]&&(e=$.jgrid.formatter.date.masks[e]),e=e.split(s);var n=$.jgrid.formatter.date.monthNames,d=$.jgrid.formatter.date.AmPm,l=function(e,t){return 0===e?12===t&&(t=0):12!==t&&(t+=12),t};for(i=0,r=e.length;r>i;i++)"M"==e[i]&&(a=$.inArray(t[i],n),-1!==a&&12>a&&(t[i]=a+1,o.m=t[i])),"F"==e[i]&&(a=$.inArray(t[i],n),-1!==a&&a>11&&(t[i]=a+1-12,o.m=t[i])),"a"==e[i]&&(a=$.inArray(t[i],d),-1!==a&&2>a&&t[i]==d[a]&&(t[i]=a,o.h=l(t[i],o.h))),"A"==e[i]&&(a=$.inArray(t[i],d),-1!==a&&a>1&&t[i]==d[a]&&(t[i]=a-2,o.h=l(t[i],o.h))),void 0!==t[i]&&(o[e[i].toLowerCase()]=parseInt(t[i],10));o.m=parseInt(o.m,10)-1;var p=o.y;p>=70&&99>=p?o.y=1900+o.y:p>=0&&69>=p&&(o.y=2e3+o.y),void 0!==o.j&&(o.d=o.j),void 0!==o.n&&(o.m=parseInt(o.n,10)-1)}return new Date(o.y,o.m,o.d,o.h,o.i,o.s,o.u)},jqID:function(e){return String(e).replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},guid:1,uidPref:"jqg",randId:function(e){return(e?e:$.jgrid.uidPref)+$.jgrid.guid++},getAccessor:function(e,t){var i,r,a,o=[];if("function"==typeof t)return t(e);if(i=e[t],void 0===i)try{if("string"==typeof t&&(o=t.split(".")),a=o.length)for(i=e;i&&a--;)r=o.shift(),i=i[r]}catch(s){}return i},getXmlData:function(e,t,i){var r,a="string"==typeof t?t.match(/^(.*)\[(\w+)\]$/):null;return"function"==typeof t?t(e):a&&a[2]?a[1]?$(a[1],e).attr(a[2]):$(e).attr(a[2]):(r=$(t,e),i?r:r.length>0?$(r).text():void 0)},cellWidth:function(){var e=$("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),t=e.appendTo("body").find("td").width();return e.remove(),5!==t},ajaxOptions:{},from:function(source){var 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 d.length>0&&(_useProperties="object"!=typeof d[0]?!1:!0),this._hasData=function(){return null===_data?!1:0===_data.length?!1:!0},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(e){var t=[];return $.each(_data,function(i,r){t.push(e(r))}),t},this._append=function(e){var t;for(null===_query?_query="":_query+=""===_queuedOperator?" && ":_queuedOperator,t=0;_orDepth>t;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?_lastCommand(e):_useProperties?_lastCommand(_lastField,e):_lastCommand(e)},this._equals=function(e,t){return 0===self._compare(e,t,1)},this._compare=function(e,t,i){var r=Object.prototype.toString;return void 0===i&&(i=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]"===r.call(e)&&"[object Date]"===r.call(t)?t>e?-i:e>t?i:0:(_usecase||"number"==typeof e||"number"==typeof t||(e=String(e).toLowerCase(),t=String(t).toLowerCase()),t>e?-i:e>t?i:0)},this._performSort=function(){0!==_sorting.length&&(_data=self._doSort(_data,0))},this._doSort=function(e,t){var i=_sorting[t].by,r=_sorting[t].dir,a=_sorting[t].type,o=_sorting[t].datefmt;if(t==_sorting.length-1)return self._getOrder(e,i,r,a,o);t++;for(var s=self._getGroup(e,i,r,a,o),n=[],d=0;d<s.length;d++)for(var l=self._doSort(s[d].items,t),p=0;p<l.length;p++)n.push(l[p]);return n},this._getOrder=function(e,t,i,r,a){var o,s,n,d,l=[],p=[],c="a"==i?1:-1;void 0===r&&(r="text"),d="float"==r||"number"==r||"currency"==r||"numeric"==r?function(e){var t=parseFloat(String(e).replace(_stripNum,""));return isNaN(t)?0:t}:"int"==r||"integer"==r?function(e){return e?parseFloat(String(e).replace(_stripNum,"")):0}:"date"==r||"datetime"==r?function(e){return $.jgrid.parseDate(a,e).getTime()}:$.isFunction(r)?r:function(e){return e||(e=""),$.trim(String(e).toUpperCase())},$.each(e,function(e,i){s=""!==t?$.jgrid.getAccessor(i,t):i,void 0===s&&(s=""),s=d(s,i),p.push({vSort:s,index:e})}),p.sort(function(e,t){return e=e.vSort,t=t.vSort,self._compare(e,t,c)}),n=0;for(var u=e.length;u>n;)o=p[n].index,l.push(e[o]),n++;return l},this._getGroup=function(e,t,i,r,a){var o,s=[],n=null,d=null;return $.each(self._getOrder(e,t,i,r,a),function(e,i){o=$.jgrid.getAccessor(i,t),void 0===o&&(o=""),self._equals(d,o)||(d=o,null!=n&&s.push(n),n=self._group(t,o)),n.items.push(i)}),null!=n&&s.push(n),s},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(e){if(self._performSort(),!self._hasData())return[];if(self.execute(),$.isFunction(e)){var t=[];return $.each(_data,function(i,r){t.push(e(r))}),t}return _data},this.hasMatch=function(){return self._hasData()?(self.execute(),_data.length>0):!1},this.andNot=function(e,t,i){return _negate=!_negate,self.and(e,t,i)},this.orNot=function(e,t,i){return _negate=!_negate,self.or(e,t,i)},this.not=function(e,t,i){return self.andNot(e,t,i)},this.and=function(e,t,i){return _queuedOperator=" && ",void 0===e?self:self._repeatCommand(e,t,i)},this.or=function(e,t,i){return _queuedOperator=" || ",void 0===e?self:self._repeatCommand(e,t,i)},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,i,r,a){var o;o=_useProperties?"jQuery.jgrid.getAccessor(this,'"+t+"')":"this",void 0===i&&(i=null);var s=i,n=void 0===a.stype?"text":a.stype;if(null!=i)switch(n){case"int":case"integer":s=isNaN(Number(s))||""===s?"0":s,o="parseInt("+o+",10)",s="parseInt("+s+",10)";break;case"float":case"number":case"numeric":s=String(s).replace(_stripNum,""),s=isNaN(Number(s))||""===s?"0":s,o="parseFloat("+o+")",s="parseFloat("+s+")";break;case"date":case"datetime":s=String($.jgrid.parseDate(a.newfmt||"Y-m-d",s).getTime()),o='jQuery.jgrid.parseDate("'+a.srcfmt+'",'+o+").getTime()";break;default:o=self._getStr(o),s=self._getStr('"'+self._toStr(s)+'"')}return self._append(o+" "+r+" "+s),self._setCommand(e,t),self._resetNegate(),self},this.equals=function(e,t,i){return self._compareValues(self.equals,e,t,"==",i)},this.notEquals=function(e,t,i){return self._compareValues(self.equals,e,t,"!==",i)},this.isNull=function(e,t,i){return self._compareValues(self.equals,e,null,"===",i)},this.greater=function(e,t,i){return self._compareValues(self.greater,e,t,">",i)},this.less=function(e,t,i){return self._compareValues(self.less,e,t,"<",i)},this.greaterOrEquals=function(e,t,i){return self._compareValues(self.greaterOrEquals,e,t,">=",i)},this.lessOrEquals=function(e,t,i){return self._compareValues(self.lessOrEquals,e,t,"<=",i)},this.startsWith=function(e,t){var i=void 0===t||null===t?e:t,r=_trim?$.trim(i.toString()).length:i.toString().length;return _useProperties?self._append(self._getStr("jQuery.jgrid.getAccessor(this,'"+e+"')")+".substr(0,"+r+") == "+self._getStr('"'+self._toStr(t)+'"')):(r=_trim?$.trim(t.toString()).length: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 i=void 0===t||null===t?e:t,r=_trim?$.trim(i.toString()).length:i.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.groupBy=function(e,t,i,r){return self._hasData()?self._getGroup(_data,e,t,i,r):null},this.orderBy=function(e,t,i,r){return t=void 0===t||null===t?"a":$.trim(t.toString().toLowerCase()),(null===i||void 0===i)&&(i="text"),(null===r||void 0===r)&&(r="Y-m-d"),("desc"==t||"descending"==t)&&(t="d"),("asc"==t||"ascending"==t)&&(t="a"),_sorting.push({by:e,dir:t,type:i,datefmt:r}),self},self};return new QueryObject(source,null)},extend:function(e){$.extend($.fn.jqGrid,e),this.no_legacy_api||$.fn.extend(e)}}),$.fn.jqGrid=function(e){if("string"==typeof e){var t=$.jgrid.getAccessor($.fn.jqGrid,e);if(!t)throw"jqGrid - No such method: "+e;var i=$.makeArray(arguments).slice(1);return t.apply(this,i)}return this.each(function(){if(!this.grid){var t=$.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:[],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,loadComplete:null,gridComplete:null,loadError:null,loadBeforeSend:null,afterInsertRow:null,beforeRequest:null,beforeProcessing:null,onHeaderClick:null,viewrecords:!1,loadonce:!1,multiselect:!1,multikey:!1,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,multiboxonly:!1,deselectAfterSort:!0,scrollrows:!1,autowidth:!1,scrollOffset:18,cellLayout:5,subGridWidth:20,multiselectWidth:20,gridview:!1,rownumWidth:25,rownumbers:!1,pagerpos:"center",recordpos:"right",footerrow:!1,userDataOnFooter:!1,hoverrows:!0,altclass:"ui-priority-secondary",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:"ui-icon-circlesmall-plus",minusicon:"ui-icon-circlesmall-minus"},ignoreCase:!1,cmTemplate:{},idPrefix:""},$.jgrid.defaults,e||{}),i=this,r={headers:[],cols:[],footers:[],dragStart:function(e,r,a){this.resizing={idx:e,startX:r.clientX,sOL:a[0]},this.hDiv.style.cursor="col-resize",this.curGbox=$("#rs_m"+$.jgrid.jqID(t.id),"#gbox_"+$.jgrid.jqID(t.id)),this.curGbox.css({display:"block",left:a[0],top:a[1],height:a[2]}),$(i).triggerHandler("jqGridResizeStart",[r,e]),$.isFunction(t.resizeStart)&&t.resizeStart.call(this,r,e),document.onselectstart=function(){return!1}},dragMove:function(e){if(this.resizing){var i,r,a=e.clientX-this.resizing.startX,o=this.headers[this.resizing.idx],s="ltr"===t.direction?o.width+a:o.width-a;s>33&&(this.curGbox.css({left:this.resizing.sOL+a}),t.forceFit===!0?(i=this.headers[this.resizing.idx+t.nv],r="ltr"===t.direction?i.width-a:i.width+a,r>33&&(o.newWidth=s,i.newWidth=r)):(this.newWidth="ltr"===t.direction?t.tblwidth+a:t.tblwidth-a,o.newWidth=s))}},dragEnd:function(){if(this.hDiv.style.cursor="default",this.resizing){var e=this.resizing.idx,r=this.headers[e].newWidth||this.headers[e].width;r=parseInt(r,10),this.resizing=!1,$("#rs_m"+$.jgrid.jqID(t.id)).css("display","none"),t.colModel[e].width=r,this.headers[e].width=r,this.headers[e].el.style.width=r+"px",this.cols[e].style.width=r+"px",this.footers.length>0&&(this.footers[e].style.width=r+"px"),t.forceFit===!0?(r=this.headers[e+t.nv].newWidth||this.headers[e+t.nv].width,this.headers[e+t.nv].width=r,this.headers[e+t.nv].el.style.width=r+"px",this.cols[e+t.nv].style.width=r+"px",this.footers.length>0&&(this.footers[e+t.nv].style.width=r+"px"),t.colModel[e+t.nv].width=r):(t.tblwidth=this.newWidth||t.tblwidth,$("table:first",this.bDiv).css("width",t.tblwidth+"px"),$("table:first",this.hDiv).css("width",t.tblwidth+"px"),this.hDiv.scrollLeft=this.bDiv.scrollLeft,t.footerrow&&($("table:first",this.sDiv).css("width",t.tblwidth+"px"),this.sDiv.scrollLeft=this.bDiv.scrollLeft)),$(i).triggerHandler("jqGridResizeStop",[r,e]),$.isFunction(t.resizeStop)&&t.resizeStop.call(this,r,e)}this.curGbox=null,document.onselectstart=function(){return!0}},populateVisible:function(){r.timer&&clearTimeout(r.timer),r.timer=null;var e=$(r.bDiv).height();if(e){var i,a,o=$("table:first",r.bDiv);if(o[0].rows.length)try{i=o[0].rows[1],a=i?$(i).outerHeight()||r.prevRowHeight:r.prevRowHeight}catch(s){a=r.prevRowHeight}if(a){r.prevRowHeight=a;var n,d,l,p=t.rowNum,c=r.scrollTop=r.bDiv.scrollTop,u=Math.round(o.position().top)-c,h=u+o.height(),f=a*p;if(e>h&&0>=u&&(void 0===t.lastpage||parseInt((h+c+f-1)/f,10)<=t.lastpage)&&(d=parseInt((e-h+f-1)/f,10),h>=0||2>d||t.scroll===!0?(n=Math.round((h+c)/f)+1,u=-1):u=1),u>0&&(n=parseInt(c/f,10)+1,d=parseInt((c+e)/f,10)+2-n,l=!0),d){if(t.lastpage&&n>t.lastpage||1==t.lastpage||n===t.page&&n===t.lastpage)return;r.hDiv.loading?r.timer=setTimeout(r.populateVisible,t.scrollTimeout):(t.page=n,l&&(r.selectionPreserver(o[0]),r.emptyRows.call(o[0],!1,!1)),r.populate(d))}}}},scrollGrid:function(e){if(t.scroll){var i=r.bDiv.scrollTop;void 0===r.scrollTop&&(r.scrollTop=0),i!=r.scrollTop&&(r.scrollTop=i,r.timer&&clearTimeout(r.timer),r.timer=setTimeout(r.populateVisible,t.scrollTimeout))}r.hDiv.scrollLeft=r.bDiv.scrollLeft,t.footerrow&&(r.sDiv.scrollLeft=r.bDiv.scrollLeft),e&&e.stopPropagation()},selectionPreserver:function(e){var t=e.p,i=t.selrow,r=t.selarrrow?$.makeArray(t.selarrrow):null,a=e.grid.bDiv.scrollLeft,o=function(){var s;if(t.selrow=null,t.selarrrow=[],t.multiselect&&r&&r.length>0)for(s=0;s<r.length;s++)r[s]!=i&&$(e).jqGrid("setSelection",r[s],!1,null);i&&$(e).jqGrid("setSelection",i,!1,null),e.grid.bDiv.scrollLeft=a,$(e).unbind(".selectionPreserver",o)};$(e).bind("jqGridGridComplete.selectionPreserver",o)}};if("TABLE"!=this.tagName.toUpperCase())return void alert("Element is not a table");if(void 0!==document.documentMode&&document.documentMode<=5)return void alert("Grid can not be used in this ('quirks') mode!");$(this).empty().attr("tabindex","1"),this.p=t,this.p.useProp=!!$.fn.prop;var a,o;if(0===this.p.colNames.length)for(a=0;a<this.p.colModel.length;a++)this.p.colNames[a]=this.p.colModel[a].label||this.p.colModel[a].name;if(this.p.colNames.length!==this.p.colModel.length)return void alert($.jgrid.errors.model);var s,n=$("<div class='ui-jqgrid-view'></div>"),d=$.browser.msie?!0:!1;i.p.direction=$.trim(i.p.direction.toLowerCase()),-1==$.inArray(i.p.direction,["ltr","rtl"])&&(i.p.direction="ltr"),o=i.p.direction,$(n).insertBefore(this),$(this).appendTo(n).removeClass("scroll");var l=$("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");$(l).insertBefore(n).attr({id:"gbox_"+this.id,dir:o}),$(n).appendTo(l).attr("id","gview_"+this.id),s=d&&$.browser.version<=6?'<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>':"",$("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").append(s).insertBefore(n),$("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(n),$(this).attr({cellspacing:"0",cellpadding:"0",border:"0",role:"grid","aria-multiselectable":!!this.p.multiselect,"aria-labelledby":"gbox_"+this.id});var p=["shiftKey","altKey","ctrlKey"],c=function(e,t){return e=parseInt(e,10),isNaN(e)?t?t:0:e},u=function(e,t,a,o,s,n){var d,l=i.p.colModel[e],p=l.align,c='style="',u=l.classes,h=l.name,f=[];return p&&(c+="text-align:"+p+";"),l.hidden===!0&&(c+="display:none;"),0===t?c+="width: "+r.headers[e].width+"px;":l.cellattr&&$.isFunction(l.cellattr)&&(d=l.cellattr.call(i,s,a,o,l,n),d&&"string"==typeof d&&(d=d.replace(/style/i,"style").replace(/title/i,"title"),d.indexOf("title")>-1&&(l.title=!1),d.indexOf("class")>-1&&(u=void 0),f=d.split("style"),2===f.length?(f[1]=$.trim(f[1].replace("=","")),(0===f[1].indexOf("'")||0===f[1].indexOf('"'))&&(f[1]=f[1].substring(1)),c+=f[1].replace(/'/gi,'"')):c+='"')),f.length||(f[0]="",c+='"'),c+=(void 0!==u?' class="'+u+'"':"")+(l.title&&a?' title="'+$.jgrid.stripHtml(a)+'"':""),c+=' aria-describedby="'+i.p.id+"_"+h+'"',c+f[0]},h=function(e){return void 0===e||null===e||""===e?"&#160;":i.p.autoencode?$.jgrid.htmlEncode(e):e+""},f=function(e,t,r,a,o){var s,n=i.p.colModel[r];if("undefined"!=typeof n.formatter){var d={rowId:e,colModel:n,gid:i.p.id,pos:r};s=$.isFunction(n.formatter)?n.formatter.call(i,t,d,a,o):$.fmatter?$.fn.fmatter.call(i,n.formatter,t,d,a,o):h(t)}else s=h(t);return s},g=function(e,t,i,r,a){var o,s;return o=f(e,t,i,a,"add"),s=u(i,r,o,a,e,!0),'<td role="gridcell" '+s+">"+o+"</td>"},m=function(e,t,r){var a='<input role="checkbox" type="checkbox" id="jqg_'+i.p.id+"_"+e+'" class="cbox" name="jqg_'+i.p.id+"_"+e+'"/>',o=u(t,r,"",null,e,!0);return'<td role="gridcell" '+o+">"+a+"</td>"},v=function(e,t,i,r){var a=(parseInt(i,10)-1)*parseInt(r,10)+1+t,o=u(e,t,a,null,t,!0);return'<td role="gridcell" class="ui-state-default jqgrid-rownum" '+o+">"+a+"</td>"},j=function(e){var t,r,a=[],o=0;for(r=0;r<i.p.colModel.length;r++)t=i.p.colModel[r],"cb"!==t.name&&"subgrid"!==t.name&&"rn"!==t.name&&(a[o]="local"==e?t.name:"xml"==e||"xmlstring"===e?t.xmlmap||t.name:t.jsonmap||t.name,o++);return a},b=function(e){var t=i.p.remapColumns;return t&&t.length||(t=$.map(i.p.colModel,function(e,t){return t})),e&&(t=$.map(t,function(t){return e>t?null:t-e})),t},w=function(e,t){var i;this.p.deepempty?$(this.rows).slice(1).remove():(i=this.rows.length>0?this.rows[0]:null,$(this.firstChild).empty().append(i)),e&&this.p.scroll&&($(this.grid.bDiv.firstChild).css({height:"auto"}),$(this.grid.bDiv.firstChild.firstChild).css({height:0,display:"none"}),0!==this.grid.bDiv.scrollTop&&(this.grid.bDiv.scrollTop=0)),t===!0&&this.p.treeGrid&&(this.p.data=[],this.p._index={})},y=function(){var e,t,r,a=i.p.data.length,o=i.p.rownumbers===!0?1:0,s=i.p.multiselect===!0?1:0,n=i.p.subGrid===!0?1:0;for(e=i.p.keyIndex===!1||i.p.loadonce===!0?i.p.localReader.id:i.p.colModel[i.p.keyIndex+s+n+o].name,t=0;a>t;t++)r=$.jgrid.getAccessor(i.p.data[t],e),i.p._index[r]=t},q=function(e,t,r,a,o){var s,n="-1",d="",l=t?"display:none;":"",p="ui-widget-content jqgrow ui-row-"+i.p.direction+r,c=$.isFunction(i.p.rowattr)?i.p.rowattr.call(i,a,o):{};if(!$.isEmptyObject(c)){c.hasOwnProperty("id")&&(e=c.id,delete c.id),c.hasOwnProperty("tabindex")&&(n=c.tabindex,delete c.tabindex),c.hasOwnProperty("style")&&(l+=c.style,delete c.style),c.hasOwnProperty("class")&&(p+=" "+c["class"],delete c["class"]);try{delete c.role}catch(u){}for(s in c)c.hasOwnProperty(s)&&(d+=" "+s+"="+c[s])}return'<tr role="row" id="'+e+'" tabindex="'+n+'" class="'+p+'"'+(""===l?"":' style="'+l+'"')+d+">"},x=function(e,t,r,a,o){var s=new Date,n="local"!=i.p.datatype&&i.p.loadonce||"xmlstring"==i.p.datatype,d="_id_",l=i.p.xmlReader,p="local"==i.p.datatype?"local":"xml";if(n&&(i.p.data=[],i.p._index={},i.p.localReader.id=d),i.p.reccount=0,$.isXMLDoc(e)){-1!==i.p.treeANode||i.p.scroll?r=r>1?r:1:(w.call(i,!1,!0),r=1);var c,u,h,f,y,x,D,_,C,I=0,G=i.p.multiselect===!0?1:0,F=i.p.subGrid===!0?1:0,k=i.p.rownumbers===!0?1:0,S=[],R={},M=[],N=i.p.altRows===!0?" "+i.p.altclass:"";l.repeatitems||(S=j(p)),f=i.p.keyIndex===!1?$.isFunction(l.id)?l.id.call(i,e):l.id:i.p.keyIndex,S.length>0&&!isNaN(f)&&(i.p.remapColumns&&i.p.remapColumns.length&&(f=$.inArray(f,i.p.remapColumns)),f=S[f]),y=-1===(f+"").indexOf("[")?S.length?function(e,t){return $(f,e).text()||t}:function(e,t){return $(l.cell,e).eq(f).text()||t}:function(e,t){return e.getAttribute(f.replace(/[\[\]]/g,""))||t},i.p.userData={},i.p.page=$.jgrid.getXmlData(e,l.page)||0,i.p.lastpage=$.jgrid.getXmlData(e,l.total),void 0===i.p.lastpage&&(i.p.lastpage=1),i.p.records=$.jgrid.getXmlData(e,l.records)||0,$.isFunction(l.userdata)?i.p.userData=l.userdata.call(i,e)||{}:$.jgrid.getXmlData(e,l.userdata,!0).each(function(){i.p.userData[this.getAttribute("name")]=$(this).text()});var O=$.jgrid.getXmlData(e,l.root,!0);O=$.jgrid.getXmlData(O,l.row,!0),O||(O=[]);var E=O.length,A=0,T=[],P=parseInt(i.p.rowNum,10);if(E>0&&i.p.page<=0&&(i.p.page=1),O&&E){var z,H=i.p.scroll?$.jgrid.randId():1;o&&(P*=o+1);for(var L=$.isFunction(i.p.afterInsertRow),B=i.p.grouping&&i.p.groupingView.groupCollapse===!0;E>A;){D=O[A],_=y(D,H+A),_=i.p.idPrefix+_,z=0===r?0:r+1,C=(z+A)%2==1?N:"";var Q=M.length;if(M.push(""),k&&M.push(v(0,A,i.p.page,i.p.rowNum)),G&&M.push(m(_,k,A)),F&&M.push($(i).jqGrid("addSubGridCell",G+k,A+r)),l.repeatitems){x||(x=b(G+F+k));var V=$.jgrid.getXmlData(D,l.cell,!0);$.each(x,function(e){var t=V[this];return t?(h=t.textContent||t.text,R[i.p.colModel[e+G+F+k].name]=h,void M.push(g(_,h,e+G+F+k,A+r,D))):!1})}else for(c=0;c<S.length;c++)h=$.jgrid.getXmlData(D,S[c]),R[i.p.colModel[c+G+F+k].name]=h,M.push(g(_,h,c+G+F+k,A+r,D));if(M[Q]=q(_,B,C,R,D),M.push("</tr>"),i.p.grouping&&(T=$(i).jqGrid("groupingPrepare",M,T,R,A),M=[]),(n||i.p.treeGrid===!0)&&(R[d]=_,i.p.data.push(R),i.p._index[_]=i.p.data.length-1),i.p.gridview===!1&&($("tbody:first",t).append(M.join("")),$(i).triggerHandler("jqGridAfterInsertRow",[_,R,D]),L&&i.p.afterInsertRow.call(i,_,R,D),M=[]),R={},I++,A++,I==P)break}}if(i.p.gridview===!0&&(u=i.p.treeANode>-1?i.p.treeANode:0,i.p.grouping?($(i).jqGrid("groupingRender",T,i.p.colModel.length),T=null):i.p.treeGrid===!0&&u>0?$(i.rows[u]).after(M.join("")):$("tbody:first",t).append(M.join(""))),i.p.subGrid===!0)try{$(i).jqGrid("addSubGrid",G+k)}catch(W){}if(i.p.totaltime=new Date-s,I>0&&0===i.p.records&&(i.p.records=E),M=null,i.p.treeGrid===!0)try{$(i).jqGrid("setTreeNode",u+1,I+u+1)}catch(U){}if(i.p.treeGrid||i.p.scroll||(i.grid.bDiv.scrollTop=0),i.p.reccount=I,i.p.treeANode=-1,i.p.userDataOnFooter&&$(i).jqGrid("footerData","set",i.p.userData,!0),n&&(i.p.records=E,i.p.lastpage=Math.ceil(E/P)),a||i.updatepager(!1,!0),n)for(;E>I;){if(D=O[I],_=y(D,I+H),_=i.p.idPrefix+_,l.repeatitems){x||(x=b(G+F+k));var X=$.jgrid.getXmlData(D,l.cell,!0);$.each(x,function(e){var t=X[this];return t?(h=t.textContent||t.text,void(R[i.p.colModel[e+G+F+k].name]=h)):!1})}else for(c=0;c<S.length;c++)h=$.jgrid.getXmlData(D,S[c]),R[i.p.colModel[c+G+F+k].name]=h;R[d]=_,i.p.data.push(R),i.p._index[_]=i.p.data.length-1,R={},I++}}},D=function(e,t,r,a,o){var s=new Date;if(e){-1!==i.p.treeANode||i.p.scroll?r=r>1?r:1:(w.call(i,!1,!0),r=1);var n,d,l="_id_",p="local"!=i.p.datatype&&i.p.loadonce||"jsonstring"==i.p.datatype;p&&(i.p.data=[],i.p._index={},i.p.localReader.id=l),i.p.reccount=0,"local"==i.p.datatype?(n=i.p.localReader,d="local"):(n=i.p.jsonReader,d="json");var c,u,h,f,y,x,D,_,C,I,G,F,k=0,S=[],R=i.p.multiselect?1:0,M=i.p.subGrid?1:0,N=i.p.rownumbers===!0?1:0,O={},E=[],A=i.p.altRows===!0?" "+i.p.altclass:"";i.p.page=$.jgrid.getAccessor(e,n.page)||0,F=$.jgrid.getAccessor(e,n.total),i.p.lastpage=void 0===F?1:F,i.p.records=$.jgrid.getAccessor(e,n.records)||0,i.p.userData=$.jgrid.getAccessor(e,n.userdata)||{},n.repeatitems||(f=S=j(d)),_=i.p.keyIndex===!1?$.isFunction(n.id)?n.id.call(i,e):n.id:i.p.keyIndex,S.length>0&&!isNaN(_)&&(i.p.remapColumns&&i.p.remapColumns.length&&(_=$.inArray(_,i.p.remapColumns)),_=S[_]),D=$.jgrid.getAccessor(e,n.root),D||(D=[]),x=D.length,u=0,x>0&&i.p.page<=0&&(i.p.page=1);var T,P=parseInt(i.p.rowNum,10),z=i.p.scroll?$.jgrid.randId():1;o&&(P*=o+1);for(var H=$.isFunction(i.p.afterInsertRow),L=[],B=i.p.grouping&&i.p.groupingView.groupCollapse===!0;x>u;){if(y=D[u],I=$.jgrid.getAccessor(y,_),void 0===I&&(I=z+u,0===S.length&&n.cell)){var Q=$.jgrid.getAccessor(y,n.cell);I=void 0!==Q?Q[_]||I:I,Q=null}I=i.p.idPrefix+I,T=1===r?0:r,G=(T+u)%2==1?A:"";var V=E.length;for(E.push(""),N&&E.push(v(0,u,i.p.page,i.p.rowNum)),R&&E.push(m(I,N,u)),M&&E.push($(i).jqGrid("addSubGridCell",R+N,u+r)),n.repeatitems&&(n.cell&&(y=$.jgrid.getAccessor(y,n.cell)),f||(f=b(R+M+N))),h=0;h<f.length;h++)c=$.jgrid.getAccessor(y,f[h]),E.push(g(I,c,h+R+M+N,u+r,y)),O[i.p.colModel[h+R+M+N].name]=c;if(E[V]=q(I,B,G,O,y),E.push("</tr>"),i.p.grouping&&(L=$(i).jqGrid("groupingPrepare",E,L,O,u),E=[]),(p||i.p.treeGrid===!0)&&(O[l]=I,i.p.data.push(O),i.p._index[I]=i.p.data.length-1),i.p.gridview===!1&&($("#"+$.jgrid.jqID(i.p.id)+" tbody:first").append(E.join("")),$(i).triggerHandler("jqGridAfterInsertRow",[I,O,y]),H&&i.p.afterInsertRow.call(i,I,O,y),E=[]),O={},k++,u++,k==P)break}if(i.p.gridview===!0&&(C=i.p.treeANode>-1?i.p.treeANode:0,i.p.grouping?($(i).jqGrid("groupingRender",L,i.p.colModel.length),L=null):i.p.treeGrid===!0&&C>0?$(i.rows[C]).after(E.join("")):$("#"+$.jgrid.jqID(i.p.id)+" tbody:first").append(E.join(""))),i.p.subGrid===!0)try{$(i).jqGrid("addSubGrid",R+N)}catch(W){}if(i.p.totaltime=new Date-s,k>0&&0===i.p.records&&(i.p.records=x),E=null,i.p.treeGrid===!0)try{$(i).jqGrid("setTreeNode",C+1,k+C+1)}catch(U){}if(i.p.treeGrid||i.p.scroll||(i.grid.bDiv.scrollTop=0),i.p.reccount=k,i.p.treeANode=-1,i.p.userDataOnFooter&&$(i).jqGrid("footerData","set",i.p.userData,!0),p&&(i.p.records=x,i.p.lastpage=Math.ceil(x/P)),a||i.updatepager(!1,!0),p)for(;x>k&&D[k];){if(y=D[k],I=$.jgrid.getAccessor(y,_),void 0===I&&(I=z+k,0===S.length&&n.cell)){var X=$.jgrid.getAccessor(y,n.cell);I=X[_]||I,X=null}if(y){for(I=i.p.idPrefix+I,n.repeatitems&&(n.cell&&(y=$.jgrid.getAccessor(y,n.cell)),f||(f=b(R+M+N))),h=0;h<f.length;h++)c=$.jgrid.getAccessor(y,f[h]),O[i.p.colModel[h+R+M+N].name]=c;O[l]=I,i.p.data.push(O),i.p._index[I]=i.p.data.length-1,O={}}k++}}},_=function(){function e(t){var r,a,o,s,d,l=0;if(void 0!==t.groups){for(a=t.groups.length&&"OR"===t.groupOp.toString().toUpperCase(),a&&f.orBegin(),r=0;r<t.groups.length;r++){l>0&&a&&f.or();try{e(t.groups[r])}catch(p){alert(p)}l++}a&&f.orEnd()}if(void 0!==t.rules){if(l>0){var c=f.select();f=$.jgrid.from(c),i.p.ignoreCase&&(f=f.ignoreCase())}try{for(o=t.rules.length&&"OR"===t.groupOp.toString().toUpperCase(),o&&f.orBegin(),r=0;r<t.rules.length;r++)d=t.rules[r],s=t.groupOp.toString().toUpperCase(),h[d.op]&&d.field&&(l>0&&s&&"OR"===s&&(f=f.or()),f=h[d.op](f,s)(d.field,d.data,n[d.field])),l++;o&&f.orEnd()}catch(u){alert(u)}}}var t,r,a,o,s=!1,n={},d=[],l=[];if($.isArray(i.p.data)){var p,c,u=i.p.grouping?i.p.groupingView:!1;if($.each(i.p.colModel,function(){if(a=this.sorttype||"text","date"==a||"datetime"==a?(this.formatter&&"string"==typeof this.formatter&&"date"==this.formatter?(r=this.formatoptions&&this.formatoptions.srcformat?this.formatoptions.srcformat:$.jgrid.formatter.date.srcformat,o=this.formatoptions&&this.formatoptions.newformat?this.formatoptions.newformat:$.jgrid.formatter.date.newformat):r=o=this.datefmt||"Y-m-d",n[this.name]={stype:a,srcfmt:r,newfmt:o}):n[this.name]={stype:a,srcfmt:"",newfmt:""},i.p.grouping)for(c=0,p=u.groupField.length;p>c;c++)if(this.name==u.groupField[c]){var e=this.name;"undefined"!=typeof this.index&&(e=this.index),d[c]=n[e],l[c]=e}s||this.index!=i.p.sortname&&this.name!=i.p.sortname||(t=this.name,s=!0)}),i.p.treeGrid)return void $(i).jqGrid("SortTree",t,i.p.sortorder,n[t].stype,n[t].srcfmt);var h={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().contains:e.andNot().contains},bw:function(e){return e.startsWith},bn:function(e,t){return"OR"===t?e.orNot().startsWith:e.andNot().startsWith},en:function(e,t){return"OR"===t?e.orNot().endsWith:e.andNot().endsWith},ew:function(e){return e.endsWith},ni:function(e,t){return"OR"===t?e.orNot().equals:e.andNot().equals},"in":function(e){return e.equals},nu:function(e){return e.isNull},nn:function(e,t){return"OR"===t?e.orNot().isNull:e.andNot().isNull}},f=$.jgrid.from(i.p.data);if(i.p.ignoreCase&&(f=f.ignoreCase()),i.p.search===!0){var g=i.p.postData.filters;if(g)"string"==typeof g&&(g=$.jgrid.parse(g)),e(g);else try{f=h[i.p.postData.searchOper](f)(i.p.postData.searchField,i.p.postData.searchString,n[i.p.postData.searchField])}catch(m){}}if(i.p.grouping)for(c=0;p>c;c++)f.orderBy(l[c],u.groupOrder[c],d[c].stype,d[c].srcfmt);t&&i.p.sortorder&&s&&("DESC"==i.p.sortorder.toUpperCase()?f.orderBy(i.p.sortname,"d",n[t].stype,n[t].srcfmt):f.orderBy(i.p.sortname,"a",n[t].stype,n[t].srcfmt));
var v=f.select(),j=parseInt(i.p.rowNum,10),b=v.length,w=parseInt(i.p.page,10),y=Math.ceil(b/j),q={};return v=v.slice((w-1)*j,w*j),f=null,n=null,q[i.p.localReader.total]=y,q[i.p.localReader.page]=w,q[i.p.localReader.records]=b,q[i.p.localReader.root]=v,q[i.p.localReader.userdata]=i.p.userData,v=null,q}},C=function(e,t){var r,a,o,s,n,d,l,p,u="",h=i.p.pager?"_"+$.jgrid.jqID(i.p.pager.substr(1)):"",f=i.p.toppager?"_"+i.p.toppager.substr(1):"";if(o=parseInt(i.p.page,10)-1,0>o&&(o=0),o*=parseInt(i.p.rowNum,10),n=o+i.p.reccount,i.p.scroll){var g=$("tbody:first > tr:gt(0)",i.grid.bDiv);o=n-g.length,i.p.reccount=g.length;var m=g.outerHeight()||i.grid.prevRowHeight;if(m){var v=o*m,j=parseInt(i.p.records,10)*m;$(">div:first",i.grid.bDiv).css({height:j}).children("div:first").css({height:v,display:v?"":"none"})}i.grid.bDiv.scrollLeft=i.grid.hDiv.scrollLeft}u=i.p.pager?i.p.pager:"",u+=i.p.toppager?u?","+i.p.toppager:i.p.toppager:"",u&&(l=$.jgrid.formatter.integer||{},r=c(i.p.page),a=c(i.p.lastpage),$(".selbox",u)[this.p.useProp?"prop":"attr"]("disabled",!1),i.p.pginput===!0&&($(".ui-pg-input",u).val(i.p.page),p=i.p.toppager?"#sp_1"+h+",#sp_1"+f:"#sp_1"+h,$(p).html($.fmatter?$.fmatter.util.NumberFormat(i.p.lastpage,l):i.p.lastpage)),i.p.viewrecords&&(0===i.p.reccount?$(".ui-paging-info",u).html(i.p.emptyrecords):(s=o+1,d=i.p.records,$.fmatter&&(s=$.fmatter.util.NumberFormat(s,l),n=$.fmatter.util.NumberFormat(n,l),d=$.fmatter.util.NumberFormat(d,l)),$(".ui-paging-info",u).html($.jgrid.format(i.p.recordtext,s,n,d)))),i.p.pgbuttons===!0&&(0>=r&&(r=a=0),1==r||0===r?($("#first"+h+", #prev"+h).addClass("ui-state-disabled").removeClass("ui-state-hover"),i.p.toppager&&$("#first_t"+f+", #prev_t"+f).addClass("ui-state-disabled").removeClass("ui-state-hover")):($("#first"+h+", #prev"+h).removeClass("ui-state-disabled"),i.p.toppager&&$("#first_t"+f+", #prev_t"+f).removeClass("ui-state-disabled")),r==a||0===r?($("#next"+h+", #last"+h).addClass("ui-state-disabled").removeClass("ui-state-hover"),i.p.toppager&&$("#next_t"+f+", #last_t"+f).addClass("ui-state-disabled").removeClass("ui-state-hover")):($("#next"+h+", #last"+h).removeClass("ui-state-disabled"),i.p.toppager&&$("#next_t"+f+", #last_t"+f).removeClass("ui-state-disabled")))),e===!0&&i.p.rownumbers===!0&&$("td.jqgrid-rownum",i.rows).each(function(e){$(this).html(o+1+e)}),t&&i.p.jqgdnd&&$(i).jqGrid("gridDnD","updateDnD"),$(i).triggerHandler("jqGridGridComplete"),$.isFunction(i.p.gridComplete)&&i.p.gridComplete.call(i),$(i).triggerHandler("jqGridAfterGridComplete")},I=function(){if(i.grid.hDiv.loading=!0,!i.p.hiddengrid)switch(i.p.loadui){case"disable":break;case"enable":$("#load_"+$.jgrid.jqID(i.p.id)).show();break;case"block":$("#lui_"+$.jgrid.jqID(i.p.id)).show(),$("#load_"+$.jgrid.jqID(i.p.id)).show()}},G=function(){switch(i.grid.hDiv.loading=!1,i.p.loadui){case"disable":break;case"enable":$("#load_"+$.jgrid.jqID(i.p.id)).hide();break;case"block":$("#lui_"+$.jgrid.jqID(i.p.id)).hide(),$("#load_"+$.jgrid.jqID(i.p.id)).hide()}},F=function(e){if(!i.grid.hDiv.loading){var t,r,a=i.p.scroll&&e===!1,o={},s=i.p.prmNames;i.p.page<=0&&(i.p.page=1),null!=s.search&&(o[s.search]=i.p.search),null!=s.nd&&(o[s.nd]=(new Date).getTime()),null!=s.rows&&(o[s.rows]=i.p.rowNum),null!=s.page&&(o[s.page]=i.p.page),null!=s.sort&&(o[s.sort]=i.p.sortname),null!=s.order&&(o[s.order]=i.p.sortorder),null!=i.p.rowTotal&&null!=s.totalrows&&(o[s.totalrows]=i.p.rowTotal);var n=$.isFunction(i.p.loadComplete),d=n?i.p.loadComplete:null,l=0;if(e=e||1,e>1?null!=s.npage?(o[s.npage]=e,l=e-1,e=1):d=function(t){i.p.page++,i.grid.hDiv.loading=!1,n&&i.p.loadComplete.call(i,t),F(e-1)}:null!=s.npage&&delete i.p.postData[s.npage],i.p.grouping){$(i).jqGrid("groupingSetup");var p,c=i.p.groupingView,u="";for(p=0;p<c.groupField.length;p++)u+=c.groupField[p]+" "+c.groupOrder[p]+", ";o[s.sort]=u+o[s.sort]}$.extend(i.p.postData,o);var h=i.p.scroll?i.rows.length-1:1,f=$(i).triggerHandler("jqGridBeforeRequest");if(f===!1||"stop"===f)return;if($.isFunction(i.p.datatype))return void i.p.datatype.call(i,i.p.postData,"load_"+i.p.id);if($.isFunction(i.p.beforeRequest)&&(f=i.p.beforeRequest.call(i),void 0===f&&(f=!0),f===!1))return;switch(t=i.p.datatype.toLowerCase()){case"json":case"jsonp":case"xml":case"script":$.ajax($.extend({url:i.p.url,type:i.p.mtype,dataType:t,data:$.isFunction(i.p.serializeGridData)?i.p.serializeGridData.call(i,i.p.postData):i.p.postData,success:function(r,o,s){return $.isFunction(i.p.beforeProcessing)&&i.p.beforeProcessing.call(i,r,o,s)===!1?void G():("xml"===t?x(r,i.grid.bDiv,h,e>1,l):D(r,i.grid.bDiv,h,e>1,l),$(i).triggerHandler("jqGridLoadComplete",[r]),d&&d.call(i,r),$(i).triggerHandler("jqGridAfterLoadComplete",[r]),a&&i.grid.populateVisible(),(i.p.loadonce||i.p.treeGrid)&&(i.p.datatype="local"),r=null,void(1===e&&G()))},error:function(t,r,a){$.isFunction(i.p.loadError)&&i.p.loadError.call(i,t,r,a),1===e&&G(),t=null},beforeSend:function(e,t){var r=!0;return $.isFunction(i.p.loadBeforeSend)&&(r=i.p.loadBeforeSend.call(i,e,t)),void 0===r&&(r=!0),r===!1?!1:void I()}},$.jgrid.ajaxOptions,i.p.ajaxGridOptions));break;case"xmlstring":I(),r=$.jgrid.stringToDoc(i.p.datastr),x(r,i.grid.bDiv),$(i).triggerHandler("jqGridLoadComplete",[r]),n&&i.p.loadComplete.call(i,r),$(i).triggerHandler("jqGridAfterLoadComplete",[r]),i.p.datatype="local",i.p.datastr=null,G();break;case"jsonstring":I(),r="string"==typeof i.p.datastr?$.jgrid.parse(i.p.datastr):i.p.datastr,D(r,i.grid.bDiv),$(i).triggerHandler("jqGridLoadComplete",[r]),n&&i.p.loadComplete.call(i,r),$(i).triggerHandler("jqGridAfterLoadComplete",[r]),i.p.datatype="local",i.p.datastr=null,G();break;case"local":case"clientside":I(),i.p.datatype="local";var g=_();D(g,i.grid.bDiv,h,e>1,l),$(i).triggerHandler("jqGridLoadComplete",[g]),d&&d.call(i,g),$(i).triggerHandler("jqGridAfterLoadComplete",[g]),a&&i.grid.populateVisible(),G()}}},k=function(e){$("#cb_"+$.jgrid.jqID(i.p.id),i.grid.hDiv)[i.p.useProp?"prop":"attr"]("checked",e);var t=i.p.frozenColumns?i.p.id+"_frozen":"";t&&$("#cb_"+$.jgrid.jqID(i.p.id),i.grid.fhDiv)[i.p.useProp?"prop":"attr"]("checked",e)},S=function(e,t){var r,a,s,n,d,l,p,u="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",h="",f="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",g="",m=function(e){var t;return $.isFunction(i.p.onPaging)&&(t=i.p.onPaging.call(i,e)),i.p.selrow=null,i.p.multiselect&&(i.p.selarrrow=[],k(!1)),i.p.savedRow=[],"stop"==t?!1:!0};if(e=e.substr(1),t+="_"+e,r="pg_"+e,a=e+"_left",s=e+"_center",n=e+"_right",$("#"+$.jgrid.jqID(e)).append("<div id='"+r+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+a+"' align='left'></td><td id='"+s+"' align='center' style='white-space:pre;'></td><td id='"+n+"' align='right'></td></tr></tbody></table></div>").attr("dir","ltr"),i.p.rowList.length>0){for(g="<td dir='"+o+"'>",g+="<select class='ui-pg-selbox' role='listbox'>",p=0;p<i.p.rowList.length;p++)g+='<option role="option" value="'+i.p.rowList[p]+'"'+(i.p.rowNum==i.p.rowList[p]?' selected="selected"':"")+">"+i.p.rowList[p]+"</option>";g+="</select></td>"}if("rtl"==o&&(f+=g),i.p.pginput===!0&&(h="<td dir='"+o+"'>"+$.jgrid.format(i.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>"),i.p.pgbuttons===!0){var v=["first"+t,"prev"+t,"next"+t,"last"+t];"rtl"==o&&v.reverse(),f+="<td id='"+v[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>",f+="<td id='"+v[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>",f+=""!==h?u+h+u:"",f+="<td id='"+v[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>",f+="<td id='"+v[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>"}else""!==h&&(f+=h);"ltr"==o&&(f+=g),f+="</tr></tbody></table>",i.p.viewrecords===!0&&$("td#"+e+"_"+i.p.recordpos,"#"+r).append("<div dir='"+o+"' style='text-align:"+i.p.recordpos+"' class='ui-paging-info'></div>"),$("td#"+e+"_"+i.p.pagerpos,"#"+r).append(f),l=$(".ui-jqgrid").css("font-size")||"11px",$(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+l+";visibility:hidden;' ></div>"),d=$(f).clone().appendTo("#testpg").width(),$("#testpg").remove(),d>0&&(""!==h&&(d+=50),$("td#"+e+"_"+i.p.pagerpos,"#"+r).width(d)),i.p._nvtd=[],i.p._nvtd[0]=d?Math.floor((i.p.width-d)/2):Math.floor(i.p.width/3),i.p._nvtd[1]=0,f=null,$(".ui-pg-selbox","#"+r).bind("change",function(){return i.p.page=Math.round(i.p.rowNum*(i.p.page-1)/this.value-.5)+1,i.p.rowNum=this.value,i.p.pager&&$(".ui-pg-selbox",i.p.pager).val(this.value),i.p.toppager&&$(".ui-pg-selbox",i.p.toppager).val(this.value),m("records")?(F(),!1):!1}),i.p.pgbuttons===!0&&($(".ui-pg-button","#"+r).hover(function(){$(this).hasClass("ui-state-disabled")?this.style.cursor="default":($(this).addClass("ui-state-hover"),this.style.cursor="pointer")},function(){$(this).hasClass("ui-state-disabled")||($(this).removeClass("ui-state-hover"),this.style.cursor="default")}),$("#first"+$.jgrid.jqID(t)+", #prev"+$.jgrid.jqID(t)+", #next"+$.jgrid.jqID(t)+", #last"+$.jgrid.jqID(t)).click(function(){var e=c(i.p.page,1),r=c(i.p.lastpage,1),a=!1,o=!0,s=!0,n=!0,d=!0;if(0===r||1===r?(o=!1,s=!1,n=!1,d=!1):r>1&&e>=1?1===e?(o=!1,s=!1):e===r&&(n=!1,d=!1):r>1&&0===e&&(n=!1,d=!1,e=r-1),this.id==="first"+t&&o&&(i.p.page=1,a=!0),this.id==="prev"+t&&s&&(i.p.page=e-1,a=!0),this.id==="next"+t&&n&&(i.p.page=e+1,a=!0),this.id==="last"+t&&d&&(i.p.page=r,a=!0),a){if(!m(this.id))return!1;F()}return!1})),i.p.pginput===!0&&$("input.ui-pg-input","#"+r).keypress(function(e){var t=e.charCode?e.charCode:e.keyCode?e.keyCode:0;return 13==t?(i.p.page=$(this).val()>0?$(this).val():i.p.page,m("user")?(F(),!1):!1):this})},R=function(e,t,r,a){if(i.p.colModel[t].sortable){var o;if(!(i.p.savedRow.length>0)){if(r||(i.p.lastsort==t?"asc"==i.p.sortorder?i.p.sortorder="desc":"desc"==i.p.sortorder&&(i.p.sortorder="asc"):i.p.sortorder=i.p.colModel[t].firstsortorder||"asc",i.p.page=1),a){if(i.p.lastsort==t&&i.p.sortorder==a&&!r)return;i.p.sortorder=a}var s=i.grid.headers[i.p.lastsort].el,n=i.grid.headers[t].el;if($("span.ui-grid-ico-sort",s).addClass("ui-state-disabled"),$(s).attr("aria-selected","false"),$("span.ui-icon-"+i.p.sortorder,n).removeClass("ui-state-disabled"),$(n).attr("aria-selected","true"),i.p.viewsortcols[0]||i.p.lastsort!=t&&($("span.s-ico",s).hide(),$("span.s-ico",n).show()),e=e.substring(5+i.p.id.length+1),i.p.sortname=i.p.colModel[t].index||e,o=i.p.sortorder,"stop"===$(i).triggerHandler("jqGridSortCol",[e,t,o]))return void(i.p.lastsort=t);if($.isFunction(i.p.onSortCol)&&"stop"==i.p.onSortCol.call(i,e,t,o))return void(i.p.lastsort=t);if("local"==i.p.datatype?i.p.deselectAfterSort&&$(i).jqGrid("resetSelection"):(i.p.selrow=null,i.p.multiselect&&k(!1),i.p.selarrrow=[],i.p.savedRow=[]),i.p.scroll){var d=i.grid.bDiv.scrollLeft;w.call(i,!0,!1),i.grid.hDiv.scrollLeft=d}i.p.subGrid&&"local"==i.p.datatype&&$("td.sgexpanded","#"+$.jgrid.jqID(i.p.id)).each(function(){$(this).trigger("click")}),F(),i.p.lastsort=t,i.p.sortname!=e&&t&&(i.p.lastsort=t)}}},M=function(){var e,t,a,o,s=0,n=$.jgrid.cellWidth()?0:c(i.p.cellLayout,0),d=0,l=c(i.p.scrollOffset,0),p=!1,u=0,h=0;$.each(i.p.colModel,function(){"undefined"==typeof this.hidden&&(this.hidden=!1),this.widthOrg=t=c(this.width,0),this.hidden===!1&&(s+=t+n,this.fixed?u+=t+n:d++,h++)}),isNaN(i.p.width)&&(i.p.width=s+(i.p.shrinkToFit!==!1||isNaN(i.p.height)?0:l)),r.width=i.p.width,i.p.tblwidth=s,i.p.shrinkToFit===!1&&i.p.forceFit===!0&&(i.p.forceFit=!1),i.p.shrinkToFit===!0&&d>0&&(a=r.width-n*d-u,isNaN(i.p.height)||(a-=l,p=!0),s=0,$.each(i.p.colModel,function(r){this.hidden!==!1||this.fixed||(t=Math.round(a*this.width/(i.p.tblwidth-n*d-u)),this.width=t,s+=t,e=r)}),o=0,p?r.width-u-(s+n*d)!==l&&(o=r.width-u-(s+n*d)-l):p||1===Math.abs(r.width-u-(s+n*d))||(o=r.width-u-(s+n*d)),i.p.colModel[e].width+=o,i.p.tblwidth=s+o+n*d+u,i.p.tblwidth>i.p.width&&(i.p.colModel[e].width-=i.p.tblwidth-parseInt(i.p.width,10),i.p.tblwidth=i.p.width))},N=function(e){var t,r=e,a=e;for(t=e+1;t<i.p.colModel.length;t++)if(i.p.colModel[t].hidden!==!0){a=t;break}return a-r},O=function(e){var t,r={},a=$.jgrid.cellWidth()?0:i.p.cellLayout;for(r[0]=r[1]=r[2]=0,t=0;e>=t;t++)i.p.colModel[t].hidden===!1&&(r[0]+=i.p.colModel[t].width+a);return"rtl"==i.p.direction&&(r[0]=i.p.width-r[0]),r[0]=r[0]-i.grid.bDiv.scrollLeft,$(i.grid.cDiv).is(":visible")&&(r[1]+=$(i.grid.cDiv).height()+parseInt($(i.grid.cDiv).css("padding-top"),10)+parseInt($(i.grid.cDiv).css("padding-bottom"),10)),i.p.toolbar[0]!==!0||"top"!=i.p.toolbar[1]&&"both"!=i.p.toolbar[1]||(r[1]+=$(i.grid.uDiv).height()+parseInt($(i.grid.uDiv).css("border-top-width"),10)+parseInt($(i.grid.uDiv).css("border-bottom-width"),10)),i.p.toppager&&(r[1]+=$(i.grid.topDiv).height()+parseInt($(i.grid.topDiv).css("border-bottom-width"),10)),r[2]+=$(i.grid.bDiv).height()+$(i.grid.hDiv).height(),r},E=function(e){var t,r=i.grid.headers,a=$.jgrid.getCellIndex(e);for(t=0;t<r.length;t++)if(e===r[t].el){a=t;break}return a};for(this.p.id=this.id,-1==$.inArray(i.p.multikey,p)&&(i.p.multikey=!1),i.p.keyIndex=!1,a=0;a<i.p.colModel.length;a++)i.p.colModel[a]=$.extend(!0,{},i.p.cmTemplate,i.p.colModel[a].template||{},i.p.colModel[a]),i.p.keyIndex===!1&&i.p.colModel[a].key===!0&&(i.p.keyIndex=a);if(i.p.sortorder=i.p.sortorder.toLowerCase(),i.p.grouping===!0&&(i.p.scroll=!1,i.p.rownumbers=!1,i.p.treeGrid=!1,i.p.gridview=!0),this.p.treeGrid===!0){try{$(this).jqGrid("setTreeGrid")}catch(A){}"local"!=i.p.datatype&&(i.p.localReader={id:"_id_"})}if(this.p.subGrid)try{$(i).jqGrid("setSubGrid")}catch(T){}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.cellWidth()?i.p.multiselectWidth+i.p.cellLayout:i.p.multiselectWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0})),this.p.rownumbers&&(this.p.colNames.unshift(""),this.p.colModel.unshift({name:"rn",width:i.p.rownumWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0})),i.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"}},i.p.xmlReader),i.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"}},i.p.jsonReader),i.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"}},i.p.localReader),i.p.scroll&&(i.p.pgbuttons=!1,i.p.pginput=!1,i.p.rowList=[]),i.p.data.length&&y();var P,z,H,L,B,Q,V,W,U,X="<thead><tr class='ui-jqgrid-labels' role='rowheader'>",Y="",J="";if(i.p.shrinkToFit===!0&&i.p.forceFit===!0)for(a=i.p.colModel.length-1;a>=0;a--)if(!i.p.colModel[a].hidden){i.p.colModel[a].resizable=!1;break}for("horizontal"==i.p.viewsortcols[1]&&(Y=" ui-i-asc",J=" ui-i-desc"),P=d?"class='ui-th-div-ie'":"",U="<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+Y+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+o+"'></span>",U+="<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+J+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+o+"'></span></span>",a=0;a<this.p.colNames.length;a++){var K=i.p.headertitles?' title="'+$.jgrid.stripHtml(i.p.colNames[a])+'"':"";X+="<th id='"+i.p.id+"_"+i.p.colModel[a].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+o+"'"+K+">",z=i.p.colModel[a].index||i.p.colModel[a].name,X+="<div id='jqgh_"+i.p.id+"_"+i.p.colModel[a].name+"' "+P+">"+i.p.colNames[a],i.p.colModel[a].width?i.p.colModel[a].width=parseInt(i.p.colModel[a].width,10):i.p.colModel[a].width=150,"boolean"!=typeof i.p.colModel[a].title&&(i.p.colModel[a].title=!0),z==i.p.sortname&&(i.p.lastsort=a),X+=U+"</div></th>"}if(X+="</tr></thead>",U=null,$(this).append(X),$("thead tr:first th",this).hover(function(){$(this).addClass("ui-state-hover")},function(){$(this).removeClass("ui-state-hover")}),this.p.multiselect){var Z,ee=[];$("#cb_"+$.jgrid.jqID(i.p.id),this).bind("click",function(){i.p.selarrrow=[];var e=i.p.frozenColumns===!0?i.p.id+"_frozen":"";this.checked?($(i.rows).each(function(t){t>0&&($(this).hasClass("ui-subgrid")||$(this).hasClass("jqgroup")||$(this).hasClass("ui-state-disabled")||($("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(this.id))[i.p.useProp?"prop":"attr"]("checked",!0),$(this).addClass("ui-state-highlight").attr("aria-selected","true"),i.p.selarrrow.push(this.id),i.p.selrow=this.id,e&&($("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(this.id),i.grid.fbDiv)[i.p.useProp?"prop":"attr"]("checked",!0),$("#"+$.jgrid.jqID(this.id),i.grid.fbDiv).addClass("ui-state-highlight"))))}),Z=!0,ee=[]):($(i.rows).each(function(t){t>0&&($(this).hasClass("ui-subgrid")||$(this).hasClass("ui-state-disabled")||($("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(this.id))[i.p.useProp?"prop":"attr"]("checked",!1),$(this).removeClass("ui-state-highlight").attr("aria-selected","false"),ee.push(this.id),e&&($("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(this.id),i.grid.fbDiv)[i.p.useProp?"prop":"attr"]("checked",!1),$("#"+$.jgrid.jqID(this.id),i.grid.fbDiv).removeClass("ui-state-highlight"))))}),i.p.selrow=null,Z=!1),$(i).triggerHandler("jqGridSelectAll",[Z?i.p.selarrrow:ee,Z]),$.isFunction(i.p.onSelectAll)&&i.p.onSelectAll.call(i,Z?i.p.selarrrow:ee,Z)})}if(i.p.autowidth===!0){var te=$(l).innerWidth();i.p.width=te>0?te:"nw"}M(),$(l).css("width",r.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+i.p.id+"'>&#160;</div>"),$(n).css("width",r.width+"px"),X=$("thead:first",i).get(0);var ie="";i.p.footerrow&&(ie+="<table role='grid' style='width:"+i.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+o+"'>");var re=$("tr:first",X),ae="<tr class='jqgfirstrow' role='row' style='height:auto'>";if(i.p.disableClick=!1,$("th",re).each(function(e){H=i.p.colModel[e].width,"undefined"==typeof i.p.colModel[e].resizable&&(i.p.colModel[e].resizable=!0),i.p.colModel[e].resizable?(L=document.createElement("span"),$(L).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-"+o),$.browser.opera||$(L).css("cursor","col-resize"),$(this).addClass(i.p.resizeclass)):L="",$(this).css("width",H+"px").prepend(L);var t="";i.p.colModel[e].hidden&&($(this).css("display","none"),t="display:none;"),ae+="<td role='gridcell' style='height:0px;width:"+H+"px;"+t+"'></td>",r.headers[e]={width:H,el:this},B=i.p.colModel[e].sortable,"boolean"!=typeof B&&(i.p.colModel[e].sortable=!0,B=!0);var a=i.p.colModel[e].name;"cb"!=a&&"subgrid"!=a&&"rn"!=a&&i.p.viewsortcols[2]&&$(">div",this).addClass("ui-jqgrid-sortable"),B&&(i.p.viewsortcols[0]?($("div span.s-ico",this).show(),e==i.p.lastsort&&$("div span.ui-icon-"+i.p.sortorder,this).removeClass("ui-state-disabled")):e==i.p.lastsort&&($("div span.s-ico",this).show(),$("div span.ui-icon-"+i.p.sortorder,this).removeClass("ui-state-disabled"))),i.p.footerrow&&(ie+="<td role='gridcell' "+u(e,0,"",null,"",!1)+">&#160;</td>")}).mousedown(function(e){if(1==$(e.target).closest("th>span.ui-jqgrid-resize").length){var t=E(this);return i.p.forceFit===!0&&(i.p.nv=N(t)),r.dragStart(t,e,O(t)),!1}}).click(function(e){if(i.p.disableClick)return i.p.disableClick=!1,!1;var t,r,a="th>div.ui-jqgrid-sortable";i.p.viewsortcols[2]||(a="th>div>span>span.ui-grid-ico-sort");var o=$(e.target).closest(a);if(1==o.length){var s=E(this);return i.p.viewsortcols[2]||(t=!0,r=o.attr("sort")),R($("div",this)[0].id,s,t,r),!1}}),i.p.sortable&&$.fn.sortable)try{$(i).jqGrid("sortableColumns",re)}catch(oe){}i.p.footerrow&&(ie+="</tr></tbody></table>"),ae+="</tr>",W=document.createElement("tbody"),this.appendChild(W),$(this).addClass("ui-jqgrid-btable").append(ae),ae=null;var se=$("<table class='ui-jqgrid-htable' style='width:"+i.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(X),ne=i.p.caption&&i.p.hiddengrid===!0?!0:!1,de=$("<div class='ui-jqgrid-hbox"+("rtl"==o?"-rtl":"")+"'></div>");X=null,r.hDiv=document.createElement("div"),$(r.hDiv).css({width:r.width+"px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(de),$(de).append(se),se=null,ne&&$(r.hDiv).hide(),i.p.pager&&("string"==typeof i.p.pager?"#"!=i.p.pager.substr(0,1)&&(i.p.pager="#"+i.p.pager):i.p.pager="#"+$(i.p.pager).attr("id"),$(i.p.pager).css({width:r.width+"px"}).appendTo(l).addClass("ui-state-default ui-jqgrid-pager ui-corner-bottom"),ne&&$(i.p.pager).hide(),S(i.p.pager,"")),i.p.cellEdit===!1&&i.p.hoverrows===!0&&$(i).bind("mouseover",function(e){V=$(e.target).closest("tr.jqgrow"),"ui-subgrid"!==$(V).attr("class")&&$(V).addClass("ui-state-hover")}).bind("mouseout",function(e){V=$(e.target).closest("tr.jqgrow"),$(V).removeClass("ui-state-hover")});var le,pe,ce;$(i).before(r.hDiv).click(function(e){if(Q=e.target,V=$(Q,i.rows).closest("tr.jqgrow"),0===$(V).length||V[0].className.indexOf("ui-state-disabled")>-1||($(Q,i).closest("table.ui-jqgrid-btable").attr("id")||"").replace("_frozen","")!==i.id)return this;var t=$(Q).hasClass("cbox"),r=$(i).triggerHandler("jqGridBeforeSelectRow",[V[0].id,e]);if(r=r===!1||"stop"===r?!1:!0,r&&$.isFunction(i.p.beforeSelectRow)&&(r=i.p.beforeSelectRow.call(i,V[0].id,e)),"A"!=Q.tagName&&("INPUT"!=Q.tagName&&"TEXTAREA"!=Q.tagName&&"OPTION"!=Q.tagName&&"SELECT"!=Q.tagName||t)&&r===!0)if(le=V[0].id,pe=$.jgrid.getCellIndex(Q),ce=$(Q).closest("td,th").html(),$(i).triggerHandler("jqGridCellSelect",[le,pe,ce,e]),$.isFunction(i.p.onCellSelect)&&i.p.onCellSelect.call(i,le,pe,ce,e),i.p.cellEdit===!0)if(i.p.multiselect&&t)$(i).jqGrid("setSelection",le,!0,e);else{le=V[0].rowIndex;try{$(i).jqGrid("editCell",le,pe,!0)}catch(a){}}else if(i.p.multikey)e[i.p.multikey]?$(i).jqGrid("setSelection",le,!0,e):i.p.multiselect&&t&&(t=$("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+le).is(":checked"),$("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+le)[i.p.useProp?"prop":"attr"]("checked",t));else if(i.p.multiselect&&i.p.multiboxonly)if(t)$(i).jqGrid("setSelection",le,!0,e);else{var o=i.p.frozenColumns?i.p.id+"_frozen":"";$(i.p.selarrrow).each(function(e,t){var r=i.rows.namedItem(t);$(r).removeClass("ui-state-highlight"),$("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(t))[i.p.useProp?"prop":"attr"]("checked",!1),o&&($("#"+$.jgrid.jqID(t),"#"+$.jgrid.jqID(o)).removeClass("ui-state-highlight"),$("#jqg_"+$.jgrid.jqID(i.p.id)+"_"+$.jgrid.jqID(t),"#"+$.jgrid.jqID(o))[i.p.useProp?"prop":"attr"]("checked",!1))}),i.p.selarrrow=[],$(i).jqGrid("setSelection",le,!0,e)}else $(i).jqGrid("setSelection",le,!0,e)}).bind("reloadGrid",function(e,t){if(i.p.treeGrid===!0&&(i.p.datatype=i.p.treedatatype),t&&t.current&&i.grid.selectionPreserver(i),"local"==i.p.datatype?($(i).jqGrid("resetSelection"),i.p.data.length&&y()):i.p.treeGrid||(i.p.selrow=null,i.p.multiselect&&(i.p.selarrrow=[],k(!1)),i.p.savedRow=[]),i.p.scroll&&w.call(i,!0,!1),t&&t.page){var r=t.page;r>i.p.lastpage&&(r=i.p.lastpage),1>r&&(r=1),i.p.page=r,i.grid.prevRowHeight?i.grid.bDiv.scrollTop=(r-1)*i.grid.prevRowHeight*i.p.rowNum:i.grid.bDiv.scrollTop=0}return i.grid.prevRowHeight&&i.p.scroll?(delete i.p.lastpage,i.grid.populateVisible()):i.grid.populate(),i.p._inlinenav===!0&&$(i).jqGrid("showAddEditButtons"),!1}).dblclick(function(e){Q=e.target,V=$(Q,i.rows).closest("tr.jqgrow"),0!==$(V).length&&(le=V[0].rowIndex,pe=$.jgrid.getCellIndex(Q),$(i).triggerHandler("jqGridDblClickRow",[$(V).attr("id"),le,pe,e]),$.isFunction(this.p.ondblClickRow)&&i.p.ondblClickRow.call(i,$(V).attr("id"),le,pe,e))}).bind("contextmenu",function(e){Q=e.target,V=$(Q,i.rows).closest("tr.jqgrow"),0!==$(V).length&&(i.p.multiselect||$(i).jqGrid("setSelection",V[0].id,!0,e),le=V[0].rowIndex,pe=$.jgrid.getCellIndex(Q),$(i).triggerHandler("jqGridRightClickRow",[$(V).attr("id"),le,pe,e]),$.isFunction(this.p.onRightClickRow)&&i.p.onRightClickRow.call(i,$(V).attr("id"),le,pe,e))}),r.bDiv=document.createElement("div"),d&&"auto"===String(i.p.height).toLowerCase()&&(i.p.height="100%"),$(r.bDiv).append($('<div style="position:relative;'+(d&&$.browser.version<8?"height:0.01%;":"")+'"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({height:i.p.height+(isNaN(i.p.height)?"":"px"),width:r.width+"px"}).scroll(r.scrollGrid),$("table:first",r.bDiv).css({width:i.p.tblwidth+"px"}),d?(2==$("tbody",this).size()&&$("tbody:gt(0)",this).remove(),i.p.multikey&&$(r.bDiv).bind("selectstart",function(){return!1})):i.p.multikey&&$(r.bDiv).bind("mousedown",function(){return!1}),ne&&$(r.bDiv).hide(),r.cDiv=document.createElement("div");var ue=i.p.hidegrid===!0?$("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function(){ue.addClass("ui-state-hover")},function(){ue.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css("rtl"==o?"left":"right","0px"):"";if($(r.cDiv).append(ue).append("<span class='ui-jqgrid-title"+("rtl"==o?"-rtl":"")+"'>"+i.p.caption+"</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"),$(r.cDiv).insertBefore(r.hDiv),i.p.toolbar[0]&&(r.uDiv=document.createElement("div"),"top"==i.p.toolbar[1]?$(r.uDiv).insertBefore(r.hDiv):"bottom"==i.p.toolbar[1]&&$(r.uDiv).insertAfter(r.hDiv),"both"==i.p.toolbar[1]?(r.ubDiv=document.createElement("div"),$(r.uDiv).insertBefore(r.hDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id),$(r.ubDiv).insertAfter(r.hDiv).addClass("ui-userdata ui-state-default").attr("id","tb_"+this.id),ne&&$(r.ubDiv).hide()):$(r.uDiv).width(r.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id),ne&&$(r.uDiv).hide()),i.p.toppager&&(i.p.toppager=$.jgrid.jqID(i.p.id)+"_toppager",r.topDiv=$("<div id='"+i.p.toppager+"'></div>")[0],i.p.toppager="#"+i.p.toppager,$(r.topDiv).insertBefore(r.hDiv).addClass("ui-state-default ui-jqgrid-toppager").width(r.width),S(i.p.toppager,"_t")),i.p.footerrow&&(r.sDiv=$("<div class='ui-jqgrid-sdiv'></div>")[0],de=$("<div class='ui-jqgrid-hbox"+("rtl"==o?"-rtl":"")+"'></div>"),$(r.sDiv).append(de).insertAfter(r.hDiv).width(r.width),$(de).append(ie),r.footers=$(".ui-jqgrid-ftable",r.sDiv)[0].rows[0].cells,i.p.rownumbers&&(r.footers[0].className="ui-state-default jqgrid-rownum"),ne&&$(r.sDiv).hide()),de=null,i.p.caption){var he=i.p.datatype;i.p.hidegrid===!0&&($(".ui-jqgrid-titlebar-close",r.cDiv).click(function(e){var t,a=$.isFunction(i.p.onHeaderClick),o=".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",s=this;return i.p.toolbar[0]===!0&&("both"==i.p.toolbar[1]&&(o+=", #"+$(r.ubDiv).attr("id")),o+=", #"+$(r.uDiv).attr("id")),t=$(o,"#gview_"+$.jgrid.jqID(i.p.id)).length,"visible"==i.p.gridstate?$(o,"#gbox_"+$.jgrid.jqID(i.p.id)).slideUp("fast",function(){t--,0===t&&($("span",s).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s"),i.p.gridstate="hidden",$("#gbox_"+$.jgrid.jqID(i.p.id)).hasClass("ui-resizable")&&$(".ui-resizable-handle","#gbox_"+$.jgrid.jqID(i.p.id)).hide(),$(i).triggerHandler("jqGridHeaderClick",[i.p.gridstate,e]),a&&(ne||i.p.onHeaderClick.call(i,i.p.gridstate,e)))}):"hidden"==i.p.gridstate&&$(o,"#gbox_"+$.jgrid.jqID(i.p.id)).slideDown("fast",function(){t--,0===t&&($("span",s).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n"),ne&&(i.p.datatype=he,F(),ne=!1),i.p.gridstate="visible",$("#gbox_"+$.jgrid.jqID(i.p.id)).hasClass("ui-resizable")&&$(".ui-resizable-handle","#gbox_"+$.jgrid.jqID(i.p.id)).show(),$(i).triggerHandler("jqGridHeaderClick",[i.p.gridstate,e]),a&&(ne||i.p.onHeaderClick.call(i,i.p.gridstate,e)))}),!1}),ne&&(i.p.datatype="local",$(".ui-jqgrid-titlebar-close",r.cDiv).trigger("click")))}else $(r.cDiv).hide();$(r.hDiv).after(r.bDiv).mousemove(function(e){return r.resizing?(r.dragMove(e),!1):void 0}),$(".ui-jqgrid-labels",r.hDiv).bind("selectstart",function(){return!1}),$(document).mouseup(function(){return r.resizing?(r.dragEnd(),!1):!0}),i.formatCol=u,i.sortData=R,i.updatepager=C,i.refreshIndex=y,i.setHeadCheckBox=k,i.constructTr=q,i.formatter=function(e,t,i,r,a){return f(e,t,i,r,a)},$.extend(r,{populate:F,emptyRows:w}),this.grid=r,i.addXmlData=function(e){x(e,i.grid.bDiv)},i.addJSONData=function(e){D(e,i.grid.bDiv)},this.grid.cols=this.rows[0].cells,F(),i.p.hiddengrid=!1,$(window).unload(function(){i=null})}})},$.jgrid.extend({getGridParam:function(e){var t=this[0];if(t&&t.grid)return e?"undefined"!=typeof t.p[e]?t.p[e]:null:t.p},setGridParam:function(e){return this.each(function(){this.grid&&"object"==typeof e&&$.extend(!0,this.p,e)})},getDataIDs:function(){var e,t=[],i=0,r=0;return this.each(function(){if(e=this.rows.length,e&&e>0)for(;e>i;)$(this.rows[i]).hasClass("jqgrow")&&(t[r]=this.rows[i].id,r++),i++}),t},setSelection:function(e,t,i){return this.each(function(){function r(e){var t=$(p.grid.bDiv)[0].clientHeight,i=$(p.grid.bDiv)[0].scrollTop,r=p.rows[e].offsetTop,a=p.rows[e].clientHeight;r+a>=t+i?$(p.grid.bDiv)[0].scrollTop=r-(t+i)+a+i:t+i>r&&i>r&&($(p.grid.bDiv)[0].scrollTop=r)}var a,o,s,n,d,l,p=this;void 0!==e&&(t=t===!1?!1:!0,o=p.rows.namedItem(e+""),!o||!o.className||o.className.indexOf("ui-state-disabled")>-1||(p.p.scrollrows===!0&&(s=p.rows.namedItem(e).rowIndex,s>=0&&r(s)),p.p.frozenColumns===!0&&(l=p.p.id+"_frozen"),p.p.multiselect?(p.setHeadCheckBox(!1),p.p.selrow=o.id,n=$.inArray(p.p.selrow,p.p.selarrrow),-1===n?("ui-subgrid"!==o.className&&$(o).addClass("ui-state-highlight").attr("aria-selected","true"),a=!0,p.p.selarrrow.push(p.p.selrow)):("ui-subgrid"!==o.className&&$(o).removeClass("ui-state-highlight").attr("aria-selected","false"),a=!1,p.p.selarrrow.splice(n,1),d=p.p.selarrrow[0],p.p.selrow=void 0===d?null:d),$("#jqg_"+$.jgrid.jqID(p.p.id)+"_"+$.jgrid.jqID(o.id))[p.p.useProp?"prop":"attr"]("checked",a),l&&(-1===n?$("#"+$.jgrid.jqID(e),"#"+$.jgrid.jqID(l)).addClass("ui-state-highlight"):$("#"+$.jgrid.jqID(e),"#"+$.jgrid.jqID(l)).removeClass("ui-state-highlight"),$("#jqg_"+$.jgrid.jqID(p.p.id)+"_"+$.jgrid.jqID(e),"#"+$.jgrid.jqID(l))[p.p.useProp?"prop":"attr"]("checked",a)),$(p).triggerHandler("jqGridSelectRow",[o.id,a,i]),p.p.onSelectRow&&t&&p.p.onSelectRow.call(p,o.id,a,i)):"ui-subgrid"!==o.className&&(p.p.selrow!=o.id?($(p.rows.namedItem(p.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected":"false",tabindex:"-1"}),$(o).addClass("ui-state-highlight").attr({"aria-selected":"true",tabindex:"0"}),l&&($("#"+$.jgrid.jqID(p.p.selrow),"#"+$.jgrid.jqID(l)).removeClass("ui-state-highlight"),$("#"+$.jgrid.jqID(e),"#"+$.jgrid.jqID(l)).addClass("ui-state-highlight")),a=!0):a=!1,p.p.selrow=o.id,$(p).triggerHandler("jqGridSelectRow",[o.id,a,i]),p.p.onSelectRow&&t&&p.p.onSelectRow.call(p,o.id,a,i))))})},resetSelection:function(e){return this.each(function(){var t,i,r,a=this;a.p.frozenColumns===!0&&(r=a.p.id+"_frozen"),"undefined"!=typeof e?(i=e===a.p.selrow?a.p.selrow:e,$("#"+$.jgrid.jqID(a.p.id)+" tbody:first tr#"+$.jgrid.jqID(i)).removeClass("ui-state-highlight").attr("aria-selected","false"),r&&$("#"+$.jgrid.jqID(i),"#"+$.jgrid.jqID(r)).removeClass("ui-state-highlight"),a.p.multiselect&&($("#jqg_"+$.jgrid.jqID(a.p.id)+"_"+$.jgrid.jqID(i),"#"+$.jgrid.jqID(a.p.id))[a.p.useProp?"prop":"attr"]("checked",!1),r&&$("#jqg_"+$.jgrid.jqID(a.p.id)+"_"+$.jgrid.jqID(i),"#"+$.jgrid.jqID(r))[a.p.useProp?"prop":"attr"]("checked",!1),a.setHeadCheckBox(!1)),i=null):a.p.multiselect?($(a.p.selarrrow).each(function(e,i){t=a.rows.namedItem(i),$(t).removeClass("ui-state-highlight").attr("aria-selected","false"),$("#jqg_"+$.jgrid.jqID(a.p.id)+"_"+$.jgrid.jqID(i))[a.p.useProp?"prop":"attr"]("checked",!1),r&&($("#"+$.jgrid.jqID(i),"#"+$.jgrid.jqID(r)).removeClass("ui-state-highlight"),$("#jqg_"+$.jgrid.jqID(a.p.id)+"_"+$.jgrid.jqID(i),"#"+$.jgrid.jqID(r))[a.p.useProp?"prop":"attr"]("checked",!1))}),a.setHeadCheckBox(!1),a.p.selarrrow=[]):a.p.selrow&&($("#"+$.jgrid.jqID(a.p.id)+" tbody:first tr#"+$.jgrid.jqID(a.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"),r&&$("#"+$.jgrid.jqID(a.p.selrow),"#"+$.jgrid.jqID(r)).removeClass("ui-state-highlight"),a.p.selrow=null),a.p.cellEdit===!0&&parseInt(a.p.iCol,10)>=0&&parseInt(a.p.iRow,10)>=0&&($("td:eq("+a.p.iCol+")",a.rows[a.p.iRow]).removeClass("edit-cell ui-state-highlight"),
$(a.rows[a.p.iRow]).removeClass("selected-row ui-state-hover")),a.p.savedRow=[]})},getRowData:function(e){var t,i,r={},a=!1,o=0;return this.each(function(){var s,n,d=this;if("undefined"==typeof e)a=!0,t=[],i=d.rows.length;else{if(n=d.rows.namedItem(e),!n)return r;i=2}for(;i>o;)a&&(n=d.rows[o]),$(n).hasClass("jqgrow")&&($('td[role="gridcell"]',n).each(function(e){if(s=d.p.colModel[e].name,"cb"!==s&&"subgrid"!==s&&"rn"!==s)if(d.p.treeGrid===!0&&s==d.p.ExpandColumn)r[s]=$.jgrid.htmlDecode($("span:first",this).html());else try{r[s]=$.unformat.call(d,this,{rowId:n.id,colModel:d.p.colModel[e]},e)}catch(t){r[s]=$.jgrid.htmlDecode($(this).html())}}),a&&(t.push(r),r={})),o++}),t?t:r},delRowData:function(e){var t,i,r,a=!1;return this.each(function(){var o=this;if(t=o.rows.namedItem(e),!t)return!1;if(r=t.rowIndex,$(t).remove(),o.p.records--,o.p.reccount--,o.updatepager(!0,!1),a=!0,o.p.multiselect&&(i=$.inArray(e,o.p.selarrrow),-1!=i&&o.p.selarrrow.splice(i,1)),e==o.p.selrow&&(o.p.selrow=null),"local"==o.p.datatype){var s=$.jgrid.stripPref(o.p.idPrefix,e),n=o.p._index[s];"undefined"!=typeof n&&(o.p.data.splice(n,1),o.refreshIndex())}if(o.p.altRows===!0&&a){var d=o.p.altclass;$(o.rows).each(function(e){e%2==1?$(this).addClass(d):$(this).removeClass(d)})}}),a},setRowData:function(e,t,i){var r,a,o=!0;return this.each(function(){if(!this.grid)return!1;var s,n,d=this,l=typeof i,p={};if(n=d.rows.namedItem(e),!n)return!1;if(t)try{if($(this.p.colModel).each(function(i){r=this.name,void 0!==t[r]&&(p[r]=this.formatter&&"string"==typeof this.formatter&&"date"==this.formatter?$.unformat.date.call(d,t[r],this):t[r],s=d.formatter(e,t[r],i,t,"edit"),a=this.title?{title:$.jgrid.stripHtml(s)}:{},d.p.treeGrid===!0&&r==d.p.ExpandColumn?$("td:eq("+i+") > span:first",n).html(s).attr(a):$("td:eq("+i+")",n).html(s).attr(a))}),"local"==d.p.datatype){var c=$.jgrid.stripPref(d.p.idPrefix,e),u=d.p._index[c];if(d.p.treeGrid)for(var h in d.p.treeReader)p.hasOwnProperty(d.p.treeReader[h])&&delete p[d.p.treeReader[h]];"undefined"!=typeof u&&(d.p.data[u]=$.extend(!0,d.p.data[u],p)),p=null}}catch(f){o=!1}o&&("string"===l?$(n).addClass(i):"object"===l&&$(n).css(i),$(d).triggerHandler("jqGridAfterGridComplete"))}),o},addRowData:function(e,t,i,r){i||(i="last");var a,o,s,n,d,l,p,c,u,h,f,g,m,v,j=!1,b="";return t&&($.isArray(t)?(u=!0,i="last",h=e):(t=[t],u=!1),this.each(function(){var w=this,y=t.length;d=w.p.rownumbers===!0?1:0,s=w.p.multiselect===!0?1:0,n=w.p.subGrid===!0?1:0,u||("undefined"!=typeof e?e+="":(e=$.jgrid.randId(),w.p.keyIndex!==!1&&(h=w.p.colModel[w.p.keyIndex+s+n+d].name,"undefined"!=typeof t[0][h]&&(e=t[0][h])))),f=w.p.altclass;for(var q=0,x="",D={},_=$.isFunction(w.p.afterInsertRow)?!0:!1;y>q;){if(g=t[q],o=[],u){try{e=g[h]}catch(C){e=$.jgrid.randId()}x=w.p.altRows===!0&&(w.rows.length-1)%2===0?f:""}for(v=e,e=w.p.idPrefix+e,d&&(b=w.formatCol(0,1,"",null,e,!0),o[o.length]='<td role="gridcell" class="ui-state-default jqgrid-rownum" '+b+">0</td>"),s&&(c='<input role="checkbox" type="checkbox" id="jqg_'+w.p.id+"_"+e+'" class="cbox"/>',b=w.formatCol(d,1,"",null,e,!0),o[o.length]='<td role="gridcell" '+b+">"+c+"</td>"),n&&(o[o.length]=$(w).jqGrid("addSubGridCell",s+d,1)),p=s+n+d;p<w.p.colModel.length;p++)m=w.p.colModel[p],a=m.name,D[a]=g[a],c=w.formatter(e,$.jgrid.getAccessor(g,a),p,g),b=w.formatCol(p,1,c,g,e,!0),o[o.length]='<td role="gridcell" '+b+">"+c+"</td>";if(o.unshift(w.constructTr(e,!1,x,D,D)),o[o.length]="</tr>",0===w.rows.length)$("table:first",w.grid.bDiv).append(o.join(""));else switch(i){case"last":$(w.rows[w.rows.length-1]).after(o.join("")),l=w.rows.length-1;break;case"first":$(w.rows[0]).after(o.join("")),l=1;break;case"after":l=w.rows.namedItem(r),l&&($(w.rows[l.rowIndex+1]).hasClass("ui-subgrid")?$(w.rows[l.rowIndex+1]).after(o):$(l).after(o.join(""))),l++;break;case"before":l=w.rows.namedItem(r),l&&($(l).before(o.join("")),l=l.rowIndex),l--}w.p.subGrid===!0&&$(w).jqGrid("addSubGrid",s+d,l),w.p.records++,w.p.reccount++,$(w).triggerHandler("jqGridAfterInsertRow",[e,g,g]),_&&w.p.afterInsertRow.call(w,e,g,g),q++,"local"==w.p.datatype&&(D[w.p.localReader.id]=v,w.p._index[v]=w.p.data.length,w.p.data.push(D),D={})}w.p.altRows!==!0||u||("last"==i?(w.rows.length-1)%2==1&&$(w.rows[w.rows.length-1]).addClass(f):$(w.rows).each(function(e){e%2==1?$(this).addClass(f):$(this).removeClass(f)})),w.updatepager(!0,!0),j=!0})),j},footerData:function(e,t,i){function r(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}var a,o,s=!1,n={};return"undefined"==typeof e&&(e="get"),"boolean"!=typeof i&&(i=!0),e=e.toLowerCase(),this.each(function(){var d,l=this;return l.grid&&l.p.footerrow?"set"==e&&r(t)?!1:(s=!0,void $(this.p.colModel).each(function(r){a=this.name,"set"==e?void 0!==t[a]&&(d=i?l.formatter("",t[a],r,t,"edit"):t[a],o=this.title?{title:$.jgrid.stripHtml(d)}:{},$("tr.footrow td:eq("+r+")",l.grid.sDiv).html(d).attr(o),s=!0):"get"==e&&(n[a]=$("tr.footrow td:eq("+r+")",l.grid.sDiv).html())})):!1}),"get"==e?n:s},showHideCol:function(e,t){return this.each(function(){var i,r=this,a=!1,o=$.jgrid.cellWidth()?0:r.p.cellLayout;if(r.grid){"string"==typeof e&&(e=[e]),t="none"!=t?"":"none";var s=""===t?!0:!1,n=r.p.groupHeader&&("object"==typeof r.p.groupHeader||$.isFunction(r.p.groupHeader));n&&$(r).jqGrid("destroyGroupHeader",!1),$(this.p.colModel).each(function(n){if(-1!==$.inArray(this.name,e)&&this.hidden===s){if(r.p.frozenColumns===!0&&this.frozen===!0)return!0;$("tr",r.grid.hDiv).each(function(){$(this.cells[n]).css("display",t)}),$(r.rows).each(function(){$(this).hasClass("jqgroup")||$(this.cells[n]).css("display",t)}),r.p.footerrow&&$("tr.footrow td:eq("+n+")",r.grid.sDiv).css("display",t),i=parseInt(this.width,10),"none"===t?r.p.tblwidth-=i+o:r.p.tblwidth+=i+o,this.hidden=!s,a=!0,$(r).triggerHandler("jqGridShowHideCol",[s,this.name,n])}}),a===!0&&(r.p.shrinkToFit!==!0||isNaN(r.p.height)||(r.p.tblwidth+=parseInt(r.p.scrollOffset,10)),$(r).jqGrid("setGridWidth",r.p.shrinkToFit===!0?r.p.tblwidth:r.p.width)),n&&$(r).jqGrid("setGroupHeaders",r.p.groupHeader)}})},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(e,t,i){function r(t){var i;i=t.length?$.makeArray(t):$.extend({},t),$.each(e,function(e){t[e]=i[this]})}function a(t,i){$(">tr"+(i||""),t).each(function(){var t=this,i=$.makeArray(t.cells);$.each(e,function(){var e=i[this];e&&t.appendChild(e)})})}var o=this.get(0);r(o.p.colModel),r(o.p.colNames),r(o.grid.headers),a($("thead:first",o.grid.hDiv),i&&":not(.ui-jqgrid-labels)"),t&&a($("#"+$.jgrid.jqID(o.p.id)+" tbody:first"),".jqgfirstrow, tr.jqgrow, tr.jqfoot"),o.p.footerrow&&a($("tbody:first",o.grid.sDiv)),o.p.remapColumns&&(o.p.remapColumns.length?r(o.p.remapColumns):o.p.remapColumns=$.makeArray(e)),o.p.lastsort=$.inArray(o.p.lastsort,e),o.p.treeGrid&&(o.p.expColInd=$.inArray(o.p.expColInd,e)),$(o).triggerHandler("jqGridRemapColumns",[e,t,i])},setGridWidth:function(e,t){return this.each(function(){if(this.grid){var i,r,a,o,s=this,n=0,d=$.jgrid.cellWidth()?0:s.p.cellLayout,l=0,p=!1,c=s.p.scrollOffset,u=0,h=0;if("boolean"!=typeof t&&(t=s.p.shrinkToFit),!isNaN(e)){if(e=parseInt(e,10),s.grid.width=s.p.width=e,$("#gbox_"+$.jgrid.jqID(s.p.id)).css("width",e+"px"),$("#gview_"+$.jgrid.jqID(s.p.id)).css("width",e+"px"),$(s.grid.bDiv).css("width",e+"px"),$(s.grid.hDiv).css("width",e+"px"),s.p.pager&&$(s.p.pager).css("width",e+"px"),s.p.toppager&&$(s.p.toppager).css("width",e+"px"),s.p.toolbar[0]===!0&&($(s.grid.uDiv).css("width",e+"px"),"both"==s.p.toolbar[1]&&$(s.grid.ubDiv).css("width",e+"px")),s.p.footerrow&&$(s.grid.sDiv).css("width",e+"px"),t===!1&&s.p.forceFit===!0&&(s.p.forceFit=!1),t===!0){if($.each(s.p.colModel,function(){this.hidden===!1&&(i=this.widthOrg,n+=i+d,this.fixed?u+=i+d:l++,h++)}),0===l)return;s.p.tblwidth=n,a=e-d*l-u,isNaN(s.p.height)||($(s.grid.bDiv)[0].clientHeight<$(s.grid.bDiv)[0].scrollHeight||1===s.rows.length)&&(p=!0,a-=c),n=0;var f=s.grid.cols.length>0;if($.each(s.p.colModel,function(e){if(this.hidden===!1&&!this.fixed){if(i=this.widthOrg,i=Math.round(a*i/(s.p.tblwidth-d*l-u)),0>i)return;this.width=i,n+=i,s.grid.headers[e].width=i,s.grid.headers[e].el.style.width=i+"px",s.p.footerrow&&(s.grid.footers[e].style.width=i+"px"),f&&(s.grid.cols[e].style.width=i+"px"),r=e}}),!r)return;if(o=0,p?e-u-(n+d*l)!==c&&(o=e-u-(n+d*l)-c):1!==Math.abs(e-u-(n+d*l))&&(o=e-u-(n+d*l)),s.p.colModel[r].width+=o,s.p.tblwidth=n+o+d*l+u,s.p.tblwidth>e){var g=s.p.tblwidth-parseInt(e,10);s.p.tblwidth=e,i=s.p.colModel[r].width=s.p.colModel[r].width-g}else i=s.p.colModel[r].width;s.grid.headers[r].width=i,s.grid.headers[r].el.style.width=i+"px",f&&(s.grid.cols[r].style.width=i+"px"),s.p.footerrow&&(s.grid.footers[r].style.width=i+"px")}s.p.tblwidth&&($("table:first",s.grid.bDiv).css("width",s.p.tblwidth+"px"),$("table:first",s.grid.hDiv).css("width",s.p.tblwidth+"px"),s.grid.hDiv.scrollLeft=s.grid.bDiv.scrollLeft,s.p.footerrow&&$("table:first",s.grid.sDiv).css("width",s.p.tblwidth+"px"))}}})},setGridHeight:function(e){return this.each(function(){var t=this;if(t.grid){var i=$(t.grid.bDiv);i.css({height:e+(isNaN(e)?"":"px")}),t.p.frozenColumns===!0&&$("#"+$.jgrid.jqID(t.p.id)+"_frozen").parent().height(i.height()-16),t.p.height=e,t.p.scroll&&t.grid.populateVisible()}})},setCaption:function(e){return this.each(function(){this.p.caption=e,$("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",this.grid.cDiv).html(e),$(this.grid.cDiv).show()})},setLabel:function(e,t,i,r){return this.each(function(){var a=this,o=-1;if(a.grid&&"undefined"!=typeof e&&($(a.p.colModel).each(function(t){return this.name==e?(o=t,!1):void 0}),o>=0)){var s=$("tr.ui-jqgrid-labels th:eq("+o+")",a.grid.hDiv);if(t){var n=$(".s-ico",s);$("[id^=jqgh_]",s).empty().html(t).append(n),a.p.colNames[o]=t}i&&("string"==typeof i?$(s).addClass(i):$(s).css(i)),"object"==typeof r&&$(s).attr(r)}})},setCell:function(e,t,i,r,a,o){return this.each(function(){var s,n,d=this,l=-1;if(d.grid&&(isNaN(t)?$(d.p.colModel).each(function(e){return this.name==t?(l=e,!1):void 0}):l=parseInt(t,10),l>=0)){var p=d.rows.namedItem(e);if(p){var c=$("td:eq("+l+")",p);if((""!==i||o===!0)&&(s=d.formatter(e,i,l,p,"edit"),n=d.p.colModel[l].title?{title:$.jgrid.stripHtml(s)}:{},d.p.treeGrid&&$(".tree-wrap",$(c)).length>0?$("span",$(c)).html(s).attr(n):$(c).html(s).attr(n),"local"==d.p.datatype)){var u,h=d.p.colModel[l];i=h.formatter&&"string"==typeof h.formatter&&"date"==h.formatter?$.unformat.date.call(d,i,h):i,u=d.p._index[e],"undefined"!=typeof u&&(d.p.data[u][h.name]=i)}"string"==typeof r?$(c).addClass(r):r&&$(c).css(r),"object"==typeof a&&$(c).attr(a)}}})},getCell:function(e,t){var i=!1;return this.each(function(){var r=this,a=-1;if(r.grid&&(isNaN(t)?$(r.p.colModel).each(function(e){return this.name===t?(a=e,!1):void 0}):a=parseInt(t,10),a>=0)){var o=r.rows.namedItem(e);if(o)try{i=$.unformat.call(r,$("td:eq("+a+")",o),{rowId:o.id,colModel:r.p.colModel[a]},a)}catch(s){i=$.jgrid.htmlDecode($("td:eq("+a+")",o).html())}}}),i},getCol:function(e,t,i){var r,a,o,s,n=[],d=0;return t="boolean"!=typeof t?!1:t,"undefined"==typeof i&&(i=!1),this.each(function(){var l=this,p=-1;if(l.grid&&(isNaN(e)?$(l.p.colModel).each(function(t){return this.name===e?(p=t,!1):void 0}):p=parseInt(e,10),p>=0)){var c=l.rows.length,u=0;if(c&&c>0){for(;c>u;){if($(l.rows[u]).hasClass("jqgrow")){try{r=$.unformat.call(l,$(l.rows[u].cells[p]),{rowId:l.rows[u].id,colModel:l.p.colModel[p]},p)}catch(h){r=$.jgrid.htmlDecode(l.rows[u].cells[p].innerHTML)}i?(s=parseFloat(r),d+=s,0===u?(a=s,o=s):(a=Math.min(a,s),o=Math.max(o,s))):t?n.push({id:l.rows[u].id,value:r}):n.push(r)}u++}if(i)switch(i.toLowerCase()){case"sum":n=d;break;case"avg":n=d/c;break;case"count":n=c;break;case"min":n=a;break;case"max":n=o}}}}),n},clearGridData:function(e){return this.each(function(){var t=this;if(t.grid){if("boolean"!=typeof e&&(e=!1),t.p.deepempty)$("#"+$.jgrid.jqID(t.p.id)+" tbody:first tr:gt(0)").remove();else{var i=$("#"+$.jgrid.jqID(t.p.id)+" tbody:first tr:first")[0];$("#"+$.jgrid.jqID(t.p.id)+" tbody:first").empty().append(i)}t.p.footerrow&&e&&$(".ui-jqgrid-ftable td",t.grid.sDiv).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.updatepager(!0,!1)}})},getInd:function(e,t){var i,r=!1;return this.each(function(){i=this.rows.namedItem(e),i&&(r=t===!0?i:i.rowIndex)}),r},bindKeys:function(e){var t=$.extend({onEnter:null,onSpace:null,onLeftKey:null,onRightKey:null,scrollingRows:!0},e||{});return this.each(function(){var e=this;$("body").is("[role]")||$("body").attr("role","application"),e.p.scrollrows=t.scrollingRows,$(e).keydown(function(i){var r,a,o,s=$(e).find("tr[tabindex=0]")[0],n=e.p.treeReader.expanded_field;if(s)if(o=e.p._index[s.id],37===i.keyCode||38===i.keyCode||39===i.keyCode||40===i.keyCode){if(38===i.keyCode){if(a=s.previousSibling,r="",a)if($(a).is(":hidden")){for(;a;)if(a=a.previousSibling,!$(a).is(":hidden")&&$(a).hasClass("jqgrow")){r=a.id;break}}else r=a.id;$(e).jqGrid("setSelection",r,!0,i)}if(40===i.keyCode){if(a=s.nextSibling,r="",a)if($(a).is(":hidden")){for(;a;)if(a=a.nextSibling,!$(a).is(":hidden")&&$(a).hasClass("jqgrow")){r=a.id;break}}else r=a.id;$(e).jqGrid("setSelection",r,!0,i)}37===i.keyCode&&(e.p.treeGrid&&e.p.data[o][n]&&$(s).find("div.treeclick").trigger("click"),$(e).triggerHandler("jqGridKeyLeft",[e.p.selrow]),$.isFunction(t.onLeftKey)&&t.onLeftKey.call(e,e.p.selrow)),39===i.keyCode&&(e.p.treeGrid&&!e.p.data[o][n]&&$(s).find("div.treeclick").trigger("click"),$(e).triggerHandler("jqGridKeyRight",[e.p.selrow]),$.isFunction(t.onRightKey)&&t.onRightKey.call(e,e.p.selrow))}else 13===i.keyCode?($(e).triggerHandler("jqGridKeyEnter",[e.p.selrow]),$.isFunction(t.onEnter)&&t.onEnter.call(e,e.p.selrow)):32===i.keyCode&&($(e).triggerHandler("jqGridKeySpace",[e.p.selrow]),$.isFunction(t.onSpace)&&t.onSpace.call(e,e.p.selrow))})})},unbindKeys:function(){return this.each(function(){$(this).unbind("keydown")})},getLocalRow:function(e){var t,i=!1;return this.each(function(){"undefined"!=typeof e&&(t=this.p._index[e],t>=0&&(i=this.p.data[t]))}),i}})}(jQuery),function(e){"use strict";e.jgrid.extend({getColProp:function(e){var t={},i=this[0];if(!i.grid)return!1;for(var r=i.p.colModel,a=0;a<r.length;a++)if(r[a].name==e){t=r[a];break}return t},setColProp:function(t,i){return this.each(function(){if(this.grid&&i)for(var r=this.p.colModel,a=0;a<r.length;a++)if(r[a].name==t){e.extend(this.p.colModel[a],i);break}})},sortGrid:function(e,t,i){return this.each(function(){var r=this,a=-1;if(r.grid){e||(e=r.p.sortname);for(var o=0;o<r.p.colModel.length;o++)if(r.p.colModel[o].index==e||r.p.colModel[o].name==e){a=o;break}if(-1!=a){var s=r.p.colModel[a].sortable;"boolean"!=typeof s&&(s=!0),"boolean"!=typeof t&&(t=!1),s&&r.sortData("jqgh_"+r.p.id+"_"+e,a,t,i)}}})},GridDestroy:function(){return this.each(function(){if(this.grid){this.p.pager&&e(this.p.pager).remove();try{e("#gbox_"+e.jgrid.jqID(this.id)).remove()}catch(t){}}})},GridUnload:function(){return this.each(function(){if(this.grid){var t={id:e(this).attr("id"),cl:e(this).attr("class")};this.p.pager&&e(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom");var i=document.createElement("table");e(i).attr({id:t.id}),i.className=t.cl;var r=e.jgrid.jqID(this.id);e(i).removeClass("ui-jqgrid-btable"),1===e(this.p.pager).parents("#gbox_"+r).length?(e(i).insertBefore("#gbox_"+r).show(),e(this.p.pager).insertBefore("#gbox_"+r)):e(i).insertBefore("#gbox_"+r).show(),e("#gbox_"+r).remove()}})},setGridState:function(t){return this.each(function(){if(this.grid){var i=this;"hidden"==t?(e(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+e.jgrid.jqID(i.p.id)).slideUp("fast"),i.p.pager&&e(i.p.pager).slideUp("fast"),i.p.toppager&&e(i.p.toppager).slideUp("fast"),i.p.toolbar[0]===!0&&("both"==i.p.toolbar[1]&&e(i.grid.ubDiv).slideUp("fast"),e(i.grid.uDiv).slideUp("fast")),i.p.footerrow&&e(".ui-jqgrid-sdiv","#gbox_"+e.jgrid.jqID(i.p.id)).slideUp("fast"),e(".ui-jqgrid-titlebar-close span",i.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s"),i.p.gridstate="hidden"):"visible"==t&&(e(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+e.jgrid.jqID(i.p.id)).slideDown("fast"),i.p.pager&&e(i.p.pager).slideDown("fast"),i.p.toppager&&e(i.p.toppager).slideDown("fast"),i.p.toolbar[0]===!0&&("both"==i.p.toolbar[1]&&e(i.grid.ubDiv).slideDown("fast"),e(i.grid.uDiv).slideDown("fast")),i.p.footerrow&&e(".ui-jqgrid-sdiv","#gbox_"+e.jgrid.jqID(i.p.id)).slideDown("fast"),e(".ui-jqgrid-titlebar-close span",i.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n"),i.p.gridstate="visible")}})},filterToolbar:function(t){return t=e.extend({autosearch:!0,searchOnEnter:!0,beforeSearch:null,afterSearch:null,beforeClear:null,afterClear:null,searchurl:"",stringResult:!1,groupOp:"AND",defaultSearch:"bw"},t||{}),this.each(function(){function i(t,i){var r=e(t);r[0]&&jQuery.each(i,function(){void 0!==this.data?r.bind(this.type,this.data,this.fn):r.bind(this.type,this.fn)})}var r=this;if(!this.ftoolbar){var a,o=function(){var i,a,o,s={},n=0,d={};e.each(r.p.colModel,function(){if(a=this.index||this.name,o=this.searchoptions&&this.searchoptions.sopt?this.searchoptions.sopt[0]:"select"==this.stype?"eq":t.defaultSearch,i=e("#gs_"+e.jgrid.jqID(this.name),this.frozen===!0&&r.p.frozenColumns===!0?r.grid.fhDiv:r.grid.hDiv).val())s[a]=i,d[a]=o,n++;else try{delete r.p.postData[a]}catch(l){}});var l=n>0?!0:!1;if(t.stringResult===!0||"local"==r.p.datatype){var p='{"groupOp":"'+t.groupOp+'","rules":[',c=0;e.each(s,function(e,t){c>0&&(p+=","),p+='{"field":"'+e+'",',p+='"op":"'+d[e]+'",',t+="",p+='"data":"'+t.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}',c++}),p+="]}",e.extend(r.p.postData,{filters:p}),e.each(["searchField","searchString","searchOper"],function(e,t){r.p.postData.hasOwnProperty(t)&&delete r.p.postData[t]})}else e.extend(r.p.postData,s);var u;r.p.searchurl&&(u=r.p.url,e(r).jqGrid("setGridParam",{url:r.p.searchurl}));var h="stop"===e(r).triggerHandler("jqGridToolbarBeforeSearch")?!0:!1;!h&&e.isFunction(t.beforeSearch)&&(h=t.beforeSearch.call(r)),h||e(r).jqGrid("setGridParam",{search:l}).trigger("reloadGrid",[{page:1}]),u&&e(r).jqGrid("setGridParam",{url:u}),e(r).triggerHandler("jqGridToolbarAfterSearch"),e.isFunction(t.afterSearch)&&t.afterSearch.call(r)},s=function(i){var a,o={},s=0;i="boolean"!=typeof i?!0:i,e.each(r.p.colModel,function(){var t;switch(this.searchoptions&&void 0!==this.searchoptions.defaultValue&&(t=this.searchoptions.defaultValue),a=this.index||this.name,this.stype){case"select":if(e("#gs_"+e.jgrid.jqID(this.name)+" option",this.frozen===!0&&r.p.frozenColumns===!0?r.grid.fhDiv:r.grid.hDiv).each(function(i){return 0===i&&(this.selected=!0),e(this).val()==t?(this.selected=!0,!1):void 0}),void 0!==t)o[a]=t,s++;else try{delete r.p.postData[a]}catch(i){}break;case"text":if(e("#gs_"+e.jgrid.jqID(this.name),this.frozen===!0&&r.p.frozenColumns===!0?r.grid.fhDiv:r.grid.hDiv).val(t),void 0!==t)o[a]=t,s++;else try{delete r.p.postData[a]}catch(n){}}});var n=s>0?!0:!1;if(t.stringResult===!0||"local"==r.p.datatype){var d='{"groupOp":"'+t.groupOp+'","rules":[',l=0;e.each(o,function(e,t){l>0&&(d+=","),d+='{"field":"'+e+'",',d+='"op":"eq",',t+="",d+='"data":"'+t.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}',l++}),d+="]}",e.extend(r.p.postData,{filters:d}),e.each(["searchField","searchString","searchOper"],function(e,t){r.p.postData.hasOwnProperty(t)&&delete r.p.postData[t]})}else e.extend(r.p.postData,o);var p;r.p.searchurl&&(p=r.p.url,e(r).jqGrid("setGridParam",{url:r.p.searchurl}));var c="stop"===e(r).triggerHandler("jqGridToolbarBeforeClear")?!0:!1;!c&&e.isFunction(t.beforeClear)&&(c=t.beforeClear.call(r)),c||i&&e(r).jqGrid("setGridParam",{search:n}).trigger("reloadGrid",[{page:1}]),p&&e(r).jqGrid("setGridParam",{url:p}),e(r).triggerHandler("jqGridToolbarAfterClear"),e.isFunction(t.afterClear)&&t.afterClear()},n=function(){var t=e("tr.ui-search-toolbar",r.grid.hDiv),i=r.p.frozenColumns===!0?e("tr.ui-search-toolbar",r.grid.fhDiv):!1;"none"==t.css("display")?(t.show(),i&&i.show()):(t.hide(),i&&i.hide())},d=e("<tr class='ui-search-toolbar' role='rowheader'></tr>");e.each(r.p.colModel,function(){var s,n,l,p,c,u=this;if(n=e("<th role='columnheader' class='ui-state-default ui-th-column ui-th-"+r.p.direction+"'></th>"),s=e("<div style='width:100%;position:relative;height:100%;padding-right:0.3em;'></div>"),this.hidden===!0&&e(n).css("display","none"),this.search=this.search===!1?!1:!0,"undefined"==typeof this.stype&&(this.stype="text"),l=e.extend({},this.searchoptions||{}),this.search)switch(this.stype){case"select":if(p=this.surl||l.dataUrl)c=s,e.ajax(e.extend({url:p,dataType:"html",success:function(r){if(void 0!==l.buildSelect){var a=l.buildSelect(r);a&&e(c).append(a)}else e(c).append(r);void 0!==l.defaultValue&&e("select",c).val(l.defaultValue),e("select",c).attr({name:u.index||u.name,id:"gs_"+u.name}),l.attr&&e("select",c).attr(l.attr),e("select",c).css({width:"100%"}),void 0!==l.dataInit&&l.dataInit(e("select",c)[0]),void 0!==l.dataEvents&&i(e("select",c)[0],l.dataEvents),t.autosearch===!0&&e("select",c).change(function(){return o(),!1}),r=null}},e.jgrid.ajaxOptions,r.p.ajaxSelectOptions||{}));else{var h,f,g;if(u.searchoptions?(h=void 0===u.searchoptions.value?"":u.searchoptions.value,f=void 0===u.searchoptions.separator?":":u.searchoptions.separator,g=void 0===u.searchoptions.delimiter?";":u.searchoptions.delimiter):u.editoptions&&(h=void 0===u.editoptions.value?"":u.editoptions.value,f=void 0===u.editoptions.separator?":":u.editoptions.separator,g=void 0===u.editoptions.delimiter?";":u.editoptions.delimiter),h){var m=document.createElement("select");m.style.width="100%",e(m).attr({name:u.index||u.name,id:"gs_"+u.name});var v,j,b;if("string"==typeof h){v=h.split(g);for(var w=0;w<v.length;w++)j=v[w].split(f),b=document.createElement("option"),b.value=j[0],b.innerHTML=j[1],m.appendChild(b)}else if("object"==typeof h)for(var y in h)h.hasOwnProperty(y)&&(b=document.createElement("option"),b.value=y,b.innerHTML=h[y],m.appendChild(b));void 0!==l.defaultValue&&e(m).val(l.defaultValue),l.attr&&e(m).attr(l.attr),void 0!==l.dataInit&&l.dataInit(m),void 0!==l.dataEvents&&i(m,l.dataEvents),e(s).append(m),t.autosearch===!0&&e(m).change(function(){return o(),!1})}}break;case"text":var q=void 0!==l.defaultValue?l.defaultValue:"";e(s).append("<input type='text' style='width:95%;padding:0px;' name='"+(u.index||u.name)+"' id='gs_"+u.name+"' value='"+q+"'/>"),l.attr&&e("input",s).attr(l.attr),void 0!==l.dataInit&&l.dataInit(e("input",s)[0]),void 0!==l.dataEvents&&i(e("input",s)[0],l.dataEvents),t.autosearch===!0&&(t.searchOnEnter?e("input",s).keypress(function(e){var t=e.charCode?e.charCode:e.keyCode?e.keyCode:0;return 13==t?(o(),!1):this}):e("input",s).keydown(function(e){var t=e.which;switch(t){case 13:return!1;case 9:case 16:case 37:case 38:case 39:case 40:case 27:break;default:a&&clearTimeout(a),a=setTimeout(function(){o()},500)}}))}e(n).append(s),e(d).append(n)}),e("table thead",r.grid.hDiv).append(d),this.ftoolbar=!0,this.triggerToolbar=o,this.clearToolbar=s,this.toggleToolbar=n}})},destroyGroupHeader:function(t){return"undefined"==typeof t&&(t=!0),this.each(function(){var i,r,a,o,s,n,d,l=this,p=l.grid,c=e("table.ui-jqgrid-htable thead",p.hDiv),u=l.p.colModel;if(p){for(e(this).unbind(".setGroupHeaders"),i=e("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels"),o=p.headers,r=0,a=o.length;a>r;r++){d=u[r].hidden?"none":"",s=e(o[r].el).width(o[r].width).css("display",d);try{s.removeAttr("rowSpan")}catch(h){s.attr("rowSpan",1)}i.append(s),n=s.children("span.ui-jqgrid-resize"),n.length>0&&(n[0].style.height=""),s.children("div")[0].style.top=""}e(c).children("tr.ui-jqgrid-labels").remove(),e(c).prepend(i),t===!0&&e(l).jqGrid("setGridParam",{groupHeader:null})}})},setGroupHeaders:function(t){return t=e.extend({useColSpanStyle:!1,groupHeaders:[]},t||{}),this.each(function(){this.p.groupHeader=t;var i,r,a,o,s,n,d,l,p,c,u,h,f,g=this,m=0,v=g.p.colModel,j=v.length,b=g.grid.headers,w=e("table.ui-jqgrid-htable",g.grid.hDiv),y=w.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"),q=w.children("thead"),x=w.find(".jqg-first-row-header");null===x.html()?x=e("<tr>",{role:"row","aria-hidden":"true"}).addClass("jqg-first-row-header").css("height","auto"):x.empty();var D,$=function(e,t){for(var i=0,r=t.length;r>i;i++)if(t[i].startColumnName===e)return i;return-1};for(e(g).prepend(q),a=e("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels jqg-third-row-header"),i=0;j>i;i++)if(s=b[i].el,n=e(s),r=v[i],d={height:"0px",width:b[i].width+"px",display:r.hidden?"none":""},e("<th>",{role:"gridcell"}).css(d).addClass("ui-first-th-"+g.p.direction).appendTo(x),s.style.width="",l=$(r.name,t.groupHeaders),l>=0){for(p=t.groupHeaders[l],c=p.numberOfColumns,u=p.titleText,h=0,l=0;c>l&&j>i+l;l++)v[i+l].hidden||h++;o=e("<th>").attr({role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+g.p.direction).css({height:"22px","border-top":"0px none"}).html(u),h>0&&o.attr("colspan",String(h)),g.p.headertitles&&o.attr("title",o.text()),0===h&&o.hide(),n.before(o),a.append(s),m=c-1}else 0===m?t.useColSpanStyle?n.attr("rowspan","2"):(e("<th>",{role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+g.p.direction).css({display:r.hidden?"none":"","border-top":"0px none"}).insertBefore(n),a.append(s)):(a.append(s),m--);f=e(g).children("thead"),f.prepend(x),a.insertAfter(y),w.append(f),t.useColSpanStyle&&(w.find("span.ui-jqgrid-resize").each(function(){var t=e(this).parent();t.is(":visible")&&(this.style.cssText="height: "+t.height()+"px !important; cursor: col-resize;")}),w.find("div.ui-jqgrid-sortable").each(function(){var t=e(this),i=t.parent();i.is(":visible")&&i.is(":has(span.ui-jqgrid-resize)")&&t.css("top",(i.height()-t.outerHeight())/2+"px")})),D=f.find("tr.jqg-first-row-header"),e(g).bind("jqGridResizeStop.setGroupHeaders",function(e,t,i){D.find("th").eq(i).width(t)})})},setFrozenColumns:function(){return this.each(function(){if(this.grid){var t=this,i=t.p.colModel,r=0,a=i.length,o=-1,s=!1;if(!(t.p.subGrid===!0||t.p.treeGrid===!0||t.p.cellEdit===!0||t.p.sortable||t.p.scroll||t.p.grouping)){for(t.p.rownumbers&&r++,t.p.multiselect&&r++;a>r&&i[r].frozen===!0;)s=!0,o=r,r++;if(o>=0&&s){var n=t.p.caption?e(t.grid.cDiv).outerHeight():0,d=e(".ui-jqgrid-htable","#gview_"+e.jgrid.jqID(t.p.id)).height();t.p.toppager&&(n+=e(t.grid.topDiv).outerHeight()),t.p.toolbar[0]===!0&&"bottom"!=t.p.toolbar[1]&&(n+=e(t.grid.uDiv).outerHeight()),t.grid.fhDiv=e('<div style="position:absolute;left:0px;top:'+n+"px;height:"+d+'px;" class="frozen-div ui-state-default ui-jqgrid-hdiv"></div>'),t.grid.fbDiv=e('<div style="position:absolute;left:0px;top:'+(parseInt(n,10)+parseInt(d,10)+1)+'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>'),e("#gview_"+e.jgrid.jqID(t.p.id)).append(t.grid.fhDiv);var l=e(".ui-jqgrid-htable","#gview_"+e.jgrid.jqID(t.p.id)).clone(!0);if(t.p.groupHeader){e("tr.jqg-first-row-header, tr.jqg-third-row-header",l).each(function(){e("th:gt("+o+")",this).remove()});var p=-1,c=-1;e("tr.jqg-second-row-header th",l).each(function(){var t=parseInt(e(this).attr("colspan"),10);return t&&(p+=t,c++),p===o?!1:void 0}),p!==o&&(c=o),e("tr.jqg-second-row-header",l).each(function(){e("th:gt("+c+")",this).remove()})}else e("tr",l).each(function(){e("th:gt("+o+")",this).remove()});e(l).width(1),e(t.grid.fhDiv).append(l).mousemove(function(e){return t.grid.resizing?(t.grid.dragMove(e),!1):void 0}),e(t).bind("jqGridResizeStop.setFrozenColumns",function(i,r,a){var o=e(".ui-jqgrid-htable",t.grid.fhDiv);e("th:eq("+a+")",o).width(r);var s=e(".ui-jqgrid-btable",t.grid.fbDiv);e("tr:first td:eq("+a+")",s).width(r)}),e(t).bind("jqGridOnSortCol.setFrozenColumns",function(i,r){var a=e("tr.ui-jqgrid-labels:last th:eq("+t.p.lastsort+")",t.grid.fhDiv),o=e("tr.ui-jqgrid-labels:last th:eq("+r+")",t.grid.fhDiv);e("span.ui-grid-ico-sort",a).addClass("ui-state-disabled"),e(a).attr("aria-selected","false"),e("span.ui-icon-"+t.p.sortorder,o).removeClass("ui-state-disabled"),e(o).attr("aria-selected","true"),t.p.viewsortcols[0]||t.p.lastsort!=r&&(e("span.s-ico",a).hide(),e("span.s-ico",o).show())}),e("#gview_"+e.jgrid.jqID(t.p.id)).append(t.grid.fbDiv),jQuery(t.grid.bDiv).scroll(function(){jQuery(t.grid.fbDiv).scrollTop(jQuery(this).scrollTop())}),t.p.hoverrows===!0&&e("#"+e.jgrid.jqID(t.p.id)).unbind("mouseover").unbind("mouseout"),e(t).bind("jqGridAfterGridComplete.setFrozenColumns",function(){e("#"+e.jgrid.jqID(t.p.id)+"_frozen").remove(),jQuery(t.grid.fbDiv).height(jQuery(t.grid.bDiv).height()-16);var i=e("#"+e.jgrid.jqID(t.p.id)).clone(!0);e("tr",i).each(function(){e("td:gt("+o+")",this).remove()}),e(i).width(1).attr("id",t.p.id+"_frozen"),e(t.grid.fbDiv).append(i),t.p.hoverrows===!0&&(e("tr.jqgrow",i).hover(function(){e(this).addClass("ui-state-hover"),e("#"+e.jgrid.jqID(this.id),"#"+e.jgrid.jqID(t.p.id)).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover"),e("#"+e.jgrid.jqID(this.id),"#"+e.jgrid.jqID(t.p.id)).removeClass("ui-state-hover")}),e("tr.jqgrow","#"+e.jgrid.jqID(t.p.id)).hover(function(){e(this).addClass("ui-state-hover"),e("#"+e.jgrid.jqID(this.id),"#"+e.jgrid.jqID(t.p.id)+"_frozen").addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover"),e("#"+e.jgrid.jqID(this.id),"#"+e.jgrid.jqID(t.p.id)+"_frozen").removeClass("ui-state-hover")})),i=null}),t.p.frozenColumns=!0}}}})},destroyFrozenColumns:function(){return this.each(function(){if(this.grid&&this.p.frozenColumns===!0){var t=this;if(e(t.grid.fhDiv).remove(),e(t.grid.fbDiv).remove(),t.grid.fhDiv=null,t.grid.fbDiv=null,e(this).unbind(".setFrozenColumns"),t.p.hoverrows===!0){var i;e("#"+e.jgrid.jqID(t.p.id)).bind("mouseover",function(t){i=e(t.target).closest("tr.jqgrow"),"ui-subgrid"!==e(i).attr("class")&&e(i).addClass("ui-state-hover")}).bind("mouseout",function(t){i=e(t.target).closest("tr.jqgrow"),e(i).removeClass("ui-state-hover")})}this.p.frozenColumns=!1}})}})}(jQuery),/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqmodal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 07/06/2008 +r13
 */
function(e){e.fn.jqm=function(r){var a={overlay:50,closeoverlay:!0,overlayClass:"jqmOverlay",closeClass:"jqmClose",trigger:".jqModal",ajax:o,ajaxText:"",target:o,modal:o,toTop:o,onShow:o,onHide:o,onLoad:o};return this.each(function(){return this._jqm?i[this._jqm].c=e.extend({},i[this._jqm].c,r):(t++,this._jqm=t,i[t]={c:e.extend(a,e.jqm.params,r),a:o,w:e(this).addClass("jqmID"+t),s:t},void(a.trigger&&e(this).jqmAddTrigger(a.trigger)))})},e.fn.jqmAddClose=function(e){return p(this,e,"jqmHide")},e.fn.jqmAddTrigger=function(e){return p(this,e,"jqmShow")},e.fn.jqmShow=function(t){return this.each(function(){e.jqm.open(this._jqm,t)})},e.fn.jqmHide=function(t){return this.each(function(){e.jqm.close(this._jqm,t)})},e.jqm={hash:{},open:function(t,n){var l=i[t],p=l.c,c="."+p.closeClass,u=parseInt(l.w.css("z-index"));u=u>0?u:3e3;var h=e("<div></div>").css({height:"100%",width:"100%",position:"fixed",left:0,top:0,"z-index":u-1,opacity:p.overlay/100});if(l.a)return o;if(l.t=n,l.a=!0,l.w.css("z-index",u),p.modal?(r[0]||setTimeout(function(){d("bind")},1),r.push(t)):p.overlay>0?p.closeoverlay&&l.w.jqmAddClose(h):h=o,l.o=h?h.addClass(p.overlayClass).prependTo("body"):o,a&&(e("html,body").css({height:"100%",width:"100%"}),h)){h=h.css({position:"absolute"})[0];for(var f in{Top:1,Left:1})h.style.setExpression(f.toLowerCase(),"(_=(document.documentElement.scroll"+f+" || document.body.scroll"+f+"))+'px'")}if(p.ajax){var g=p.target||l.w,m=p.ajax;g="string"==typeof g?e(g,l.w):e(g),m="@"==m.substr(0,1)?e(n).attr(m.substring(1)):m,g.html(p.ajaxText).load(m,function(){p.onLoad&&p.onLoad.call(this,l),c&&l.w.jqmAddClose(e(c,l.w)),s(l)})}else c&&l.w.jqmAddClose(e(c,l.w));return p.toTop&&l.o&&l.w.before('<span id="jqmP'+l.w[0]._jqm+'"></span>').insertAfter(l.o),p.onShow?p.onShow(l):l.w.show(),s(l),o},close:function(t){var a=i[t];return a.a?(a.a=o,r[0]&&(r.pop(),r[0]||d("unbind")),a.c.toTop&&a.o&&e("#jqmP"+a.w[0]._jqm).after(a.w).remove(),a.c.onHide?a.c.onHide(a):(a.w.hide(),a.o&&a.o.remove()),o):o},params:{}};var t=0,i=e.jqm.hash,r=[],a=e.browser.msie&&"6.0"==e.browser.version,o=!1,s=function(t){var i=e('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0});a&&(t.o?t.o.html('<p style="width:100%;height:100%"/>').prepend(i):e("iframe.jqm",t.w)[0]||t.w.prepend(i)),n(t)},n=function(t){try{e(":input:visible",t.w)[0].focus()}catch(i){}},d=function(t){e(document)[t]("keypress",l)[t]("keydown",l)[t]("mousedown",l)},l=function(t){var a=i[r[r.length-1]],o=!e(t.target).parents(".jqmID"+a.s)[0];return o&&n(a),!o},p=function(t,r,a){return t.each(function(){var t=this._jqm;e(r).each(function(){this[a]||(this[a]=[],e(this).click(function(){for(var e in{jqmShow:1,jqmHide:1})for(var t in this[e])i[this[e][t]]&&i[this[e][t]].w[e](this);return o})),this[a].push(t)})})}}(jQuery),/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * $Version: 2007.08.19 +r2
 */
function(e){e.fn.jqDrag=function(e){return s(this,e,"d")},e.fn.jqResize=function(e,t){return s(this,e,"r",t)},e.jqDnR={dnr:{},e:0,drag:function(e){return"d"==a.k?o.css({left:a.X+e.pageX-a.pX,top:a.Y+e.pageY-a.pY}):(o.css({width:Math.max(e.pageX-a.pX+a.W,0),height:Math.max(e.pageY-a.pY+a.H,0)}),i&&t.css({width:Math.max(e.pageX-i.pX+i.W,0),height:Math.max(e.pageY-i.pY+i.H,0)})),!1},stop:function(){e(document).unbind("mousemove",r.drag).unbind("mouseup",r.stop)}};var t,i,r=e.jqDnR,a=r.dnr,o=r.e,s=function(r,s,l,p){return r.each(function(){s=s?e(s,r):r,s.bind("mousedown",{e:r,k:l},function(r){var s=r.data,l={};if(o=s.e,t=p?e(p):!1,"relative"!=o.css("position"))try{o.position(l)}catch(c){}if(a={X:l.left||n("left")||0,Y:l.top||n("top")||0,W:n("width")||o[0].scrollWidth||0,H:n("height")||o[0].scrollHeight||0,pX:r.pageX,pY:r.pageY,k:s.k},i=t&&"d"!=s.k?{X:l.left||d("left")||0,Y:l.top||d("top")||0,W:t[0].offsetWidth||d("width")||0,H:t[0].offsetHeight||d("height")||0,pX:r.pageX,pY:r.pageY,k:s.k}:!1,e("input.hasDatepicker",o[0])[0])try{e("input.hasDatepicker",o[0]).datepicker("hide")}catch(u){}return e(document).mousemove(e.jqDnR.drag).mouseup(e.jqDnR.stop),!1})})},n=function(e){return parseInt(o.css(e),10)||!1},d=function(e){return parseInt(t.css(e),10)||!1}}(jQuery);var xmlJsonClass={xml2json:function(e,t){9===e.nodeType&&(e=e.documentElement);var i=this.removeWhite(e),r=this.toObj(i),a=this.toJson(r,e.nodeName,"	");return"{\n"+t+(t?a.replace(/\t/g,t):a.replace(/\t|\n/g,""))+"\n}"},json2xml:function(e,t){var i,r=function(e,t,i){var a,o,s="";if(e instanceof Array)if(0===e.length)s+=i+"<"+t+">__EMPTY_ARRAY_</"+t+">\n";else for(a=0,o=e.length;o>a;a+=1){var n=i+r(e[a],t,i+"	")+"\n";s+=n}else if("object"==typeof e){var d=!1;s+=i+"<"+t;var l;for(l in e)e.hasOwnProperty(l)&&("@"===l.charAt(0)?s+=" "+l.substr(1)+'="'+e[l].toString()+'"':d=!0);if(s+=d?">":"/>",d){for(l in e)e.hasOwnProperty(l)&&("#text"===l?s+=e[l]:"#cdata"===l?s+="<![CDATA["+e[l]+"]]>":"@"!==l.charAt(0)&&(s+=r(e[l],l,i+"	")));s+=("\n"===s.charAt(s.length-1)?i:"")+"</"+t+">"}}else"function"==typeof e?s+=i+"<"+t+"><![CDATA["+e+"]]></"+t+">":(void 0===e&&(e=""),s+='""'===e.toString()||0===e.toString().length?i+"<"+t+">__EMPTY_STRING_</"+t+">":i+"<"+t+">"+e.toString()+"</"+t+">");return s},a="";for(i in e)e.hasOwnProperty(i)&&(a+=r(e[i],i,""));return t?a.replace(/\t/g,t):a.replace(/\t|\n/g,"")},toObj:function(e){var t={},i=/function/i;if(1===e.nodeType){if(e.attributes.length){var r;for(r=0;r<e.attributes.length;r+=1)t["@"+e.attributes[r].nodeName]=(e.attributes[r].nodeValue||"").toString()}if(e.firstChild){var a,o=0,s=0,n=!1;for(a=e.firstChild;a;a=a.nextSibling)1===a.nodeType?n=!0:3===a.nodeType&&a.nodeValue.match(/[^ \f\n\r\t\v]/)?o+=1:4===a.nodeType&&(s+=1);if(n)if(2>o&&2>s)for(this.removeWhite(e),a=e.firstChild;a;a=a.nextSibling)3===a.nodeType?t["#text"]=this.escape(a.nodeValue):4===a.nodeType?i.test(a.nodeValue)?t[a.nodeName]=[t[a.nodeName],a.nodeValue]:t["#cdata"]=this.escape(a.nodeValue):t[a.nodeName]?t[a.nodeName]instanceof Array?t[a.nodeName][t[a.nodeName].length]=this.toObj(a):t[a.nodeName]=[t[a.nodeName],this.toObj(a)]:t[a.nodeName]=this.toObj(a);else e.attributes.length?t["#text"]=this.escape(this.innerXml(e)):t=this.escape(this.innerXml(e));else if(o)e.attributes.length?t["#text"]=this.escape(this.innerXml(e)):(t=this.escape(this.innerXml(e)),"__EMPTY_ARRAY_"===t?t="[]":"__EMPTY_STRING_"===t&&(t=""));else if(s)if(s>1)t=this.escape(this.innerXml(e));else for(a=e.firstChild;a;a=a.nextSibling){if(i.test(e.firstChild.nodeValue)){t=e.firstChild.nodeValue;break}t["#cdata"]=this.escape(a.nodeValue)}}e.attributes.length||e.firstChild||(t=null)}else 9===e.nodeType?t=this.toObj(e.documentElement):alert("unhandled node type: "+e.nodeType);return t},toJson:function(e,t,i,r){void 0===r&&(r=!0);var a=t?'"'+t+'"':"",o="	",s="\n";if(r||(o="",s=""),"[]"===e)a+=t?":[]":"[]";else if(e instanceof Array){var n,d,l=[];for(d=0,n=e.length;n>d;d+=1)l[d]=this.toJson(e[d],"",i+o,r);a+=(t?":[":"[")+(l.length>1?s+i+o+l.join(","+s+i+o)+s+i:l.join(""))+"]"}else if(null===e)a+=(t&&":")+"null";else if("object"==typeof e){var p,c=[];for(p in e)e.hasOwnProperty(p)&&(c[c.length]=this.toJson(e[p],p,i+o,r));a+=(t?":{":"{")+(c.length>1?s+i+o+c.join(","+s+i+o)+s+i:c.join(""))+"}"}else a+="string"==typeof e?(t&&":")+'"'+e.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"':(t&&":")+e.toString();return a},innerXml:function(e){var t="";if("innerHTML"in e)t=e.innerHTML;else for(var i=function(e){var t,r="";if(1===e.nodeType){for(r+="<"+e.nodeName,t=0;t<e.attributes.length;t+=1)r+=" "+e.attributes[t].nodeName+'="'+(e.attributes[t].nodeValue||"").toString()+'"';if(e.firstChild){r+=">";for(var a=e.firstChild;a;a=a.nextSibling)r+=i(a);r+="</"+e.nodeName+">"}else r+="/>"}else 3===e.nodeType?r+=e.nodeValue:4===e.nodeType&&(r+="<![CDATA["+e.nodeValue+"]]>");return r},r=e.firstChild;r;r=r.nextSibling)t+=i(r);return t},escape:function(e){return e.replace(/[\\]/g,"\\\\").replace(/[\"]/g,'\\"').replace(/[\n]/g,"\\n").replace(/[\r]/g,"\\r")},removeWhite:function(e){e.normalize();var t;for(t=e.firstChild;t;)if(3===t.nodeType)if(t.nodeValue.match(/[^ \f\n\r\t\v]/))t=t.nextSibling;else{var i=t.nextSibling;e.removeChild(t),t=i}else 1===t.nodeType?(this.removeWhite(t),t=t.nextSibling):t=t.nextSibling;return e}};!function(e){"use strict";e.fmatter={},e.extend(e.fmatter,{isBoolean:function(e){return"boolean"==typeof e},isObject:function(t){return t&&("object"==typeof t||e.isFunction(t))||!1},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e&&isFinite(e)},isNull:function(e){return null===e},isUndefined:function(e){return"undefined"==typeof e},isValue:function(e){return this.isObject(e)||this.isString(e)||this.isNumber(e)||this.isBoolean(e)},isEmpty:function(t){return!this.isString(t)&&this.isValue(t)?!1:this.isValue(t)?(t=e.trim(t).replace(/\&nbsp\;/gi,"").replace(/\&#160\;/gi,""),""===t):!0}}),e.fn.fmatter=function(t,i,r,a,o){var s=i;r=e.extend({},e.jgrid.formatter,r);try{s=e.fn.fmatter[t].call(this,i,r,a,o)}catch(n){}return s},e.fmatter.util={NumberFormat:function(t,i){if(e.fmatter.isNumber(t)||(t*=1),e.fmatter.isNumber(t)){var r,a=0>t,o=t+"",s=i.decimalSeparator?i.decimalSeparator:".";if(e.fmatter.isNumber(i.decimalPlaces)){var n=i.decimalPlaces,d=Math.pow(10,n);if(o=Math.round(t*d)/d+"",r=o.lastIndexOf("."),n>0)for(0>r?(o+=s,r=o.length-1):"."!==s&&(o=o.replace(".",s));o.length-1-r<n;)o+="0"}if(i.thousandsSeparator){var l=i.thousandsSeparator;r=o.lastIndexOf(s),r=r>-1?r:o.length;for(var p=o.substring(r),c=-1,u=r;u>0;u--)c++,c%3===0&&u!==r&&(!a||u>1)&&(p=l+p),p=o.charAt(u-1)+p;o=p}return o=i.prefix?i.prefix+o:o,o=i.suffix?o+i.suffix:o}return t},DateFormat:function(t,i,r,a){var o,s,n,d=/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,l=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,p=/[^-+\dA-Z]/g,c=new RegExp("^/Date\\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\\)/$"),u="string"==typeof i?i.match(c):null,h=function(e,t){for(e=String(e),t=parseInt(t,10)||2;e.length<t;)e="0"+e;return e},f={m:1,d:1,y:1970,h:0,i:0,s:0,u:0},g=0,m=["i18n"];if(m.i18n={dayNames:a.dayNames,monthNames:a.monthNames},t in a.masks&&(t=a.masks[t]),isNaN(i-0)||"u"!=String(t).toLowerCase())if(i.constructor===Date)g=i;else if(null!=u){if(g=new Date(parseInt(u[1],10)),u[3]){var v=60*Number(u[5])+Number(u[6]);v*="-"==u[4]?1:-1,v-=g.getTimezoneOffset(),g.setTime(Number(Number(g)+60*v*1e3))}}else{for(i=String(i).split(/[\\\/:_;.,\t\T\s-]/),t=t.split(/[\\\/:_;.,\t\T\s-]/),s=0,n=t.length;n>s;s++)"M"==t[s]&&(o=e.inArray(i[s],m.i18n.monthNames),-1!==o&&12>o&&(i[s]=o+1)),"F"==t[s]&&(o=e.inArray(i[s],m.i18n.monthNames),-1!==o&&o>11&&(i[s]=o+1-12)),i[s]&&(f[t[s].toLowerCase()]=parseInt(i[s],10));if(f.f&&(f.m=f.f),0===f.m&&0===f.y&&0===f.d)return"&#160;";f.m=parseInt(f.m,10)-1;var j=f.y;j>=70&&99>=j?f.y=1900+f.y:j>=0&&69>=j&&(f.y=2e3+f.y),g=new Date(f.y,f.m,f.d,f.h,f.i,f.s,f.u)}else g=new Date(1e3*parseFloat(i));r in a.masks?r=a.masks[r]:r||(r="Y-m-d");var b=g.getHours(),w=g.getMinutes(),y=g.getDate(),q=g.getMonth()+1,x=g.getTimezoneOffset(),D=g.getSeconds(),$=g.getMilliseconds(),_=g.getDay(),C=g.getFullYear(),I=(_+6)%7+1,G=(new Date(C,q-1,y)-new Date(C,0,1))/864e5,F={d:h(y),D:m.i18n.dayNames[_],j:y,l:m.i18n.dayNames[_+7],N:I,S:a.S(y),w:_,z:G,W:5>I?Math.floor((G+I-1)/7)+1:Math.floor((G+I-1)/7)||((new Date(C-1,0,1).getDay()+6)%7<4?53:52),F:m.i18n.monthNames[q-1+12],m:h(q),M:m.i18n.monthNames[q-1],n:q,t:"?",L:"?",o:"?",Y:C,y:String(C).substring(2),a:12>b?a.AmPm[0]:a.AmPm[1],A:12>b?a.AmPm[2]:a.AmPm[3],B:"?",g:b%12||12,G:b,h:h(b%12||12),H:h(b),i:h(w),s:h(D),u:$,e:"?",I:"?",O:(x>0?"-":"+")+h(100*Math.floor(Math.abs(x)/60)+Math.abs(x)%60,4),P:"?",T:(String(g).match(l)||[""]).pop().replace(p,""),Z:"?",c:"?",r:"?",U:Math.floor(g/1e3)};return r.replace(d,function(e){return e in F?F[e]:e.substring(1)})}},e.fn.fmatter.defaultFormat=function(t,i){return e.fmatter.isValue(t)&&""!==t?t:i.defaultValue?i.defaultValue:"&#160;"},e.fn.fmatter.email=function(t,i){return e.fmatter.isEmpty(t)?e.fn.fmatter.defaultFormat(t,i):'<a href="mailto:'+t+'">'+t+"</a>"},e.fn.fmatter.checkbox=function(t,i){var r,a=e.extend({},i.checkbox);void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(a=e.extend({},a,i.colModel.formatoptions)),r=a.disabled===!0?'disabled="disabled"':"",(e.fmatter.isEmpty(t)||e.fmatter.isUndefined(t))&&(t=e.fn.fmatter.defaultFormat(t,a)),t+="",t=t.toLowerCase();var o=t.search(/(false|0|no|off)/i)<0?" checked='checked' ":"";return'<input type="checkbox" '+o+' value="'+t+'" offval="no" '+r+"/>"},e.fn.fmatter.link=function(t,i){var r={target:i.target},a="";return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(r=e.extend({},r,i.colModel.formatoptions)),r.target&&(a="target="+r.target),e.fmatter.isEmpty(t)?e.fn.fmatter.defaultFormat(t,i):"<a "+a+' href="'+t+'">'+t+"</a>"},e.fn.fmatter.showlink=function(t,i){var r,a={baseLinkUrl:i.baseLinkUrl,showAction:i.showAction,addParam:i.addParam||"",target:i.target,idName:i.idName},o="";return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(a=e.extend({},a,i.colModel.formatoptions)),a.target&&(o="target="+a.target),r=a.baseLinkUrl+a.showAction+"?"+a.idName+"="+i.rowId+a.addParam,e.fmatter.isString(t)||e.fmatter.isNumber(t)?"<a "+o+' href="'+r+'">'+t+"</a>":e.fn.fmatter.defaultFormat(t,i)},e.fn.fmatter.integer=function(t,i){var r=e.extend({},i.integer);return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(r=e.extend({},r,i.colModel.formatoptions)),e.fmatter.isEmpty(t)?r.defaultValue:e.fmatter.util.NumberFormat(t,r)},e.fn.fmatter.number=function(t,i){var r=e.extend({},i.number);return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(r=e.extend({},r,i.colModel.formatoptions)),e.fmatter.isEmpty(t)?r.defaultValue:e.fmatter.util.NumberFormat(t,r)},e.fn.fmatter.currency=function(t,i){var r=e.extend({},i.currency);return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(r=e.extend({},r,i.colModel.formatoptions)),e.fmatter.isEmpty(t)?r.defaultValue:e.fmatter.util.NumberFormat(t,r)},e.fn.fmatter.date=function(t,i,r,a){var o=e.extend({},i.date);return void 0===i.colModel||e.fmatter.isUndefined(i.colModel.formatoptions)||(o=e.extend({},o,i.colModel.formatoptions)),o.reformatAfterEdit||"edit"!=a?e.fmatter.isEmpty(t)?e.fn.fmatter.defaultFormat(t,i):e.fmatter.util.DateFormat(o.srcformat,t,o.newformat,o):e.fn.fmatter.defaultFormat(t,i)},e.fn.fmatter.select=function(t,i){t+="";var r,a,o=!1,s=[];if(e.fmatter.isUndefined(i.colModel.formatoptions)?e.fmatter.isUndefined(i.colModel.editoptions)||(o=i.colModel.editoptions.value,r=void 0===i.colModel.editoptions.separator?":":i.colModel.editoptions.separator,a=void 0===i.colModel.editoptions.delimiter?";":i.colModel.editoptions.delimiter):(o=i.colModel.formatoptions.value,r=void 0===i.colModel.formatoptions.separator?":":i.colModel.formatoptions.separator,a=void 0===i.colModel.formatoptions.delimiter?";":i.colModel.formatoptions.delimiter),o){var n,d=i.colModel.editoptions.multiple===!0?!0:!1,l=[];if(d&&(l=t.split(","),l=e.map(l,function(t){return e.trim(t)})),e.fmatter.isString(o)){for(var p=o.split(a),c=0,u=0;u<p.length;u++)if(n=p[u].split(r),n.length>2&&(n[1]=e.map(n,function(e,t){return t>0?e:void 0}).join(r)),d)e.inArray(n[0],l)>-1&&(s[c]=n[1],c++);else if(e.trim(n[0])==e.trim(t)){s[0]=n[1];break}}else e.fmatter.isObject(o)&&(d?s=e.map(l,function(e){return o[e]}):s[0]=o[t]||"")}return t=s.join(", "),""===t?e.fn.fmatter.defaultFormat(t,i):t},e.fn.fmatter.rowactions=function(t,i,r,a){var o={keys:!1,onEdit:null,onSuccess:null,afterSave:null,onError:null,afterRestore:null,extraparam:{},url:null,restoreAfterError:!0,mtype:"POST",delOptions:{},editOptions:{}};t=e.jgrid.jqID(t),i=e.jgrid.jqID(i);var s=e("#"+i)[0].p.colModel[a];e.fmatter.isUndefined(s.formatoptions)||(o=e.extend(o,s.formatoptions)),e.fmatter.isUndefined(e("#"+i)[0].p.editOptions)||(o.editOptions=e("#"+i)[0].p.editOptions),e.fmatter.isUndefined(e("#"+i)[0].p.delOptions)||(o.delOptions=e("#"+i)[0].p.delOptions);var n=e("#"+i)[0],d=function(r,a){e.isFunction(o.afterSave)&&o.afterSave.call(n,r,a),e("tr#"+t+" div.ui-inline-edit, tr#"+t+" div.ui-inline-del","#"+i+".ui-jqgrid-btable:first").show(),e("tr#"+t+" div.ui-inline-save, tr#"+t+" div.ui-inline-cancel","#"+i+".ui-jqgrid-btable:first").hide()},l=function(r){e.isFunction(o.afterRestore)&&o.afterRestore.call(n,r),e("tr#"+t+" div.ui-inline-edit, tr#"+t+" div.ui-inline-del","#"+i+".ui-jqgrid-btable:first").show(),e("tr#"+t+" div.ui-inline-save, tr#"+t+" div.ui-inline-cancel","#"+i+".ui-jqgrid-btable:first").hide()};if(e("#"+t,"#"+i).hasClass("jqgrid-new-row")){var p=n.p.prmNames,c=p.oper;o.extraparam[c]=p.addoper}var u={keys:o.keys,oneditfunc:o.onEdit,successfunc:o.onSuccess,url:o.url,extraparam:o.extraparam,aftersavefunc:d,errorfunc:o.onError,afterrestorefunc:l,restoreAfterError:o.restoreAfterError,mtype:o.mtype};switch(r){case"edit":e("#"+i).jqGrid("editRow",t,u),e("tr#"+t+" div.ui-inline-edit, tr#"+t+" div.ui-inline-del","#"+i+".ui-jqgrid-btable:first").hide(),e("tr#"+t+" div.ui-inline-save, tr#"+t+" div.ui-inline-cancel","#"+i+".ui-jqgrid-btable:first").show(),e(n).triggerHandler("jqGridAfterGridComplete");break;case"save":e("#"+i).jqGrid("saveRow",t,u)&&(e("tr#"+t+" div.ui-inline-edit, tr#"+t+" div.ui-inline-del","#"+i+".ui-jqgrid-btable:first").show(),e("tr#"+t+" div.ui-inline-save, tr#"+t+" div.ui-inline-cancel","#"+i+".ui-jqgrid-btable:first").hide(),e(n).triggerHandler("jqGridAfterGridComplete"));break;case"cancel":e("#"+i).jqGrid("restoreRow",t,l),e("tr#"+t+" div.ui-inline-edit, tr#"+t+" div.ui-inline-del","#"+i+".ui-jqgrid-btable:first").show(),e("tr#"+t+" div.ui-inline-save, tr#"+t+" div.ui-inline-cancel","#"+i+".ui-jqgrid-btable:first").hide(),e(n).triggerHandler("jqGridAfterGridComplete");break;case"del":e("#"+i).jqGrid("delGridRow",t,o.delOptions);break;case"formedit":e("#"+i).jqGrid("setSelection",t),e("#"+i).jqGrid("editGridRow",t,o.editOptions)}},e.fn.fmatter.actions=function(t,i){var r={keys:!1,editbutton:!0,delbutton:!0,editformbutton:!1};e.fmatter.isUndefined(i.colModel.formatoptions)||(r=e.extend(r,i.colModel.formatoptions));var a,o=i.rowId,s="";return"undefined"==typeof o||e.fmatter.isEmpty(o)?"":(r.editformbutton?(a="onclick=jQuery.fn.fmatter.rowactions('"+o+"','"+i.gid+"','formedit',"+i.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ",s=s+"<div title='"+e.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+a+"><span class='ui-icon ui-icon-pencil'></span></div>"):r.editbutton&&(a="onclick=jQuery.fn.fmatter.rowactions('"+o+"','"+i.gid+"','edit',"+i.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover') ",s=s+"<div title='"+e.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+a+"><span class='ui-icon ui-icon-pencil'></span></div>"),r.delbutton&&(a="onclick=jQuery.fn.fmatter.rowactions('"+o+"','"+i.gid+"','del',"+i.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ",s=s+"<div title='"+e.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+a+"><span class='ui-icon ui-icon-trash'></span></div>"),a="onclick=jQuery.fn.fmatter.rowactions('"+o+"','"+i.gid+"','save',"+i.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ",s=s+"<div title='"+e.jgrid.edit.bSubmit+"' style='float:left;display:none' class='ui-pg-div ui-inline-save' "+a+"><span class='ui-icon ui-icon-disk'></span></div>",a="onclick=jQuery.fn.fmatter.rowactions('"+o+"','"+i.gid+"','cancel',"+i.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ",s=s+"<div title='"+e.jgrid.edit.bCancel+"' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel' "+a+"><span class='ui-icon ui-icon-cancel'></span></div>","<div style='margin-left:8px;'>"+s+"</div>")},e.unformat=function(t,i,r,a){var o,s,n=i.colModel.formatter,d=i.colModel.formatoptions||{},l=/([\.\*\_\'\(\)\{\}\+\?\\])/g,p=i.colModel.unformat||e.fn.fmatter[n]&&e.fn.fmatter[n].unformat;if("undefined"!=typeof p&&e.isFunction(p))o=p.call(this,e(t).text(),i,t);else if(!e.fmatter.isUndefined(n)&&e.fmatter.isString(n)){var c,u=e.jgrid.formatter||{};switch(n){case"integer":d=e.extend({},u.integer,d),s=d.thousandsSeparator.replace(l,"\\$1"),c=new RegExp(s,"g"),o=e(t).text().replace(c,"");break;case"number":d=e.extend({},u.number,d),s=d.thousandsSeparator.replace(l,"\\$1"),c=new RegExp(s,"g"),o=e(t).text().replace(c,"").replace(d.decimalSeparator,".");break;case"currency":d=e.extend({},u.currency,d),s=d.thousandsSeparator.replace(l,"\\$1"),c=new RegExp(s,"g"),o=e(t).text(),d.prefix&&d.prefix.length&&(o=o.substr(d.prefix.length)),d.suffix&&d.suffix.length&&(o=o.substr(0,o.length-d.suffix.length)),o=o.replace(c,"").replace(d.decimalSeparator,".");break;case"checkbox":var h=i.colModel.editoptions?i.colModel.editoptions.value.split(":"):["Yes","No"];o=e("input",t).is(":checked")?h[0]:h[1];break;case"select":o=e.unformat.select(t,i,r,a);break;case"actions":return"";default:o=e(t).text()}}return void 0!==o?o:a===!0?e(t).text():e.jgrid.htmlDecode(e(t).html())},e.unformat.select=function(t,i,r,a){var o=[],s=e(t).text();if(a===!0)return s;var n=e.extend({},e.fmatter.isUndefined(i.colModel.formatoptions)?i.colModel.editoptions:i.colModel.formatoptions),d=void 0===n.separator?":":n.separator,l=void 0===n.delimiter?";":n.delimiter;if(n.value){var p,c=n.value,u=n.multiple===!0?!0:!1,h=[];if(u&&(h=s.split(","),h=e.map(h,function(t){return e.trim(t)})),e.fmatter.isString(c)){for(var f=c.split(l),g=0,m=0;m<f.length;m++)if(p=f[m].split(d),p.length>2&&(p[1]=e.map(p,function(e,t){return t>0?e:void 0}).join(d)),u)e.inArray(p[1],h)>-1&&(o[g]=p[0],g++);else if(e.trim(p[1])==e.trim(s)){o[0]=p[0];break}}else(e.fmatter.isObject(c)||e.isArray(c))&&(u||(h[0]=s),o=e.map(h,function(t){var i;return e.each(c,function(e,r){return r==t?(i=e,!1):void 0}),"undefined"!=typeof i?i:void 0}));return o.join(", ")}return s||""},e.unformat.date=function(t,i){var r=e.jgrid.formatter.date||{};return e.fmatter.isUndefined(i.formatoptions)||(r=e.extend({},r,i.formatoptions)),e.fmatter.isEmpty(t)?e.fn.fmatter.defaultFormat(t,i):e.fmatter.util.DateFormat(r.newformat,t,r.srcformat,r)}}(jQuery),function(e){e.extend(e.jgrid,{showModal:function(e){e.w.show()},closeModal:function(e){e.w.hide().attr("aria-hidden","true"),e.o&&e.o.remove()},hideModal:function(t,i){if(i=e.extend({jqm:!0,gb:""},i||{}),i.onClose){var r=i.onClose(t);if("boolean"==typeof r&&!r)return}if(e.fn.jqm&&i.jqm===!0)e(t).attr("aria-hidden","true").jqmHide();else{if(""!==i.gb)try{e(".jqgrid-overlay:first",i.gb).hide()}catch(a){}e(t).hide().attr("aria-hidden","true")}},findPos:function(e){var t=0,i=0;if(e.offsetParent)do t+=e.offsetLeft,i+=e.offsetTop;while(e=e.offsetParent);return[t,i]},createModal:function(t,i,r,a,o,s,n){var d,l=document.createElement("div"),p=this;n=e.extend({},n||{}),d="rtl"==e(r.gbox).attr("dir")?!0:!1,l.className="ui-widget ui-widget-content ui-corner-all ui-jqdialog",l.id=t.themodal;var c=document.createElement("div");c.className="ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix",c.id=t.modalhead,e(c).append("<span class='ui-jqdialog-title'>"+r.caption+"</span>");var u=e("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function(){u.addClass("ui-state-hover")},function(){u.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-closethick'></span>");e(c).append(u),d?(l.dir="rtl",e(".ui-jqdialog-title",c).css("float","right"),e(".ui-jqdialog-titlebar-close",c).css("left","0.3em")):(l.dir="ltr",e(".ui-jqdialog-title",c).css("float","left"),e(".ui-jqdialog-titlebar-close",c).css("right","0.3em"));var h=document.createElement("div");e(h).addClass("ui-jqdialog-content ui-widget-content").attr("id",t.modalcontent),e(h).append(i),l.appendChild(h),e(l).prepend(c),s===!0?e("body").append(l):"string"==typeof s?e(s).append(l):e(l).insertBefore(a),e(l).css(n),"undefined"==typeof r.jqModal&&(r.jqModal=!0);var f={};if(e.fn.jqm&&r.jqModal===!0){if(0===r.left&&0===r.top&&r.overlay){var g=[];g=e.jgrid.findPos(o),r.left=g[0]+4,r.top=g[1]+4}f.top=r.top+"px",f.left=r.left}else(0!==r.left||0!==r.top)&&(f.left=r.left,f.top=r.top+"px");if(e("a.ui-jqdialog-titlebar-close",c).click(function(){var i=e("#"+e.jgrid.jqID(t.themodal)).data("onClose")||r.onClose,a=e("#"+e.jgrid.jqID(t.themodal)).data("gbox")||r.gbox;return p.hideModal("#"+e.jgrid.jqID(t.themodal),{gb:a,jqm:r.jqModal,onClose:i}),!1}),0!==r.width&&r.width||(r.width=300),0!==r.height&&r.height||(r.height=200),!r.zIndex){var m=e(a).parents("*[role=dialog]").filter(":first").css("z-index");m?r.zIndex=parseInt(m,10)+2:r.zIndex=950}var v=0;if(d&&f.left&&!s&&(v=e(r.gbox).width()-(isNaN(r.width)?0:parseInt(r.width,10))-8,f.left=parseInt(f.left,10)+parseInt(v,10)),f.left&&(f.left+="px"),e(l).css(e.extend({width:isNaN(r.width)?"auto":r.width+"px",height:isNaN(r.height)?"auto":r.height+"px",zIndex:r.zIndex,overflow:"hidden"},f)).attr({tabIndex:"-1",role:"dialog","aria-labelledby":t.modalhead,"aria-hidden":"true"}),"undefined"==typeof r.drag&&(r.drag=!0),"undefined"==typeof r.resize&&(r.resize=!0),r.drag)if(e(c).css("cursor","move"),e.fn.jqDrag)e(l).jqDrag(c);else try{e(l).draggable({handle:e("#"+e.jgrid.jqID(c.id))})}catch(j){}if(r.resize)if(e.fn.jqResize)e(l).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>"),e("#"+e.jgrid.jqID(t.themodal)).jqResize(".jqResize",t.scrollelm?"#"+e.jgrid.jqID(t.scrollelm):!1);else try{e(l).resizable({handles:"se, sw",alsoResize:t.scrollelm?"#"+e.jgrid.jqID(t.scrollelm):!1})}catch(b){}r.closeOnEscape===!0&&e(l).keydown(function(i){if(27==i.which){var a=e("#"+e.jgrid.jqID(t.themodal)).data("onClose")||r.onClose;p.hideModal(this,{gb:r.gbox,jqm:r.jqModal,onClose:a})}})},viewModal:function(t,i){if(i=e.extend({toTop:!0,overlay:10,modal:!1,overlayClass:"ui-widget-overlay",onShow:e.jgrid.showModal,onHide:e.jgrid.closeModal,gbox:"",jqm:!0,jqM:!0},i||{}),e.fn.jqm&&i.jqm===!0)i.jqM?e(t).attr("aria-hidden","false").jqm(i).jqmShow():e(t).attr("aria-hidden","false").jqmShow();else{""!==i.gbox&&(e(".jqgrid-overlay:first",i.gbox).show(),e(t).data("gbox",i.gbox)),e(t).show().attr("aria-hidden","false");try{e(":input:visible",t)[0].focus()}catch(r){}}},info_dialog:function(t,i,r,a){var o={width:290,height:"auto",dataheight:"auto",drag:!0,resize:!1,caption:"<b>"+t+"</b>",left:250,top:170,zIndex:1e3,jqModal:!0,modal:!1,closeOnEscape:!0,align:"center",buttonalign:"center",buttons:[]};e.extend(o,a||{});var s=o.jqModal,n=this;e.fn.jqm&&!s&&(s=!1);var d="";if(o.buttons.length>0)for(var l=0;l<o.buttons.length;l++)"undefined"==typeof o.buttons[l].id&&(o.buttons[l].id="info_button_"+l),d+="<a href='javascript:void(0)' id='"+o.buttons[l].id+"' class='fm-button ui-state-default ui-corner-all'>"+o.buttons[l].text+"</a>";var p=isNaN(o.dataheight)?o.dataheight:o.dataheight+"px",c="text-align:"+o.align+";",u="<div id='info_id'>";u+="<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+p+";"+c+"'>"+i+"</div>",u+=r?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+o.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>"+r+"</a>"+d+"</div>":""!==d?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+o.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+d+"</div>":"",u+="</div>";try{"false"==e("#info_dialog").attr("aria-hidden")&&e.jgrid.hideModal("#info_dialog",{jqm:s}),e("#info_dialog").remove()}catch(h){}e.jgrid.createModal({themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content",scrollelm:"infocnt"},u,o,"","",!0),d&&e.each(o.buttons,function(t){e("#"+e.jgrid.jqID(this.id),"#info_id").bind("click",function(){return o.buttons[t].onClick.call(e("#info_dialog")),!1})}),e("#closedialog","#info_id").click(function(){return n.hideModal("#info_dialog",{jqm:s}),!1}),e(".fm-button","#info_dialog").hover(function(){e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),e.isFunction(o.beforeOpen)&&o.beforeOpen(),e.jgrid.viewModal("#info_dialog",{onHide:function(e){e.w.hide().remove(),e.o&&e.o.remove()},modal:o.modal,jqm:s}),e.isFunction(o.afterOpen)&&o.afterOpen();try{e("#info_dialog").focus()}catch(f){}},createEl:function(t,i,r,a,o){function s(t,i){return e.isFunction(i.dataInit)&&i.dataInit.call(l,t),i.dataEvents&&e.each(i.dataEvents,function(){void 0!==this.data?e(t).bind(this.type,this.data,this.fn):e(t).bind(this.type,this.fn)}),i}function n(t,i,r){var a=["dataInit","dataEvents","dataUrl","buildSelect","sopt","searchhidden","defaultValue","attr"];"undefined"!=typeof r&&e.isArray(r)&&e.merge(a,r),e.each(i,function(i,r){-1===e.inArray(i,a)&&e(t).attr(i,r)}),i.hasOwnProperty("id")||e(t).attr("id",e.jgrid.randId())}var d="",l=this;switch(t){case"textarea":d=document.createElement("textarea"),a?i.cols||e(d).css({width:"98%"}):i.cols||(i.cols=20),i.rows||(i.rows=2),("&nbsp;"==r||"&#160;"==r||1==r.length&&160==r.charCodeAt(0))&&(r=""),d.value=r,n(d,i),i=s(d,i),e(d).attr({role:"textbox",multiline:"true"});break;case"checkbox":if(d=document.createElement("input"),d.type="checkbox",i.value){var p=i.value.split(":");r===p[0]&&(d.checked=!0,d.defaultChecked=!0),d.value=p[0],e(d).attr("offval",p[1])}else{var c=r.toLowerCase();c.search(/(false|0|no|off|undefined)/i)<0&&""!==c?(d.checked=!0,d.defaultChecked=!0,d.value=r):d.value="on",e(d).attr("offval","off")}n(d,i,["value"]),i=s(d,i),e(d).attr("role","checkbox");break;case"select":d=document.createElement("select"),d.setAttribute("role","select");var u,h=[];if(i.multiple===!0?(u=!0,d.multiple="multiple",e(d).attr("aria-multiselectable","true")):u=!1,"undefined"!=typeof i.dataUrl)e.ajax(e.extend({url:i.dataUrl,type:"GET",dataType:"html",context:{elem:d,options:i,vl:r},success:function(t){var i,r=[],a=this.elem,o=this.vl,d=e.extend({},this.options),p=d.multiple===!0;if(e.isFunction(d.buildSelect)){var c=d.buildSelect.call(l,t);i=e(c).html()}else i=e(t).html();i&&(e(a).append(i),n(a,d),d=s(a,d),"undefined"==typeof d.size&&(d.size=p?3:1),p?(r=o.split(","),r=e.map(r,function(t){return e.trim(t)})):r[0]=e.trim(o),setTimeout(function(){e("option",a).each(function(t){0===t&&a.multiple&&(this.selected=!1),e(this).attr("role","option"),(e.inArray(e.trim(e(this).text()),r)>-1||e.inArray(e.trim(e(this).val()),r)>-1)&&(this.selected="selected")})},0))}},o||{}));else if(i.value){var f;"undefined"==typeof i.size&&(i.size=u?3:1),u&&(h=r.split(","),h=e.map(h,function(t){return e.trim(t)})),"function"==typeof i.value&&(i.value=i.value());var g,m,v,j=void 0===i.separator?":":i.separator,b=void 0===i.delimiter?";":i.delimiter;if("string"==typeof i.value)for(g=i.value.split(b),f=0;f<g.length;f++)m=g[f].split(j),m.length>2&&(m[1]=e.map(m,function(e,t){return t>0?e:void 0}).join(j)),v=document.createElement("option"),v.setAttribute("role","option"),v.value=m[0],v.innerHTML=m[1],d.appendChild(v),u||e.trim(m[0])!=e.trim(r)&&e.trim(m[1])!=e.trim(r)||(v.selected="selected"),u&&(e.inArray(e.trim(m[1]),h)>-1||e.inArray(e.trim(m[0]),h)>-1)&&(v.selected="selected");else if("object"==typeof i.value){var w=i.value;for(var y in w)w.hasOwnProperty(y)&&(v=document.createElement("option"),v.setAttribute("role","option"),v.value=y,v.innerHTML=w[y],d.appendChild(v),u||e.trim(y)!=e.trim(r)&&e.trim(w[y])!=e.trim(r)||(v.selected="selected"),u&&(e.inArray(e.trim(w[y]),h)>-1||e.inArray(e.trim(y),h)>-1)&&(v.selected="selected"))}n(d,i,["value"]),i=s(d,i)}break;case"text":case"password":case"button":var q;q="button"==t?"button":"textbox",d=document.createElement("input"),d.type=t,d.value=r,n(d,i),i=s(d,i),"button"!=t&&(a?i.size||e(d).css({width:"98%"}):i.size||(i.size=20)),e(d).attr("role",q);break;case"image":case"file":d=document.createElement("input"),d.type=t,n(d,i),i=s(d,i);break;case"custom":d=document.createElement("span");try{if(!e.isFunction(i.custom_element))throw"e1";var x=i.custom_element.call(l,r,i);if(!x)throw"e2";x=e(x).addClass("customelement").attr({id:i.id,name:i.name}),e(d).empty().append(x)}catch(D){"e1"==D&&e.jgrid.info_dialog(e.jgrid.errors.errcap,"function 'custom_element' "+e.jgrid.edit.msg.nodefined,e.jgrid.edit.bClose),"e2"==D?e.jgrid.info_dialog(e.jgrid.errors.errcap,"function 'custom_element' "+e.jgrid.edit.msg.novalue,e.jgrid.edit.bClose):e.jgrid.info_dialog(e.jgrid.errors.errcap,"string"==typeof D?D:D.message,e.jgrid.edit.bClose)}}return d},checkDate:function(e,t){var i,r=function(e){return e%4!==0||e%100===0&&e%400!==0?28:29},a=function(e){for(var t=1;e>=t;t++)this[t]=31,(4==t||6==t||9==t||11==t)&&(this[t]=30),2==t&&(this[t]=29);return this},o={};if(e=e.toLowerCase(),i=-1!=e.indexOf("/")?"/":-1!=e.indexOf("-")?"-":-1!=e.indexOf(".")?".":"/",e=e.split(i),t=t.split(i),3!=t.length)return!1;for(var s,n=-1,d=-1,l=-1,p=0;p<e.length;p++){var c=isNaN(t[p])?0:parseInt(t[p],10);o[e[p]]=c,s=e[p],-1!=s.indexOf("y")&&(n=p),-1!=s.indexOf("m")&&(l=p),-1!=s.indexOf("d")&&(d=p)}s="y"==e[n]||"yyyy"==e[n]?4:"yy"==e[n]?2:-1;var u,h=a(12);return-1===n?!1:(u=o[e[n]].toString(),2==s&&1==u.length&&(s=1),u.length!=s||0===o[e[n]]&&"00"!=t[n]?!1:-1===l?!1:(u=o[e[l]].toString(),u.length<1||o[e[l]]<1||o[e[l]]>12?!1:-1===d?!1:(u=o[e[d]].toString(),u.length<1||o[e[d]]<1||o[e[d]]>31||2==o[e[l]]&&o[e[d]]>r(o[e[n]])||o[e[d]]>h[o[e[l]]]?!1:!0)))},isEmpty:function(e){return e.match(/^\s+$/)||""===e?!0:!1},checkTime:function(t){var i,r=/^(\d{1,2}):(\d{2})([ap]m)?$/;if(!e.jgrid.isEmpty(t)){if(i=t.match(r),!i)return!1;if(i[3]){if(i[1]<1||i[1]>12)return!1}else if(i[1]>23)return!1;if(i[2]>59)return!1}return!0},checkValues:function(t,i,r,a,o){var s,n,d,l,p;if("undefined"==typeof a)if("string"==typeof i){for(n=0,p=r.p.colModel.length;p>n;n++)if(r.p.colModel[n].name==i){s=r.p.colModel[n].editrules,i=n;try{d=r.p.colModel[n].formoptions.label}catch(c){}break}}else i>=0&&(s=r.p.colModel[i].editrules);else s=a,d=void 0===o?"_":o;if(s){if(d||(d=r.p.colNames[i]),s.required===!0&&e.jgrid.isEmpty(t))return[!1,d+": "+e.jgrid.edit.msg.required,""];var u=s.required===!1?!1:!0;if(s.number===!0&&(u!==!1||!e.jgrid.isEmpty(t))&&isNaN(t))return[!1,d+": "+e.jgrid.edit.msg.number,""];if("undefined"!=typeof s.minValue&&!isNaN(s.minValue)&&parseFloat(t)<parseFloat(s.minValue))return[!1,d+": "+e.jgrid.edit.msg.minValue+" "+s.minValue,""];if("undefined"!=typeof s.maxValue&&!isNaN(s.maxValue)&&parseFloat(t)>parseFloat(s.maxValue))return[!1,d+": "+e.jgrid.edit.msg.maxValue+" "+s.maxValue,""];var h;if(s.email===!0&&!(u===!1&&e.jgrid.isEmpty(t)||(h=/^((([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,
h.test(t))))return[!1,d+": "+e.jgrid.edit.msg.email,""];if(s.integer===!0&&(u!==!1||!e.jgrid.isEmpty(t))){if(isNaN(t))return[!1,d+": "+e.jgrid.edit.msg.integer,""];if(t%1!==0||-1!=t.indexOf("."))return[!1,d+": "+e.jgrid.edit.msg.integer,""]}if(s.date===!0&&!(u===!1&&e.jgrid.isEmpty(t)||(l=r.p.colModel[i].formatoptions&&r.p.colModel[i].formatoptions.newformat?r.p.colModel[i].formatoptions.newformat:r.p.colModel[i].datefmt||"Y-m-d",e.jgrid.checkDate(l,t))))return[!1,d+": "+e.jgrid.edit.msg.date+" - "+l,""];if(s.time===!0&&!(u===!1&&e.jgrid.isEmpty(t)||e.jgrid.checkTime(t)))return[!1,d+": "+e.jgrid.edit.msg.date+" - hh:mm (am/pm)",""];if(s.url===!0&&!(u===!1&&e.jgrid.isEmpty(t)||(h=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,h.test(t))))return[!1,d+": "+e.jgrid.edit.msg.url,""];if(s.custom===!0&&(u!==!1||!e.jgrid.isEmpty(t))){if(e.isFunction(s.custom_func)){var f=s.custom_func.call(r,t,d);return e.isArray(f)?f:[!1,e.jgrid.edit.msg.customarray,""]}return[!1,e.jgrid.edit.msg.customfcheck,""]}}return[!0,"",""]}})}(jQuery),/*
 * jqFilter  jQuery jqGrid filter addon.
 * Copyright (c) 2011, Tony Tomov, tony@trirand.com
 * Dual licensed under the MIT and GPL licenses
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
 *
 * The work is inspired from this Stefan Pirvu
 * http://www.codeproject.com/KB/scripting/json-filtering.aspx
 *
 * The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:

{ "groupOp": "AND",
      "groups" : [
        { "groupOp": "OR",
            "rules": [
                { "field": "name", "op": "eq", "data": "England" },
                { "field": "id", "op": "le", "data": "5"}
             ]
        }
      ],
      "rules": [
        { "field": "name", "op": "eq", "data": "Romania" },
        { "field": "id", "op": "le", "data": "1"}
      ]
}
*/
function(e){e.fn.jqFilter=function(t){if("string"==typeof t){var i=e.fn.jqFilter[t];if(!i)throw"jqFilter - No such method: "+t;var r=e.makeArray(arguments).slice(1);return i.apply(this,r)}var a=e.extend(!0,{filter:null,columns:[],onChange:null,afterRedraw:null,checkValues:null,error:!1,errmsg:"",errorcheck:!0,showQuery:!0,sopt:null,ops:[{name:"eq",description:"equal",operator:"="},{name:"ne",description:"not equal",operator:"<>"},{name:"lt",description:"less",operator:"<"},{name:"le",description:"less or equal",operator:"<="},{name:"gt",description:"greater",operator:">"},{name:"ge",description:"greater or equal",operator:">="},{name:"bw",description:"begins with",operator:"LIKE"},{name:"bn",description:"does not begin with",operator:"NOT LIKE"},{name:"in",description:"in",operator:"IN"},{name:"ni",description:"not in",operator:"NOT IN"},{name:"ew",description:"ends with",operator:"LIKE"},{name:"en",description:"does not end with",operator:"NOT LIKE"},{name:"cn",description:"contains",operator:"LIKE"},{name:"nc",description:"does not contain",operator:"NOT LIKE"},{name:"nu",description:"is null",operator:"IS NULL"},{name:"nn",description:"is not null",operator:"IS NOT 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"],_gridsopt:[],groupOps:[{op:"AND",text:"AND"},{op:"OR",text:"OR"}],groupButton:!0,ruleButtons:!0,direction:"ltr"},e.jgrid.filter,t||{});return this.each(function(){if(!this.filter){this.p=a,(null===this.p.filter||void 0===this.p.filter)&&(this.p.filter={groupOp:this.p.groupOps[0].op,rules:[],groups:[]});var t,i,r=this.p.columns.length,o=/msie/i.test(navigator.userAgent)&&!window.opera;if(this.p._gridsopt.length)for(t=0;t<this.p._gridsopt.length;t++)this.p.ops[t].description=this.p._gridsopt[t];if(this.p.initFilter=e.extend(!0,{},this.p.filter),r){for(t=0;r>t;t++)i=this.p.columns[t],i.stype?i.inputtype=i.stype:i.inputtype||(i.inputtype="text"),i.sorttype?i.searchtype=i.sorttype:i.searchtype||(i.searchtype="string"),void 0===i.hidden&&(i.hidden=!1),i.label||(i.label=i.name),i.index&&(i.name=i.index),i.hasOwnProperty("searchoptions")||(i.searchoptions={}),i.hasOwnProperty("searchrules")||(i.searchrules={});this.p.showQuery&&e(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");var s=function(t,i){var r=[!0,""];if(e.isFunction(i.searchrules))r=i.searchrules(t,i);else if(e.jgrid&&e.jgrid.checkValues)try{r=e.jgrid.checkValues(t,-1,null,i.searchrules,i.label)}catch(o){}r&&r.length&&r[0]===!1&&(a.error=!r[0],a.errmsg=r[1])};this.onchange=function(){return this.p.error=!1,this.p.errmsg="",e.isFunction(this.p.onChange)?this.p.onChange.call(this,this.p):!1},this.reDraw=function(){e("table.group:first",this).remove();var t=this.createTableForGroup(a.filter,null);e(this).append(t),e.isFunction(this.p.afterRedraw)&&this.p.afterRedraw.call(this,this.p)},this.createTableForGroup=function(t,i){var r,o=this,s=e("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody></tbody></table>"),n="left";"rtl"==this.p.direction&&(n="right",s.attr("dir","rtl")),null===i&&s.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='"+n+"'></th></tr>");var d=e("<tr></tr>");s.append(d);var l=e("<th colspan='5' align='"+n+"'></th>");if(d.append(l),this.p.ruleButtons===!0){var p=e("<select class='opsel'></select>");l.append(p);var c,u="";for(r=0;r<a.groupOps.length;r++)c=t.groupOp===o.p.groupOps[r].op?" selected='selected'":"",u+="<option value='"+o.p.groupOps[r].op+"'"+c+">"+o.p.groupOps[r].text+"</option>";p.append(u).bind("change",function(){t.groupOp=e(p).val(),o.onchange()})}var h="<span></span>";if(this.p.groupButton&&(h=e("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>"),h.bind("click",function(){return void 0===t.groups&&(t.groups=[]),t.groups.push({groupOp:a.groupOps[0].op,rules:[],groups:[]}),o.reDraw(),o.onchange(),!1})),l.append(h),this.p.ruleButtons===!0){var f,g=e("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>");g.bind("click",function(){for(void 0===t.rules&&(t.rules=[]),r=0;r<o.p.columns.length;r++){var e="undefined"==typeof o.p.columns[r].search?!0:o.p.columns[r].search,i=o.p.columns[r].hidden===!0,a=o.p.columns[r].searchoptions.searchhidden===!0;if(a&&e||e&&!i){f=o.p.columns[r];break}}var s;return s=f.searchoptions.sopt?f.searchoptions.sopt:o.p.sopt?o.p.sopt:"string"===f.searchtype?o.p.stropts:o.p.numopts,t.rules.push({field:f.name,op:s[0],data:""}),o.reDraw(),!1}),l.append(g)}if(null!=i){var m=e("<input type='button' value='-' title='Delete group' class='delete-group'/>");l.append(m),m.bind("click",function(){for(r=0;r<i.groups.length;r++)if(i.groups[r]===t){i.groups.splice(r,1);break}return o.reDraw(),o.onchange(),!1})}if(void 0!==t.groups)for(r=0;r<t.groups.length;r++){var v=e("<tr></tr>");s.append(v);var j=e("<td class='first'></td>");v.append(j);var b=e("<td colspan='4'></td>");b.append(this.createTableForGroup(t.groups[r],t)),v.append(b)}if(void 0===t.groupOp&&(t.groupOp=o.p.groupOps[0].op),void 0!==t.rules)for(r=0;r<t.rules.length;r++)s.append(this.createTableRowForRule(t.rules[r],t));return s},this.createTableRowForRule=function(t,i){var r,s,n,d,l,p=this,c=e("<tr></tr>"),u="";c.append("<td class='first'></td>");var h=e("<td class='columns'></td>");c.append(h);var f,g=e("<select></select>"),m=[];h.append(g),g.bind("change",function(){for(t.field=e(g).val(),n=e(this).parents("tr:first"),r=0;r<p.p.columns.length;r++)if(p.p.columns[r].name===t.field){d=p.p.columns[r];break}if(d){d.searchoptions.id=e.jgrid.randId(),o&&"text"===d.inputtype&&(d.searchoptions.size||(d.searchoptions.size=10));var i=e.jgrid.createEl(d.inputtype,d.searchoptions,"",!0,p.p.ajaxSelectOptions,!0);e(i).addClass("input-elm"),s=d.searchoptions.sopt?d.searchoptions.sopt:p.p.sopt?p.p.sopt:"string"===d.searchtype?p.p.stropts:p.p.numopts;var a="",l=0;for(m=[],e.each(p.p.ops,function(){m.push(this.name)}),r=0;r<s.length;r++)f=e.inArray(s[r],m),-1!==f&&(0===l&&(t.op=p.p.ops[f].name),a+="<option value='"+p.p.ops[f].name+"'>"+p.p.ops[f].description+"</option>",l++);if(e(".selectopts",n).empty().append(a),e(".selectopts",n)[0].selectedIndex=0,e.browser.msie&&e.browser.version<9){var c=parseInt(e("select.selectopts",n)[0].offsetWidth)+1;e(".selectopts",n).width(c),e(".selectopts",n).css("width","auto")}e(".data",n).empty().append(i),e(".input-elm",n).bind("change",function(i){var r=e(this).hasClass("ui-autocomplete-input")?200:0;setTimeout(function(){var r=i.target;t.data="SPAN"===r.nodeName.toUpperCase()&&d.searchoptions&&e.isFunction(d.searchoptions.custom_value)?d.searchoptions.custom_value(e(r).children(".customelement:first"),"get"):r.value,p.onchange()},r)}),setTimeout(function(){t.data=e(i).val(),p.onchange()},0)}});var v=0;for(r=0;r<p.p.columns.length;r++){var j="undefined"==typeof p.p.columns[r].search?!0:p.p.columns[r].search,b=p.p.columns[r].hidden===!0,w=p.p.columns[r].searchoptions.searchhidden===!0;(w&&j||j&&!b)&&(l="",t.field===p.p.columns[r].name&&(l=" selected='selected'",v=r),u+="<option value='"+p.p.columns[r].name+"'"+l+">"+p.p.columns[r].label+"</option>")}g.append(u);var y=e("<td class='operators'></td>");c.append(y),d=a.columns[v],d.searchoptions.id=e.jgrid.randId(),o&&"text"===d.inputtype&&(d.searchoptions.size||(d.searchoptions.size=10));var q=e.jgrid.createEl(d.inputtype,d.searchoptions,t.data,!0,p.p.ajaxSelectOptions,!0),x=e("<select class='selectopts'></select>");for(y.append(x),x.bind("change",function(){t.op=e(x).val(),n=e(this).parents("tr:first");var i=e(".input-elm",n)[0];"nu"===t.op||"nn"===t.op?(t.data="",i.value="",i.setAttribute("readonly","true"),i.setAttribute("disabled","true")):(i.removeAttribute("readonly"),i.removeAttribute("disabled")),p.onchange()}),s=d.searchoptions.sopt?d.searchoptions.sopt:p.p.sopt?p.p.sopt:"string"===d.searchtype?a.stropts:p.p.numopts,u="",e.each(p.p.ops,function(){m.push(this.name)}),r=0;r<s.length;r++)f=e.inArray(s[r],m),-1!==f&&(l=t.op===p.p.ops[f].name?" selected='selected'":"",u+="<option value='"+p.p.ops[f].name+"'"+l+">"+p.p.ops[f].description+"</option>");x.append(u);var D=e("<td class='data'></td>");c.append(D),D.append(q),e(q).addClass("input-elm").bind("change",function(){t.data="custom"===d.inputtype?d.searchoptions.custom_value(e(this).children(".customelement:first"),"get"):e(this).val(),p.onchange()});var $=e("<td></td>");if(c.append($),this.p.ruleButtons===!0){var _=e("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>");$.append(_),_.bind("click",function(){for(r=0;r<i.rules.length;r++)if(i.rules[r]===t){i.rules.splice(r,1);break}return p.reDraw(),p.onchange(),!1})}return c},this.getStringForGroup=function(e){var t,i="(";if(void 0!==e.groups)for(t=0;t<e.groups.length;t++){i.length>1&&(i+=" "+e.groupOp+" ");try{i+=this.getStringForGroup(e.groups[t])}catch(r){alert(r)}}if(void 0!==e.rules)try{for(t=0;t<e.rules.length;t++)i.length>1&&(i+=" "+e.groupOp+" "),i+=this.getStringForRule(e.rules[t])}catch(a){alert(a)}return i+=")","()"===i?"":i},this.getStringForRule=function(t){var i,r,o,n,d="",l="",p=["int","integer","float","number","currency"];for(i=0;i<this.p.ops.length;i++)if(this.p.ops[i].name===t.op){d=this.p.ops[i].operator,l=this.p.ops[i].name;break}for(i=0;i<this.p.columns.length;i++)if(this.p.columns[i].name===t.field){r=this.p.columns[i];break}return n=t.data,("bw"===l||"bn"===l)&&(n+="%"),("ew"===l||"en"===l)&&(n="%"+n),("cn"===l||"nc"===l)&&(n="%"+n+"%"),("in"===l||"ni"===l)&&(n=" ("+n+")"),a.errorcheck&&s(t.data,r),o=-1!==e.inArray(r.searchtype,p)||"nn"===l||"nu"===l?t.field+" "+d+" "+n:t.field+" "+d+' "'+n+'"'},this.resetFilter=function(){this.p.filter=e.extend(!0,{},this.p.initFilter),this.reDraw(),this.onchange()},this.hideError=function(){e("th.ui-state-error",this).html(""),e("tr.error",this).hide()},this.showError=function(){e("th.ui-state-error",this).html(this.p.errmsg),e("tr.error",this).show()},this.toUserFriendlyString=function(){return this.getStringForGroup(a.filter)},this.toString=function(){function e(e){if(i.p.errorcheck){var t,r;for(t=0;t<i.p.columns.length;t++)if(i.p.columns[t].name===e.field){r=i.p.columns[t];break}r&&s(e.data,r)}return e.op+"(item."+e.field+",'"+e.data+"')"}function t(i){var r,a="(";if(void 0!==i.groups)for(r=0;r<i.groups.length;r++)a.length>1&&(a+="OR"===i.groupOp?" || ":" && "),a+=t(i.groups[r]);if(void 0!==i.rules)for(r=0;r<i.rules.length;r++)a.length>1&&(a+="OR"===i.groupOp?" || ":" && "),a+=e(i.rules[r]);return a+=")","()"===a?"":a}var i=this;return t(this.p.filter)},this.reDraw(),this.p.showQuery&&this.onchange(),this.filter=!0}}})},e.extend(e.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(e){return void 0!==e&&this.p.hasOwnProperty(e)?this.p[e]:this.p},resetFilter:function(){return this.each(function(){this.resetFilter()})},addFilter:function(e){"string"==typeof e&&(e=jQuery.jgrid.parse(e)),this.each(function(){this.p.filter=e,this.reDraw(),this.onchange()})}})}(jQuery),function(e){"use strict";var t={};e.jgrid.extend({searchGrid:function(t){return t=e.extend({recreateFilter:!1,drag:!0,sField:"searchField",sValue:"searchString",sOper:"searchOper",sFilter:"filters",loadDefaults:!0,beforeShowSearch:null,afterShowSearch:null,onInitializeSearch:null,afterRedraw:null,afterChange: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},e.jgrid.search,t||{}),this.each(function(){function i(i){o=e(r).triggerHandler("jqGridFilterBeforeShow",[i]),"undefined"==typeof o&&(o=!0),o&&e.isFunction(t.beforeShowSearch)&&(o=t.beforeShowSearch.call(r,i)),o&&(e.jgrid.viewModal("#"+e.jgrid.jqID(s.themodal),{gbox:"#gbox_"+e.jgrid.jqID(a),jqm:t.jqModal,modal:t.modal,overlay:t.overlay,toTop:t.toTop}),e(r).triggerHandler("jqGridFilterAfterShow",[i]),e.isFunction(t.afterShowSearch)&&t.afterShowSearch.call(r,i))}var r=this;if(r.grid){var a="fbox_"+r.p.id,o=!0,s={themodal:"searchmod"+a,modalhead:"searchhd"+a,modalcontent:"searchcnt"+a,scrollelm:a},n=r.p.postData[t.sFilter];if("string"==typeof n&&(n=e.jgrid.parse(n)),t.recreateFilter===!0&&e("#"+e.jgrid.jqID(s.themodal)).remove(),null!=e("#"+e.jgrid.jqID(s.themodal)).html())i(e("#fbox_"+e.jgrid.jqID(+r.p.id)));else{var d=e("<div><div id='"+a+"' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_"+e.jgrid.jqID(r.p.id)),l="left",p="";"rtl"==r.p.direction&&(l="right",p=" style='text-align:left'",d.attr("dir","rtl"));var c,u,h=e.extend([],r.p.colModel),f="<a href='javascript:void(0)' id='"+a+"_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>"+t.Find+"</a>",g="<a href='javascript:void(0)' id='"+a+"_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>"+t.Reset+"</a>",m="",v="",j=!1,b=-1;if(t.showQuery&&(m="<a href='javascript:void(0)' id='"+a+"_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>"),t.columns.length?h=t.columns:e.each(h,function(e,t){if(t.label||(t.label=r.p.colNames[e]),!j){var i="undefined"==typeof t.search?!0:t.search,a=t.hidden===!0,o=t.searchoptions&&t.searchoptions.searchhidden===!0;(o&&i||i&&!a)&&(j=!0,c=t.index||t.name,b=e)}}),!n&&c||t.multipleSearch===!1){var w="eq";b>=0&&h[b].searchoptions&&h[b].searchoptions.sopt?w=h[b].searchoptions.sopt[0]:t.sopt&&t.sopt.length&&(w=t.sopt[0]),n={groupOp:"AND",rules:[{field:c,op:w,data:""}]}}j=!1,t.tmplNames&&t.tmplNames.length&&(j=!0,v=t.tmplLabel,v+="<select class='ui-template'>",v+="<option value='default'>Default</option>",e.each(t.tmplNames,function(e,t){v+="<option value='"+e+"'>"+t+"</option>"}),v+="</select>"),u="<table class='EditTable' style='border:0px none;margin-top:5px' id='"+a+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='EditButton' style='text-align:"+l+"'>"+g+v+"</td><td class='EditButton' "+p+">"+m+f+"</td></tr></tbody></table>",a=e.jgrid.jqID(a),e("#"+a).jqFilter({columns:h,filter:t.loadDefaults?n:null,showQuery:t.showQuery,errorcheck:t.errorcheck,sopt:t.sopt,groupButton:t.multipleGroup,ruleButtons:t.multipleSearch,afterRedraw:t.afterRedraw,_gridsopt:e.jgrid.search.odata,ajaxSelectOptions:r.p.ajaxSelectOptions,groupOps:t.groupOps,onChange:function(){this.p.showQuery&&e(".query",this).html(this.toUserFriendlyString()),e.isFunction(t.afterChange)&&t.afterChange.call(r,e("#"+a),t)},direction:r.p.direction}),d.append(u),j&&t.tmplFilters&&t.tmplFilters.length&&e(".ui-template",d).bind("change",function(){var i=e(this).val();return"default"==i?e("#"+a).jqFilter("addFilter",n):e("#"+a).jqFilter("addFilter",t.tmplFilters[parseInt(i,10)]),!1}),t.multipleGroup===!0&&(t.multipleSearch=!0),e(r).triggerHandler("jqGridFilterInitialize",[e("#"+a)]),e.isFunction(t.onInitializeSearch)&&t.onInitializeSearch.call(r,e("#"+a)),t.gbox="#gbox_"+a,t.layer?e.jgrid.createModal(s,d,t,"#gview_"+e.jgrid.jqID(r.p.id),e("#gbox_"+e.jgrid.jqID(r.p.id))[0],"#"+e.jgrid.jqID(t.layer),{position:"relative"}):e.jgrid.createModal(s,d,t,"#gview_"+e.jgrid.jqID(r.p.id),e("#gbox_"+e.jgrid.jqID(r.p.id))[0]),(t.searchOnEnter||t.closeOnEscape)&&e("#"+e.jgrid.jqID(s.themodal)).keydown(function(i){var r=e(i.target);return!t.searchOnEnter||13!==i.which||r.hasClass("add-group")||r.hasClass("add-rule")||r.hasClass("delete-group")||r.hasClass("delete-rule")||r.hasClass("fm-button")&&r.is("[id$=_query]")?t.closeOnEscape&&27===i.which?(e("#"+e.jgrid.jqID(s.modalhead)).find(".ui-jqdialog-titlebar-close").focus().click(),!1):void 0:(e("#"+a+"_search").focus().click(),!1)}),m&&e("#"+a+"_query").bind("click",function(){return e(".queryresult",d).toggle(),!1}),void 0===t.stringResult&&(t.stringResult=t.multipleSearch),e("#"+a+"_search").bind("click",function(){var i,o=e("#"+a),n={},d=o.jqFilter("filterData");if(t.errorcheck&&(o[0].hideError(),t.showQuery||o.jqFilter("toSQLString"),o[0].p.error))return o[0].showError(),!1;if(t.stringResult){try{i=xmlJsonClass.toJson(d,"","",!1)}catch(l){try{i=JSON.stringify(d)}catch(p){}}"string"==typeof i&&(n[t.sFilter]=i,e.each([t.sField,t.sValue,t.sOper],function(){n[this]=""}))}else t.multipleSearch?(n[t.sFilter]=d,e.each([t.sField,t.sValue,t.sOper],function(){n[this]=""})):(n[t.sField]=d.rules[0].field,n[t.sValue]=d.rules[0].data,n[t.sOper]=d.rules[0].op,n[t.sFilter]="");return r.p.search=!0,e.extend(r.p.postData,n),e(r).triggerHandler("jqGridFilterSearch"),e.isFunction(t.onSearch)&&t.onSearch.call(r),e(r).trigger("reloadGrid",[{page:1}]),t.closeAfterSearch&&e.jgrid.hideModal("#"+e.jgrid.jqID(s.themodal),{gb:"#gbox_"+e.jgrid.jqID(r.p.id),jqm:t.jqModal,onClose:t.onClose}),!1}),e("#"+a+"_reset").bind("click",function(){var i={},o=e("#"+a);return r.p.search=!1,t.multipleSearch===!1?i[t.sField]=i[t.sValue]=i[t.sOper]="":i[t.sFilter]="",o[0].resetFilter(),j&&e(".ui-template",d).val("default"),e.extend(r.p.postData,i),e(r).triggerHandler("jqGridFilterReset"),e.isFunction(t.onReset)&&t.onReset.call(r),e(r).trigger("reloadGrid",[{page:1}]),!1}),i(e("#"+a)),e(".fm-button:not(.ui-state-disabled)",d).hover(function(){e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")})}}})},editGridRow:function(i,r){return r=e.extend({top:0,left:0,width:300,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,_savedData:{},processing:!1,onClose:null,ajaxEditOptions:{},serializeEditData:null,viewPagerButtons:!0},e.jgrid.edit,r||{}),t[e(this)[0].p.id]=r,this.each(function(){function a(){return e(x+" > tbody > tr > td > .FormElement").each(function(){var t=e(".customelement",this);if(t.length){var i=t[0],r=e(i).attr("name");e.each(f.p.colModel,function(){if(this.name===r&&this.editoptions&&e.isFunction(this.editoptions.custom_value)){try{if(g[r]=this.editoptions.custom_value.call(f,e("#"+e.jgrid.jqID(r),x),"get"),void 0===g[r])throw"e1"}catch(t){"e1"===t?e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose):e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,t.message,jQuery.jgrid.edit.bClose)}return!0}})}else{switch(e(this).get(0).type){case"checkbox":if(e(this).is(":checked"))g[this.name]=e(this).val();else{var a=e(this).attr("offval");g[this.name]=a}break;case"select-one":g[this.name]=e("option:selected",this).val(),m[this.name]=e("option:selected",this).text();break;case"select-multiple":g[this.name]=e(this).val(),g[this.name]?g[this.name]=g[this.name].join(","):g[this.name]="";var o=[];e("option:selected",this).each(function(t,i){o[t]=e(i).text()}),m[this.name]=o.join(",");break;case"password":case"text":case"textarea":case"button":g[this.name]=e(this).val()}f.p.autoencode&&(g[this.name]=e.jgrid.htmlEncode(g[this.name]))}}),!0}function o(i,r,a,o){var s,n,d,l,p,c,u,h=0,g=[],m=!1,v="<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>",j="";for(u=1;o>=u;u++)j+=v;if("_empty"!=i&&(m=e(r).jqGrid("getInd",i)),e(r.p.colModel).each(function(u){if(s=this.name,n=this.editrules&&this.editrules.edithidden===!0?!1:this.hidden===!0?!0:!1,p=n?"style='display:none'":"","cb"!==s&&"subgrid"!==s&&this.editable===!0&&"rn"!==s){if(m===!1)l="";else if(s==r.p.ExpandColumn&&r.p.treeGrid===!0)l=e("td:eq("+u+")",r.rows[m]).text();else{try{l=e.unformat.call(r,e("td:eq("+u+")",r.rows[m]),{rowId:i,colModel:this},u)}catch(v){l=this.edittype&&"textarea"==this.edittype?e("td:eq("+u+")",r.rows[m]).text():e("td:eq("+u+")",r.rows[m]).html()}(!l||"&nbsp;"==l||"&#160;"==l||1==l.length&&160==l.charCodeAt(0))&&(l="")}var b=e.extend({},this.editoptions||{},{id:s,name:s}),w=e.extend({},{elmprefix:"",elmsuffix:"",rowabove:!1,rowcontent:""},this.formoptions||{}),y=parseInt(w.rowpos,10)||h+1,q=parseInt(2*(parseInt(w.colpos,10)||1),10);if("_empty"==i&&b.defaultValue&&(l=e.isFunction(b.defaultValue)?b.defaultValue.call(f):b.defaultValue),this.edittype||(this.edittype="text"),f.p.autoencode&&(l=e.jgrid.htmlDecode(l)),c=e.jgrid.createEl.call(f,this.edittype,b,l,!1,e.extend({},e.jgrid.ajaxOptions,r.p.ajaxSelectOptions||{})),""===l&&"checkbox"==this.edittype&&(l=e(c).attr("offval")),""===l&&"select"==this.edittype&&(l=e("option:eq(0)",c).text()),(t[f.p.id].checkOnSubmit||t[f.p.id].checkOnUpdate)&&(t[f.p.id]._savedData[s]=l),e(c).addClass("FormElement"),("text"==this.edittype||"textarea"==this.edittype)&&e(c).addClass("ui-widget-content ui-corner-all"),d=e(a).find("tr[rowpos="+y+"]"),w.rowabove){var x=e("<tr><td class='contentinfo' colspan='"+2*o+"'>"+w.rowcontent+"</td></tr>");e(a).append(x),x[0].rp=y}0===d.length&&(d=e("<tr "+p+" rowpos='"+y+"'></tr>").addClass("FormData").attr("id","tr_"+s),e(d).append(j),e(a).append(d),d[0].rp=y),e("td:eq("+(q-2)+")",d[0]).html("undefined"==typeof w.label?r.p.colNames[u]:w.label),e("td:eq("+(q-1)+")",d[0]).append(w.elmprefix).append(c).append(w.elmsuffix),g[h]=u,h++}}),h>0){var b=e("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(2*o-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+r.p.id+"_id' value='"+i+"'/></td></tr>");b[0].rp=h+999,e(a).append(b),(t[f.p.id].checkOnSubmit||t[f.p.id].checkOnUpdate)&&(t[f.p.id]._savedData[r.p.id+"_id"]=i)}return g}function s(i,r,a){var o,s,n,d,l,p,c=0;(t[f.p.id].checkOnSubmit||t[f.p.id].checkOnUpdate)&&(t[f.p.id]._savedData={},t[f.p.id]._savedData[r.p.id+"_id"]=i);var u=r.p.colModel;if("_empty"==i)return e(u).each(function(){o=this.name,d=e.extend({},this.editoptions||{}),n=e("#"+e.jgrid.jqID(o),"#"+a),n&&n.length&&null!=n[0]&&(l="",d.defaultValue?(l=e.isFunction(d.defaultValue)?d.defaultValue.call(f):d.defaultValue,"checkbox"==n[0].type?(p=l.toLowerCase(),p.search(/(false|0|no|off|undefined)/i)<0&&""!==p?(n[0].checked=!0,n[0].defaultChecked=!0,n[0].value=l):(n[0].checked=!1,n[0].defaultChecked=!1)):n.val(l)):"checkbox"==n[0].type?(n[0].checked=!1,n[0].defaultChecked=!1,l=e(n).attr("offval")):n[0].type&&"select"==n[0].type.substr(0,6)?n[0].selectedIndex=0:n.val(l),(t[f.p.id].checkOnSubmit===!0||t[f.p.id].checkOnUpdate)&&(t[f.p.id]._savedData[o]=l))}),void e("#id_g","#"+a).val(i);var h=e(r).jqGrid("getInd",i,!0);h&&(e('td[role="gridcell"]',h).each(function(n){if(o=u[n].name,"cb"!==o&&"subgrid"!==o&&"rn"!==o&&u[n].editable===!0){if(o==r.p.ExpandColumn&&r.p.treeGrid===!0)s=e(this).text();else try{s=e.unformat.call(r,e(this),{rowId:i,colModel:u[n]},n)}catch(d){s="textarea"==u[n].edittype?e(this).text():e(this).html()}switch(f.p.autoencode&&(s=e.jgrid.htmlDecode(s)),(t[f.p.id].checkOnSubmit===!0||t[f.p.id].checkOnUpdate)&&(t[f.p.id]._savedData[o]=s),o=e.jgrid.jqID(o),u[n].edittype){case"password":case"text":case"button":case"image":case"textarea":("&nbsp;"==s||"&#160;"==s||1==s.length&&160==s.charCodeAt(0))&&(s=""),e("#"+o,"#"+a).val(s);break;case"select":var l=s.split(",");l=e.map(l,function(t){return e.trim(t)}),e("#"+o+" option","#"+a).each(function(){u[n].editoptions.multiple||e.trim(s)!=e.trim(e(this).text())&&l[0]!=e.trim(e(this).text())&&l[0]!=e.trim(e(this).val())?u[n].editoptions.multiple&&(e.inArray(e.trim(e(this).text()),l)>-1||e.inArray(e.trim(e(this).val()),l)>-1)?this.selected=!0:this.selected=!1:this.selected=!0});break;case"checkbox":if(s+="",u[n].editoptions&&u[n].editoptions.value){var p=u[n].editoptions.value.split(":");p[0]==s?(e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("checked",!0),e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("defaultChecked",!0)):(e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("checked",!1),e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("defaultChecked",!1))}else s=s.toLowerCase(),s.search(/(false|0|no|off|undefined)/i)<0&&""!==s?(e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("checked",!0),e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("defaultChecked",!0)):(e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("checked",!1),e("#"+o,"#"+a)[f.p.useProp?"prop":"attr"]("defaultChecked",!1));break;case"custom":try{if(!u[n].editoptions||!e.isFunction(u[n].editoptions.custom_value))throw"e1";u[n].editoptions.custom_value.call(f,e("#"+o,"#"+a),"set",s)}catch(h){"e1"==h?e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose):e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,h.message,jQuery.jgrid.edit.bClose)}}c++}}),c>0&&e("#id_g",x).val(i))}function n(){e.each(f.p.colModel,function(e,t){t.editoptions&&t.editoptions.NullIfEmpty===!0&&g.hasOwnProperty(t.name)&&""===g[t.name]&&(g[t.name]="null")})}function d(){var i,a,o,d,l,p,c=[!0,"",""],u={},h=f.p.prmNames,v=e(f).triggerHandler("jqGridAddEditBeforeCheckValues",[e("#"+y),b]);v&&"object"==typeof v&&(g=v),e.isFunction(t[f.p.id].beforeCheckValues)&&(v=t[f.p.id].beforeCheckValues.call(f,g,e("#"+y),"_empty"==g[f.p.id+"_id"]?h.addoper:h.editoper),v&&"object"==typeof v&&(g=v));for(d in g)if(g.hasOwnProperty(d)&&(c=e.jgrid.checkValues.call(f,g[d],d,f),c[0]===!1))break;if(n(),c[0]&&(u=e(f).triggerHandler("jqGridAddEditClickSubmit",[t[f.p.id],g,b]),void 0===u&&e.isFunction(t[f.p.id].onclickSubmit)&&(u=t[f.p.id].onclickSubmit.call(f,t[f.p.id],g)||{}),c=e(f).triggerHandler("jqGridAddEditBeforeSubmit",[g,e("#"+y),b]),void 0===c&&(c=[!0,"",""]),c[0]&&e.isFunction(t[f.p.id].beforeSubmit)&&(c=t[f.p.id].beforeSubmit.call(f,g,e("#"+y)))),c[0]&&!t[f.p.id].processing){if(t[f.p.id].processing=!0,e("#sData",x+"_2").addClass("ui-state-active"),o=h.oper,a=h.id,g[o]="_empty"==e.trim(g[f.p.id+"_id"])?h.addoper:h.editoper,g[o]!=h.addoper?g[a]=g[f.p.id+"_id"]:void 0===g[a]&&(g[a]=g[f.p.id+"_id"]),delete g[f.p.id+"_id"],g=e.extend(g,t[f.p.id].editData,u),f.p.treeGrid===!0){if(g[o]==h.addoper){l=e(f).jqGrid("getGridParam","selrow");var j="adjacency"==f.p.treeGridModel?f.p.treeReader.parent_id_field:"parent_id";g[j]=l}for(p in f.p.treeReader)if(f.p.treeReader.hasOwnProperty(p)){var q=f.p.treeReader[p];if(g.hasOwnProperty(q)){if(g[o]==h.addoper&&"parent_id_field"===p)continue;delete g[q]}}}g[a]=e.jgrid.stripPref(f.p.idPrefix,g[a]);var $=e.extend({url:t[f.p.id].url?t[f.p.id].url:e(f).jqGrid("getGridParam","editurl"),type:t[f.p.id].mtype,data:e.isFunction(t[f.p.id].serializeEditData)?t[f.p.id].serializeEditData.call(f,g):g,complete:function(n,d){if(g[a]=f.p.idPrefix+g[a],"success"!=d?(c[0]=!1,c[1]=e(f).triggerHandler("jqGridAddEditErrorTextFormat",[n,b]),e.isFunction(t[f.p.id].errorTextFormat)?c[1]=t[f.p.id].errorTextFormat.call(f,n):c[1]=d+" Status: '"+n.statusText+"'. Error code: "+n.status):(c=e(f).triggerHandler("jqGridAddEditAfterSubmit",[n,g,b]),void 0===c&&(c=[!0,"",""]),c[0]&&e.isFunction(t[f.p.id].afterSubmit)&&(c=t[f.p.id].afterSubmit.call(f,n,g))),c[0]===!1)e("#FormError>td",x).html(c[1]),e("#FormError",x).show();else if(e.each(f.p.colModel,function(){if(m[this.name]&&this.formatter&&"select"==this.formatter)try{delete m[this.name]}catch(e){}}),g=e.extend(g,m),f.p.autoencode&&e.each(g,function(t,i){g[t]=e.jgrid.htmlDecode(i)}),g[o]==h.addoper?(c[2]||(c[2]=e.jgrid.randId()),g[a]=c[2],t[f.p.id].closeAfterAdd?(t[f.p.id].reloadAfterSubmit?e(f).trigger("reloadGrid"):f.p.treeGrid===!0?e(f).jqGrid("addChildNode",c[2],l,g):(e(f).jqGrid("addRowData",c[2],g,r.addedrow),e(f).jqGrid("setSelection",c[2])),e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose})):t[f.p.id].clearAfterAdd?(t[f.p.id].reloadAfterSubmit?e(f).trigger("reloadGrid"):f.p.treeGrid===!0?e(f).jqGrid("addChildNode",c[2],l,g):e(f).jqGrid("addRowData",c[2],g,r.addedrow),s("_empty",f,y)):t[f.p.id].reloadAfterSubmit?e(f).trigger("reloadGrid"):f.p.treeGrid===!0?e(f).jqGrid("addChildNode",c[2],l,g):e(f).jqGrid("addRowData",c[2],g,r.addedrow)):(t[f.p.id].reloadAfterSubmit?(e(f).trigger("reloadGrid"),t[f.p.id].closeAfterEdit||setTimeout(function(){e(f).jqGrid("setSelection",g[a])},1e3)):f.p.treeGrid===!0?e(f).jqGrid("setTreeRow",g[a],g):e(f).jqGrid("setRowData",g[a],g),t[f.p.id].closeAfterEdit&&e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose})),e.isFunction(t[f.p.id].afterComplete)&&(i=n,setTimeout(function(){e(f).triggerHandler("jqGridAddEditAfterComplete",[i,g,e("#"+y),b]),t[f.p.id].afterComplete.call(f,i,g,e("#"+y)),i=null},500)),(t[f.p.id].checkOnSubmit||t[f.p.id].checkOnUpdate)&&(e("#"+y).data("disabled",!1),"_empty"!=t[f.p.id]._savedData[f.p.id+"_id"]))for(var p in t[f.p.id]._savedData)g[p]&&(t[f.p.id]._savedData[p]=g[p]);t[f.p.id].processing=!1,e("#sData",x+"_2").removeClass("ui-state-active");try{e(":input:visible","#"+y)[0].focus()}catch(u){}}},e.jgrid.ajaxOptions,t[f.p.id].ajaxEditOptions);if($.url||t[f.p.id].useDataProxy||(e.isFunction(f.p.dataProxy)?t[f.p.id].useDataProxy=!0:(c[0]=!1,c[1]+=" "+e.jgrid.errors.nourl)),c[0])if(t[f.p.id].useDataProxy){var _=f.p.dataProxy.call(f,$,"set_"+f.p.id);"undefined"==typeof _&&(_=[!0,""]),_[0]===!1?(c[0]=!1,c[1]=_[1]||"Error deleting the selected row!"):($.data.oper==h.addoper&&t[f.p.id].closeAfterAdd&&e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),$.data.oper==h.editoper&&t[f.p.id].closeAfterEdit&&e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}))}else e.ajax($)}c[0]===!1&&(e("#FormError>td",x).html(c[1]),e("#FormError",x).show())}function l(e,t){var i,r=!1;for(i in e)if(e[i]!=t[i]){r=!0;break}return r}function p(){var i=!0;return e("#FormError",x).hide(),t[f.p.id].checkOnUpdate&&(g={},m={},a(),v=e.extend({},g,m),j=l(v,t[f.p.id]._savedData),j&&(e("#"+y).data("disabled",!0),e(".confirm","#"+D.themodal).show(),i=!1)),i}function c(){if("_empty"!==i&&"undefined"!=typeof f.p.savedRow&&f.p.savedRow.length>0&&e.isFunction(e.fn.jqGrid.restoreRow))for(var t=0;t<f.p.savedRow.length;t++)if(f.p.savedRow[t].id==i){e(f).jqGrid("restoreRow",i);break}}function u(t,i){0===t?e("#pData",x+"_2").addClass("ui-state-disabled"):e("#pData",x+"_2").removeClass("ui-state-disabled"),t==i?e("#nData",x+"_2").addClass("ui-state-disabled"):e("#nData",x+"_2").removeClass("ui-state-disabled")}function h(){var t=e(f).jqGrid("getDataIDs"),i=e("#id_g",x).val(),r=e.inArray(i,t);return[r,t]}var f=this;if(f.grid&&i){var g,m,v,j,b,w=f.p.id,y="FrmGrid_"+w,q="TblGrid_"+w,x="#"+e.jgrid.jqID(q),D={themodal:"editmod"+w,modalhead:"edithd"+w,modalcontent:"editcnt"+w,scrollelm:y},$=e.isFunction(t[f.p.id].beforeShowForm)?t[f.p.id].beforeShowForm:!1,_=e.isFunction(t[f.p.id].afterShowForm)?t[f.p.id].afterShowForm:!1,C=e.isFunction(t[f.p.id].beforeInitData)?t[f.p.id].beforeInitData:!1,I=e.isFunction(t[f.p.id].onInitializeForm)?t[f.p.id].onInitializeForm:!1,G=!0,F=1,k=0;y=e.jgrid.jqID(y),"new"===i?(i="_empty",b="add",r.caption=t[f.p.id].addCaption):(r.caption=t[f.p.id].editCaption,b="edit"),r.recreateForm===!0&&null!=e("#"+e.jgrid.jqID(D.themodal)).html()&&e("#"+e.jgrid.jqID(D.themodal)).remove();var S=!0;if(r.checkOnUpdate&&r.jqModal&&!r.modal&&(S=!1),null!=e("#"+e.jgrid.jqID(D.themodal)).html()){if(G=e(f).triggerHandler("jqGridAddEditBeforeInitData",[e("#"+e.jgrid.jqID(y))]),"undefined"==typeof G&&(G=!0),G&&C&&(G=C.call(f,e("#"+y))),G===!1)return;c(),e(".ui-jqdialog-title","#"+e.jgrid.jqID(D.modalhead)).html(r.caption),e("#FormError",x).hide(),t[f.p.id].topinfo?(e(".topinfo",x).html(t[f.p.id].topinfo),e(".tinfo",x).show()):e(".tinfo",x).hide(),t[f.p.id].bottominfo?(e(".bottominfo",x+"_2").html(t[f.p.id].bottominfo),e(".binfo",x+"_2").show()):e(".binfo",x+"_2").hide(),s(i,f,y),"_empty"!=i&&t[f.p.id].viewPagerButtons?e("#pData, #nData",x+"_2").show():e("#pData, #nData",x+"_2").hide(),t[f.p.id].processing===!0&&(t[f.p.id].processing=!1,e("#sData",x+"_2").removeClass("ui-state-active")),e("#"+y).data("disabled")===!0&&(e(".confirm","#"+e.jgrid.jqID(D.themodal)).hide(),
e("#"+y).data("disabled",!1)),e(f).triggerHandler("jqGridAddEditBeforeShowForm",[e("#"+y),b]),$&&$.call(f,e("#"+y)),e("#"+e.jgrid.jqID(D.themodal)).data("onClose",t[f.p.id].onClose),e.jgrid.viewModal("#"+e.jgrid.jqID(D.themodal),{gbox:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,jqM:!1,overlay:r.overlay,modal:r.modal}),S||e(".jqmOverlay").click(function(){return p()?(e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1):!1}),e(f).triggerHandler("jqGridAddEditAfterShowForm",[e("#"+y),b]),_&&_.call(f,e("#"+y))}else{var R=isNaN(r.dataheight)?r.dataheight:r.dataheight+"px",M=e("<form name='FormPost' id='"+y+"' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:"+R+";'></form>").data("disabled",!1),N=e("<table id='"+q+"' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>");if(G=e(f).triggerHandler("jqGridAddEditBeforeInitData",[e("#"+y),b]),"undefined"==typeof G&&(G=!0),G&&C&&(G=C.call(f,e("#"+y))),G===!1)return;c(),e(f.p.colModel).each(function(){var e=this.formoptions;F=Math.max(F,e?e.colpos||0:0),k=Math.max(k,e?e.rowpos||0:0)}),e(M).append(N);var O=e("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+2*F+"'></td></tr>");O[0].rp=0,e(N).append(O),O=e("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+2*F+"'>"+t[f.p.id].topinfo+"</td></tr>"),O[0].rp=0,e(N).append(O);var E="rtl"==f.p.direction?!0:!1,A=E?"nData":"pData",T=E?"pData":"nData";o(i,f,N,F);var P="<a href='javascript:void(0)' id='"+A+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",z="<a href='javascript:void(0)' id='"+T+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",H="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+r.bSubmit+"</a>",L="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+r.bCancel+"</a>",B="<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='"+q+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+(E?z+P:P+z)+"</td><td class='EditButton'>"+H+L+"</td></tr>";if(B+="<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+t[f.p.id].bottominfo+"</td></tr>",B+="</tbody></table>",k>0){var Q=[];e.each(e(N)[0].rows,function(e,t){Q[e]=t}),Q.sort(function(e,t){return e.rp>t.rp?1:e.rp<t.rp?-1:0}),e.each(Q,function(t,i){e("tbody",N).append(i)})}r.gbox="#gbox_"+e.jgrid.jqID(w);var V=!1;r.closeOnEscape===!0&&(r.closeOnEscape=!1,V=!0);var W=e("<span></span>").append(M).append(B);if(e.jgrid.createModal(D,W,r,"#gview_"+e.jgrid.jqID(f.p.id),e("#gbox_"+e.jgrid.jqID(f.p.id))[0]),E&&(e("#pData, #nData",x+"_2").css("float","right"),e(".EditButton",x+"_2").css("text-align","left")),t[f.p.id].topinfo&&e(".tinfo",x).show(),t[f.p.id].bottominfo&&e(".binfo",x+"_2").show(),W=null,B=null,e("#"+e.jgrid.jqID(D.themodal)).keydown(function(i){var a=i.target;if(e("#"+y).data("disabled")===!0)return!1;if(t[f.p.id].savekey[0]===!0&&i.which==t[f.p.id].savekey[1]&&"TEXTAREA"!=a.tagName)return e("#sData",x+"_2").trigger("click"),!1;if(27===i.which)return p()?(V&&e.jgrid.hideModal(this,{gb:r.gbox,jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1):!1;if(t[f.p.id].navkeys[0]===!0){if("_empty"==e("#id_g",x).val())return!0;if(i.which==t[f.p.id].navkeys[1])return e("#pData",x+"_2").trigger("click"),!1;if(i.which==t[f.p.id].navkeys[2])return e("#nData",x+"_2").trigger("click"),!1}}),r.checkOnUpdate&&(e("a.ui-jqdialog-titlebar-close span","#"+e.jgrid.jqID(D.themodal)).removeClass("jqmClose"),e("a.ui-jqdialog-titlebar-close","#"+e.jgrid.jqID(D.themodal)).unbind("click").click(function(){return p()?(e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1):!1})),r.saveicon=e.extend([!0,"left","ui-icon-disk"],r.saveicon),r.closeicon=e.extend([!0,"left","ui-icon-close"],r.closeicon),r.saveicon[0]===!0&&e("#sData",x+"_2").addClass("right"==r.saveicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+r.saveicon[2]+"'></span>"),r.closeicon[0]===!0&&e("#cData",x+"_2").addClass("right"==r.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+r.closeicon[2]+"'></span>"),t[f.p.id].checkOnSubmit||t[f.p.id].checkOnUpdate){H="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+r.bYes+"</a>",z="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+r.bNo+"</a>",L="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+r.bExit+"</a>";var U,X=r.zIndex||999;X++,U=e.browser.msie&&6==e.browser.version?'<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>':"",e("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:"+X+";display:none;'>&#160;"+U+"</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(X+1)+"'>"+r.saveData+"<br/><br/>"+H+z+L+"</div>").insertAfter("#"+y),e("#sNew","#"+e.jgrid.jqID(D.themodal)).click(function(){return d(),e("#"+y).data("disabled",!1),e(".confirm","#"+e.jgrid.jqID(D.themodal)).hide(),!1}),e("#nNew","#"+e.jgrid.jqID(D.themodal)).click(function(){return e(".confirm","#"+e.jgrid.jqID(D.themodal)).hide(),e("#"+y).data("disabled",!1),setTimeout(function(){e(":input","#"+y)[0].focus()},0),!1}),e("#cNew","#"+e.jgrid.jqID(D.themodal)).click(function(){return e(".confirm","#"+e.jgrid.jqID(D.themodal)).hide(),e("#"+y).data("disabled",!1),e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1})}e(f).triggerHandler("jqGridAddEditInitializeForm",[e("#"+y),b]),I&&I.call(f,e("#"+y)),"_empty"!=i&&t[f.p.id].viewPagerButtons?e("#pData,#nData",x+"_2").show():e("#pData,#nData",x+"_2").hide(),e(f).triggerHandler("jqGridAddEditBeforeShowForm",[e("#"+y),b]),$&&$.call(f,e("#"+y)),e("#"+e.jgrid.jqID(D.themodal)).data("onClose",t[f.p.id].onClose),e.jgrid.viewModal("#"+e.jgrid.jqID(D.themodal),{gbox:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,overlay:r.overlay,modal:r.modal}),S||e(".jqmOverlay").click(function(){return p()?(e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1):!1}),e(f).triggerHandler("jqGridAddEditAfterShowForm",[e("#"+y),b]),_&&_.call(f,e("#"+y)),e(".fm-button","#"+e.jgrid.jqID(D.themodal)).hover(function(){e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),e("#sData",x+"_2").click(function(){return g={},m={},e("#FormError",x).hide(),a(),"_empty"==g[f.p.id+"_id"]?d():r.checkOnSubmit===!0?(v=e.extend({},g,m),j=l(v,t[f.p.id]._savedData),j?(e("#"+y).data("disabled",!0),e(".confirm","#"+e.jgrid.jqID(D.themodal)).show()):d()):d(),!1}),e("#cData",x+"_2").click(function(){return p()?(e.jgrid.hideModal("#"+e.jgrid.jqID(D.themodal),{gb:"#gbox_"+e.jgrid.jqID(w),jqm:r.jqModal,onClose:t[f.p.id].onClose}),!1):!1}),e("#nData",x+"_2").click(function(){if(!p())return!1;e("#FormError",x).hide();var t=h();return t[0]=parseInt(t[0],10),-1!=t[0]&&t[1][t[0]+1]&&(e(f).triggerHandler("jqGridAddEditClickPgButtons",["next",e("#"+y),t[1][t[0]]]),e.isFunction(r.onclickPgButtons)&&r.onclickPgButtons.call(f,"next",e("#"+y),t[1][t[0]]),s(t[1][t[0]+1],f,y),e(f).jqGrid("setSelection",t[1][t[0]+1]),e(f).triggerHandler("jqGridAddEditAfterClickPgButtons",["next",e("#"+y),t[1][t[0]]]),e.isFunction(r.afterclickPgButtons)&&r.afterclickPgButtons.call(f,"next",e("#"+y),t[1][t[0]+1]),u(t[0]+1,t[1].length-1)),!1}),e("#pData",x+"_2").click(function(){if(!p())return!1;e("#FormError",x).hide();var t=h();return-1!=t[0]&&t[1][t[0]-1]&&(e(f).triggerHandler("jqGridAddEditClickPgButtons",["prev",e("#"+y),t[1][t[0]]]),e.isFunction(r.onclickPgButtons)&&r.onclickPgButtons.call(f,"prev",e("#"+y),t[1][t[0]]),s(t[1][t[0]-1],f,y),e(f).jqGrid("setSelection",t[1][t[0]-1]),e(f).triggerHandler("jqGridAddEditAfterClickPgButtons",["prev",e("#"+y),t[1][t[0]]]),e.isFunction(r.afterclickPgButtons)&&r.afterclickPgButtons.call(f,"prev",e("#"+y),t[1][t[0]-1]),u(t[0]-1,t[1].length-1)),!1})}var Y=h();u(Y[0],Y[1].length-1)}})},viewGridRow:function(t,i){return i=e.extend({top:0,left:0,width:0,height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,jqModal:!0,closeOnEscape:!1,labelswidth:"30%",closeicon:[],navkeys:[!1,38,40],onClose:null,beforeShowForm:null,beforeInitData:null,viewPagerButtons:!0},e.jgrid.view,i||{}),this.each(function(){function r(){(i.closeOnEscape===!0||i.navkeys[0]===!0)&&setTimeout(function(){e(".ui-jqdialog-titlebar-close","#"+e.jgrid.jqID(f.modalhead)).focus()},0)}function a(t,r,a,o){for(var s,n,d,l,p,c,u,h,f=0,g=[],m=!1,v="<td class='CaptionTD form-view-label ui-widget-content' width='"+i.labelswidth+"'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>",j="",b="<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>",w=["integer","number","currency"],y=0,q=0,x=1;o>=x;x++)j+=1==x?v:b;if(e(r.p.colModel).each(function(){n=this.editrules&&this.editrules.edithidden===!0?!1:this.hidden===!0?!0:!1,n||"right"!==this.align||(this.formatter&&-1!==e.inArray(this.formatter,w)?y=Math.max(y,parseInt(this.width,10)):q=Math.max(q,parseInt(this.width,10)))}),c=0!==y?y:0!==q?q:0,m=e(r).jqGrid("getInd",t),e(r.p.colModel).each(function(t){if(s=this.name,u=!1,n=this.editrules&&this.editrules.edithidden===!0?!1:this.hidden===!0?!0:!1,p=n?"style='display:none'":"",h="boolean"!=typeof this.viewable?!0:this.viewable,"cb"!==s&&"subgrid"!==s&&"rn"!==s&&h){l=m===!1?"":s==r.p.ExpandColumn&&r.p.treeGrid===!0?e("td:eq("+t+")",r.rows[m]).text():e("td:eq("+t+")",r.rows[m]).html(),u="right"===this.align&&0!==c?!0:!1;var i=(e.extend({},this.editoptions||{},{id:s,name:s}),e.extend({},{rowabove:!1,rowcontent:""},this.formoptions||{})),v=parseInt(i.rowpos,10)||f+1,b=parseInt(2*(parseInt(i.colpos,10)||1),10);if(i.rowabove){var w=e("<tr><td class='contentinfo' colspan='"+2*o+"'>"+i.rowcontent+"</td></tr>");e(a).append(w),w[0].rp=v}d=e(a).find("tr[rowpos="+v+"]"),0===d.length&&(d=e("<tr "+p+" rowpos='"+v+"'></tr>").addClass("FormData").attr("id","trv_"+s),e(d).append(j),e(a).append(d),d[0].rp=v),e("td:eq("+(b-2)+")",d[0]).html("<b>"+("undefined"==typeof i.label?r.p.colNames[t]:i.label)+"</b>"),e("td:eq("+(b-1)+")",d[0]).append("<span>"+l+"</span>").attr("id","v_"+s),u&&e("td:eq("+(b-1)+") span",d[0]).css({"text-align":"right",width:c+"px"}),g[f]=t,f++}}),f>0){var D=e("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(2*o-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+t+"'/></td></tr>");D[0].rp=f+99,e(a).append(D)}return g}function o(t,i){var r,a,o,s,n,d=0;n=e(i).jqGrid("getInd",t,!0),n&&(e("td",n).each(function(t){r=i.p.colModel[t].name,a=i.p.colModel[t].editrules&&i.p.colModel[t].editrules.edithidden===!0?!1:i.p.colModel[t].hidden===!0?!0:!1,"cb"!==r&&"subgrid"!==r&&"rn"!==r&&(o=r==i.p.ExpandColumn&&i.p.treeGrid===!0?e(this).text():e(this).html(),s=e.extend({},i.p.colModel[t].editoptions||{}),r=e.jgrid.jqID("v_"+r),e("#"+r+" span","#"+c).html(o),a&&e("#"+r,"#"+c).parents("tr:first").hide(),d++)}),d>0&&e("#id_g","#"+c).val(t))}function s(t,i){0===t?e("#pData","#"+c+"_2").addClass("ui-state-disabled"):e("#pData","#"+c+"_2").removeClass("ui-state-disabled"),t==i?e("#nData","#"+c+"_2").addClass("ui-state-disabled"):e("#nData","#"+c+"_2").removeClass("ui-state-disabled")}function n(){var t=e(d).jqGrid("getDataIDs"),i=e("#id_g","#"+c).val(),r=e.inArray(i,t);return[r,t]}var d=this;if(d.grid&&t){var l=d.p.id,p="ViewGrid_"+e.jgrid.jqID(l),c="ViewTbl_"+e.jgrid.jqID(l),u="ViewGrid_"+l,h="ViewTbl_"+l,f={themodal:"viewmod"+l,modalhead:"viewhd"+l,modalcontent:"viewcnt"+l,scrollelm:p},g=e.isFunction(i.beforeInitData)?i.beforeInitData:!1,m=!0,v=1,j=0;if(null!=e("#"+e.jgrid.jqID(f.themodal)).html()){if(g&&(m=g.call(d,e("#"+p)),"undefined"==typeof m&&(m=!0)),m===!1)return;e(".ui-jqdialog-title","#"+e.jgrid.jqID(f.modalhead)).html(i.caption),e("#FormError","#"+c).hide(),o(t,d),e.isFunction(i.beforeShowForm)&&i.beforeShowForm.call(d,e("#"+p)),e.jgrid.viewModal("#"+e.jgrid.jqID(f.themodal),{gbox:"#gbox_"+e.jgrid.jqID(l),jqm:i.jqModal,jqM:!1,overlay:i.overlay,modal:i.modal}),r()}else{var b=isNaN(i.dataheight)?i.dataheight:i.dataheight+"px",w=e("<form name='FormPost' id='"+u+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+b+";'></form>"),y=e("<table id='"+h+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");if(g&&(m=g.call(d,e("#"+p)),"undefined"==typeof m&&(m=!0)),m===!1)return;e(d.p.colModel).each(function(){var e=this.formoptions;v=Math.max(v,e?e.colpos||0:0),j=Math.max(j,e?e.rowpos||0:0)}),e(w).append(y),a(t,d,y,v);var q="rtl"==d.p.direction?!0:!1,x=q?"nData":"pData",D=q?"pData":"nData",$="<a href='javascript:void(0)' id='"+x+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",_="<a href='javascript:void(0)' id='"+D+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",C="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+i.bClose+"</a>";if(j>0){var I=[];e.each(e(y)[0].rows,function(e,t){I[e]=t}),I.sort(function(e,t){return e.rp>t.rp?1:e.rp<t.rp?-1:0}),e.each(I,function(t,i){e("tbody",y).append(i)})}i.gbox="#gbox_"+e.jgrid.jqID(l);var G=!1;i.closeOnEscape===!0&&(i.closeOnEscape=!1,G=!0);var F=e("<span></span>").append(w).append("<table border='0' class='EditTable' id='"+c+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+i.labelswidth+"'>"+(q?_+$:$+_)+"</td><td class='EditButton'>"+C+"</td></tr></tbody></table>");e.jgrid.createModal(f,F,i,"#gview_"+e.jgrid.jqID(d.p.id),e("#gview_"+e.jgrid.jqID(d.p.id))[0]),q&&(e("#pData, #nData","#"+c+"_2").css("float","right"),e(".EditButton","#"+c+"_2").css("text-align","left")),i.viewPagerButtons||e("#pData, #nData","#"+c+"_2").hide(),F=null,e("#"+f.themodal).keydown(function(t){if(27===t.which)return G&&e.jgrid.hideModal(this,{gb:i.gbox,jqm:i.jqModal,onClose:i.onClose}),!1;if(i.navkeys[0]===!0){if(t.which===i.navkeys[1])return e("#pData","#"+c+"_2").trigger("click"),!1;if(t.which===i.navkeys[2])return e("#nData","#"+c+"_2").trigger("click"),!1}}),i.closeicon=e.extend([!0,"left","ui-icon-close"],i.closeicon),i.closeicon[0]===!0&&e("#cData","#"+c+"_2").addClass("right"==i.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+i.closeicon[2]+"'></span>"),e.isFunction(i.beforeShowForm)&&i.beforeShowForm.call(d,e("#"+p)),e.jgrid.viewModal("#"+e.jgrid.jqID(f.themodal),{gbox:"#gbox_"+e.jgrid.jqID(l),jqm:i.jqModal,modal:i.modal}),e(".fm-button:not(.ui-state-disabled)","#"+c+"_2").hover(function(){e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),r(),e("#cData","#"+c+"_2").click(function(){return e.jgrid.hideModal("#"+e.jgrid.jqID(f.themodal),{gb:"#gbox_"+e.jgrid.jqID(l),jqm:i.jqModal,onClose:i.onClose}),!1}),e("#nData","#"+c+"_2").click(function(){e("#FormError","#"+c).hide();var t=n();return t[0]=parseInt(t[0],10),-1!=t[0]&&t[1][t[0]+1]&&(e.isFunction(i.onclickPgButtons)&&i.onclickPgButtons.call(d,"next",e("#"+p),t[1][t[0]]),o(t[1][t[0]+1],d),e(d).jqGrid("setSelection",t[1][t[0]+1]),e.isFunction(i.afterclickPgButtons)&&i.afterclickPgButtons.call(d,"next",e("#"+p),t[1][t[0]+1]),s(t[0]+1,t[1].length-1)),r(),!1}),e("#pData","#"+c+"_2").click(function(){e("#FormError","#"+c).hide();var t=n();return-1!=t[0]&&t[1][t[0]-1]&&(e.isFunction(i.onclickPgButtons)&&i.onclickPgButtons.call(d,"prev",e("#"+p),t[1][t[0]]),o(t[1][t[0]-1],d),e(d).jqGrid("setSelection",t[1][t[0]-1]),e.isFunction(i.afterclickPgButtons)&&i.afterclickPgButtons.call(d,"prev",e("#"+p),t[1][t[0]-1]),s(t[0]-1,t[1].length-1)),r(),!1})}var k=n();s(k[0],k[1].length-1)}})},delGridRow:function(i,r){return r=e.extend({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.jgrid.del,r||{}),t[e(this)[0].p.id]=r,this.each(function(){var a=this;if(a.grid&&i){var o,s,n,d,l=e.isFunction(t[a.p.id].beforeShowForm),p=e.isFunction(t[a.p.id].afterShowForm),c=e.isFunction(t[a.p.id].beforeInitData)?t[a.p.id].beforeInitData:!1,u=a.p.id,h={},f=!0,g="DelTbl_"+e.jgrid.jqID(u),m="DelTbl_"+u,v={themodal:"delmod"+u,modalhead:"delhd"+u,modalcontent:"delcnt"+u,scrollelm:g};if(jQuery.isArray(i)&&(i=i.join()),null!=e("#"+e.jgrid.jqID(v.themodal)).html()){if(c&&(f=c.call(a,e("#"+g)),"undefined"==typeof f&&(f=!0)),f===!1)return;e("#DelData>td","#"+g).text(i),e("#DelError","#"+g).hide(),t[a.p.id].processing===!0&&(t[a.p.id].processing=!1,e("#dData","#"+g).removeClass("ui-state-active")),l&&t[a.p.id].beforeShowForm.call(a,e("#"+g)),e.jgrid.viewModal("#"+e.jgrid.jqID(v.themodal),{gbox:"#gbox_"+e.jgrid.jqID(u),jqm:t[a.p.id].jqModal,jqM:!1,overlay:t[a.p.id].overlay,modal:t[a.p.id].modal}),p&&t[a.p.id].afterShowForm.call(a,e("#"+g))}else{var j=isNaN(t[a.p.id].dataheight)?t[a.p.id].dataheight:t[a.p.id].dataheight+"px",b="<div id='"+m+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+j+";'>";b+="<table class='DelTable'><tbody>",b+="<tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>",b+="<tr id='DelData' style='display:none'><td >"+i+"</td></tr>",b+='<tr><td class="delmsg" style="white-space:pre;">'+t[a.p.id].msg+"</td></tr><tr><td >&#160;</td></tr>",b+="</tbody></table></div>";var w="<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+r.bSubmit+"</a>",y="<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+r.bCancel+"</a>";if(b+="<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+g+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+w+"&#160;"+y+"</td></tr></tbody></table>",r.gbox="#gbox_"+e.jgrid.jqID(u),e.jgrid.createModal(v,b,r,"#gview_"+e.jgrid.jqID(a.p.id),e("#gview_"+e.jgrid.jqID(a.p.id))[0]),c&&(f=c.call(a,e("#"+g)),"undefined"==typeof f&&(f=!0)),f===!1)return;e(".fm-button","#"+g+"_2").hover(function(){e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),r.delicon=e.extend([!0,"left","ui-icon-scissors"],t[a.p.id].delicon),r.cancelicon=e.extend([!0,"left","ui-icon-cancel"],t[a.p.id].cancelicon),r.delicon[0]===!0&&e("#dData","#"+g+"_2").addClass("right"==r.delicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+r.delicon[2]+"'></span>"),r.cancelicon[0]===!0&&e("#eData","#"+g+"_2").addClass("right"==r.cancelicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+r.cancelicon[2]+"'></span>"),e("#dData","#"+g+"_2").click(function(){var i=[!0,""];h={};var l=e("#DelData>td","#"+g).text();if(e.isFunction(t[a.p.id].onclickSubmit)&&(h=t[a.p.id].onclickSubmit.call(a,t[a.p.id],l)||{}),e.isFunction(t[a.p.id].beforeSubmit)&&(i=t[a.p.id].beforeSubmit.call(a,l)),i[0]&&!t[a.p.id].processing){if(t[a.p.id].processing=!0,n=a.p.prmNames,o=e.extend({},t[a.p.id].delData,h),d=n.oper,o[d]=n.deloper,s=n.id,l=String(l).split(","),!l.length)return!1;for(var p in l)l.hasOwnProperty(p)&&(l[p]=e.jgrid.stripPref(a.p.idPrefix,l[p]));o[s]=l.join(),e(this).addClass("ui-state-active");var c=e.extend({url:t[a.p.id].url?t[a.p.id].url:e(a).jqGrid("getGridParam","editurl"),type:t[a.p.id].mtype,data:e.isFunction(t[a.p.id].serializeDelData)?t[a.p.id].serializeDelData.call(a,o):o,complete:function(s,n){if("success"!=n?(i[0]=!1,e.isFunction(t[a.p.id].errorTextFormat)?i[1]=t[a.p.id].errorTextFormat.call(a,s):i[1]=n+" Status: '"+s.statusText+"'. Error code: "+s.status):e.isFunction(t[a.p.id].afterSubmit)&&(i=t[a.p.id].afterSubmit.call(a,s,o)),i[0]===!1)e("#DelError>td","#"+g).html(i[1]),e("#DelError","#"+g).show();else{if(t[a.p.id].reloadAfterSubmit&&"local"!=a.p.datatype)e(a).trigger("reloadGrid");else{if(a.p.treeGrid===!0)try{e(a).jqGrid("delTreeNode",a.p.idPrefix+l[0])}catch(d){}else for(var p=0;p<l.length;p++)e(a).jqGrid("delRowData",a.p.idPrefix+l[p]);a.p.selrow=null,a.p.selarrrow=[]}e.isFunction(t[a.p.id].afterComplete)&&setTimeout(function(){t[a.p.id].afterComplete.call(a,s,l)},500)}t[a.p.id].processing=!1,e("#dData","#"+g+"_2").removeClass("ui-state-active"),i[0]&&e.jgrid.hideModal("#"+e.jgrid.jqID(v.themodal),{gb:"#gbox_"+e.jgrid.jqID(u),jqm:r.jqModal,onClose:t[a.p.id].onClose})}},e.jgrid.ajaxOptions,t[a.p.id].ajaxDelOptions);if(c.url||t[a.p.id].useDataProxy||(e.isFunction(a.p.dataProxy)?t[a.p.id].useDataProxy=!0:(i[0]=!1,i[1]+=" "+e.jgrid.errors.nourl)),i[0])if(t[a.p.id].useDataProxy){var f=a.p.dataProxy.call(a,c,"del_"+a.p.id);"undefined"==typeof f&&(f=[!0,""]),f[0]===!1?(i[0]=!1,i[1]=f[1]||"Error deleting the selected row!"):e.jgrid.hideModal("#"+e.jgrid.jqID(v.themodal),{gb:"#gbox_"+e.jgrid.jqID(u),jqm:r.jqModal,onClose:t[a.p.id].onClose})}else e.ajax(c)}return i[0]===!1&&(e("#DelError>td","#"+g).html(i[1]),e("#DelError","#"+g).show()),!1}),e("#eData","#"+g+"_2").click(function(){return e.jgrid.hideModal("#"+e.jgrid.jqID(v.themodal),{gb:"#gbox_"+e.jgrid.jqID(u),jqm:t[a.p.id].jqModal,onClose:t[a.p.id].onClose}),!1}),l&&t[a.p.id].beforeShowForm.call(a,e("#"+g)),e.jgrid.viewModal("#"+e.jgrid.jqID(v.themodal),{gbox:"#gbox_"+e.jgrid.jqID(u),jqm:t[a.p.id].jqModal,overlay:t[a.p.id].overlay,modal:t[a.p.id].modal}),p&&t[a.p.id].afterShowForm.call(a,e("#"+g))}t[a.p.id].closeOnEscape===!0&&setTimeout(function(){e(".ui-jqdialog-titlebar-close","#"+e.jgrid.jqID(v.modalhead)).focus()},0)}})},navGrid:function(t,i,r,a,o,s,n){return i=e.extend({edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",del:!0,delicon:"ui-icon-trash",search:!0,searchicon:"ui-icon-search",refresh:!0,refreshicon:"ui-icon-refresh",refreshstate:"firstpage",view:!1,viewicon:"ui-icon-document",position:"left",closeOnEscape:!0,beforeRefresh:null,afterRefresh:null,cloneToTop:!1,alertwidth:200,alertheight:"auto",alerttop:null,alertleft:null,alertzIndex:null},e.jgrid.nav,i||{}),this.each(function(){if(!this.nav){var d,l,p={themodal:"alertmod",modalhead:"alerthd",modalcontent:"alertcnt"},c=this;if(c.grid&&"string"==typeof t){null===e("#"+p.themodal).html()&&(i.alerttop||i.alertleft||("undefined"!=typeof window.innerWidth?(i.alertleft=window.innerWidth,i.alerttop=window.innerHeight):"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.clientWidth&&0!==document.documentElement.clientWidth?(i.alertleft=document.documentElement.clientWidth,i.alerttop=document.documentElement.clientHeight):(i.alertleft=1024,i.alerttop=768),i.alertleft=i.alertleft/2-parseInt(i.alertwidth,10)/2,i.alerttop=i.alerttop/2-25),e.jgrid.createModal(p,"<div>"+i.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+e.jgrid.jqID(c.p.id),jqModal:!0,drag:!0,resize:!0,caption:i.alertcap,top:i.alerttop,left:i.alertleft,width:i.alertwidth,height:i.alertheight,closeOnEscape:i.closeOnEscape,zIndex:i.alertzIndex},"","",!0));var u=1;i.cloneToTop&&c.p.toppager&&(u=2);for(var h=0;u>h;h++){var f,g,m,v=e("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),j="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>";0===h?(g=t,m=c.p.id,g==c.p.toppager&&(m+="_top",u=1)):(g=c.p.toppager,m=c.p.id+"_top"),"rtl"==c.p.direction&&e(v).attr("dir","rtl").css("float","right"),i.add&&(a=a||{},f=e("<td class='ui-pg-button ui-corner-all'></td>"),e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.addicon+"'></span>"+i.addtext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.addtitle||"",id:a.id||"add_"+m}).click(function(){return e(this).hasClass("ui-state-disabled")||(e.isFunction(i.addfunc)?i.addfunc.call(c):e(c).jqGrid("editGridRow","new",a)),!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),f=null),i.edit&&(f=e("<td class='ui-pg-button ui-corner-all'></td>"),r=r||{},e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.editicon+"'></span>"+i.edittext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.edittitle||"",id:r.id||"edit_"+m}).click(function(){if(!e(this).hasClass("ui-state-disabled")){var t=c.p.selrow;t?e.isFunction(i.editfunc)?i.editfunc.call(c,t):e(c).jqGrid("editGridRow",t,r):(e.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+e.jgrid.jqID(c.p.id),jqm:!0}),e("#jqg_alrt").focus())}return!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),f=null),i.view&&(f=e("<td class='ui-pg-button ui-corner-all'></td>"),n=n||{},e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.viewicon+"'></span>"+i.viewtext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.viewtitle||"",id:n.id||"view_"+m}).click(function(){if(!e(this).hasClass("ui-state-disabled")){var t=c.p.selrow;t?e.isFunction(i.viewfunc)?i.viewfunc.call(c,t):e(c).jqGrid("viewGridRow",t,n):(e.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+e.jgrid.jqID(c.p.id),jqm:!0}),e("#jqg_alrt").focus())}return!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),f=null),i.del&&(f=e("<td class='ui-pg-button ui-corner-all'></td>"),o=o||{},e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.delicon+"'></span>"+i.deltext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.deltitle||"",id:o.id||"del_"+m}).click(function(){if(!e(this).hasClass("ui-state-disabled")){var t;c.p.multiselect?(t=c.p.selarrrow,0===t.length&&(t=null)):t=c.p.selrow,t?e.isFunction(i.delfunc)?i.delfunc.call(c,t):e(c).jqGrid("delGridRow",t,o):(e.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+e.jgrid.jqID(c.p.id),jqm:!0}),e("#jqg_alrt").focus())}return!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),f=null),(i.add||i.edit||i.del||i.view)&&e("tr",v).append(j),i.search&&(f=e("<td class='ui-pg-button ui-corner-all'></td>"),s=s||{},e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.searchicon+"'></span>"+i.searchtext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.searchtitle||"",id:s.id||"search_"+m}).click(function(){return e(this).hasClass("ui-state-disabled")||(e.isFunction(i.searchfunc)?i.searchfunc.call(c,s):e(c).jqGrid("searchGrid",s)),!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),s.showOnLoad&&s.showOnLoad===!0&&e(f,v).click(),f=null),i.refresh&&(f=e("<td class='ui-pg-button ui-corner-all'></td>"),e(f).append("<div class='ui-pg-div'><span class='ui-icon "+i.refreshicon+"'></span>"+i.refreshtext+"</div>"),e("tr",v).append(f),e(f,v).attr({title:i.refreshtitle||"",id:"refresh_"+m}).click(function(){if(!e(this).hasClass("ui-state-disabled")){e.isFunction(i.beforeRefresh)&&i.beforeRefresh.call(c),c.p.search=!1;try{var t=c.p.id;c.p.postData.filters="",e("#fbox_"+e.jgrid.jqID(t)).jqFilter("resetFilter"),e.isFunction(c.clearToolbar)&&c.clearToolbar.call(c,!1)}catch(r){}switch(i.refreshstate){case"firstpage":e(c).trigger("reloadGrid",[{page:1}]);break;case"current":e(c).trigger("reloadGrid",[{current:!0}])}e.isFunction(i.afterRefresh)&&i.afterRefresh.call(c)}return!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")}),f=null),l=e(".ui-jqgrid").css("font-size")||"11px",e("body").append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+l+";visibility:hidden;' ></div>"),d=e(v).clone().appendTo("#testpg2").width(),e("#testpg2").remove(),e(g+"_"+i.position,g).append(v),c.p._nvtd&&(d>c.p._nvtd[0]&&(e(g+"_"+i.position,g).width(d),c.p._nvtd[0]=d),c.p._nvtd[1]=d),l=null,d=null,v=null,this.nav=!0}}}})},navButtonAdd:function(t,i){return i=e.extend({caption:"newButton",title:"",buttonicon:"ui-icon-newwin",onClickButton:null,position:"last",cursor:"pointer"},i||{}),this.each(function(){if(this.grid){"string"==typeof t&&0!==t.indexOf("#")&&(t="#"+e.jgrid.jqID(t));var r=e(".navtable",t)[0],a=this;if(r){if(i.id&&null!=e("#"+e.jgrid.jqID(i.id),r).html())return;var o=e("<td></td>");"NONE"==i.buttonicon.toString().toUpperCase()?e(o).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>"+i.caption+"</div>"):e(o).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon "+i.buttonicon+"'></span>"+i.caption+"</div>"),i.id&&e(o).attr("id",i.id),"first"==i.position?0===r.rows[0].cells.length?e("tr",r).append(o):e("tr td:eq(0)",r).before(o):e("tr",r).append(o),e(o,r).attr("title",i.title||"").click(function(t){return e(this).hasClass("ui-state-disabled")||e.isFunction(i.onClickButton)&&i.onClickButton.call(a,t),!1}).hover(function(){e(this).hasClass("ui-state-disabled")||e(this).addClass("ui-state-hover")},function(){e(this).removeClass("ui-state-hover")})}}})},navSeparatorAdd:function(t,i){return i=e.extend({sepclass:"ui-separator",sepcontent:""},i||{}),this.each(function(){if(this.grid){"string"==typeof t&&0!==t.indexOf("#")&&(t="#"+e.jgrid.jqID(t));var r=e(".navtable",t)[0];if(r){var a="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+i.sepclass+"'></span>"+i.sepcontent+"</td>";e("tr",r).append(a)}}})},GridToForm:function(t,i){return this.each(function(){var r=this;if(r.grid){var a=e(r).jqGrid("getRowData",t);if(a)for(var o in a)e("[name="+e.jgrid.jqID(o)+"]",i).is("input:radio")||e("[name="+e.jgrid.jqID(o)+"]",i).is("input:checkbox")?e("[name="+e.jgrid.jqID(o)+"]",i).each(function(){e(this).val()==a[o]?e(this)[r.p.useProp?"prop":"attr"]("checked",!0):e(this)[r.p.useProp?"prop":"attr"]("checked",!1)}):e("[name="+e.jgrid.jqID(o)+"]",i).val(a[o])}})},FormToGrid:function(t,i,r,a){return this.each(function(){var o=this;if(o.grid){r||(r="set"),a||(a="first");var s=e(i).serializeArray(),n={};e.each(s,function(e,t){n[t.name]=t.value}),"add"==r?e(o).jqGrid("addRowData",t,n,a):"set"==r&&e(o).jqGrid("setRowData",t,n)}})}})}(jQuery),function(e){"use strict";e.jgrid.inlineEdit=e.jgrid.inlineEdit||{},e.jgrid.extend({editRow:function(t,i,r,a,o,s,n,d,l){var p={},c=e.makeArray(arguments).slice(1);return"object"===e.type(c[0])?p=c[0]:("undefined"!=typeof i&&(p.keys=i),e.isFunction(r)&&(p.oneditfunc=r),e.isFunction(a)&&(p.successfunc=a),"undefined"!=typeof o&&(p.url=o),"undefined"!=typeof s&&(p.extraparam=s),e.isFunction(n)&&(p.aftersavefunc=n),e.isFunction(d)&&(p.errorfunc=d),e.isFunction(l)&&(p.afterrestorefunc=l)),p=e.extend(!0,{keys:!1,oneditfunc:null,successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,mtype:"POST"},e.jgrid.inlineEdit,p),this.each(function(){var i,r,a,o,s,n=this,d=0,l=null,c={};n.grid&&(o=e(n).jqGrid("getInd",t,!0),o!==!1&&(a=e(o).attr("editable")||"0","0"!=a||e(o).hasClass("not-editable-row")||(s=n.p.colModel,e('td[role="gridcell"]',o).each(function(a){i=s[a].name;var o=n.p.treeGrid===!0&&i==n.p.ExpandColumn;if(o)r=e("span:first",this).html();else try{r=e.unformat.call(n,this,{rowId:t,colModel:s[a]},a)}catch(p){r=s[a].edittype&&"textarea"==s[a].edittype?e(this).text():e(this).html()}if("cb"!=i&&"subgrid"!=i&&"rn"!=i&&(n.p.autoencode&&(r=e.jgrid.htmlDecode(r)),c[i]=r,s[a].editable===!0)){null===l&&(l=a),o?e("span:first",this).html(""):e(this).html("");var u=e.extend({},s[a].editoptions||{},{id:t+"_"+i,name:i});s[a].edittype||(s[a].edittype="text"),("&nbsp;"==r||"&#160;"==r||1==r.length&&160==r.charCodeAt(0))&&(r="");var h=e.jgrid.createEl.call(n,s[a].edittype,u,r,!0,e.extend({},e.jgrid.ajaxOptions,n.p.ajaxSelectOptions||{}));e(h).addClass("editable"),
o?e("span:first",this).append(h):e(this).append(h),"select"==s[a].edittype&&"undefined"!=typeof s[a].editoptions&&s[a].editoptions.multiple===!0&&"undefined"==typeof s[a].editoptions.dataUrl&&e.browser.msie&&e(h).width(e(h).width()),d++}}),d>0&&(c.id=t,n.p.savedRow.push(c),e(o).attr("editable","1"),e("td:eq("+l+") input",o).focus(),p.keys===!0&&e(o).bind("keydown",function(i){if(27===i.keyCode){if(e(n).jqGrid("restoreRow",t,p.afterrestorefunc),n.p._inlinenav)try{e(n).jqGrid("showAddEditButtons")}catch(r){}return!1}if(13===i.keyCode){var a=i.target;if("TEXTAREA"==a.tagName)return!0;if(e(n).jqGrid("saveRow",t,p)&&n.p._inlinenav)try{e(n).jqGrid("showAddEditButtons")}catch(o){}return!1}}),e(n).triggerHandler("jqGridInlineEditRow",[t,p]),e.isFunction(p.oneditfunc)&&p.oneditfunc.call(n,t)))))})},saveRow:function(t,i,r,a,o,s,n){var d=e.makeArray(arguments).slice(1),l={};"object"===e.type(d[0])?l=d[0]:(e.isFunction(i)&&(l.successfunc=i),"undefined"!=typeof r&&(l.url=r),"undefined"!=typeof a&&(l.extraparam=a),e.isFunction(o)&&(l.aftersavefunc=o),e.isFunction(s)&&(l.errorfunc=s),e.isFunction(n)&&(l.afterrestorefunc=n)),l=e.extend(!0,{successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,mtype:"POST"},e.jgrid.inlineEdit,l);var p,c,u,h,f,g=!1,m=this[0],v={},j={},b={};if(!m.grid)return g;if(f=e(m).jqGrid("getInd",t,!0),f===!1)return g;if(c=e(f).attr("editable"),l.url=l.url?l.url:m.p.editurl,"1"===c){var w;if(e('td[role="gridcell"]',f).each(function(t){if(w=m.p.colModel[t],p=w.name,"cb"!=p&&"subgrid"!=p&&w.editable===!0&&"rn"!=p&&!e(this).hasClass("not-editable-cell")){switch(w.edittype){case"checkbox":var i=["Yes","No"];w.editoptions&&(i=w.editoptions.value.split(":")),v[p]=e("input",this).is(":checked")?i[0]:i[1];break;case"text":case"password":case"textarea":case"button":v[p]=e("input, textarea",this).val();break;case"select":if(w.editoptions.multiple){var r=e("select",this),a=[];v[p]=e(r).val(),v[p]?v[p]=v[p].join(","):v[p]="",e("select option:selected",this).each(function(t,i){a[t]=e(i).text()}),j[p]=a.join(",")}else v[p]=e("select option:selected",this).val(),j[p]=e("select option:selected",this).text();w.formatter&&"select"==w.formatter&&(j={});break;case"custom":try{if(!w.editoptions||!e.isFunction(w.editoptions.custom_value))throw"e1";if(v[p]=w.editoptions.custom_value.call(m,e(".customelement",this),"get"),void 0===v[p])throw"e2"}catch(o){"e1"==o&&e.jgrid.info_dialog(e.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.nodefined,e.jgrid.edit.bClose),"e2"==o?e.jgrid.info_dialog(e.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.novalue,e.jgrid.edit.bClose):e.jgrid.info_dialog(e.jgrid.errors.errcap,o.message,e.jgrid.edit.bClose)}}if(h=e.jgrid.checkValues(v[p],t,m),h[0]===!1)return h[1]=v[p]+" "+h[1],!1;m.p.autoencode&&(v[p]=e.jgrid.htmlEncode(v[p])),"clientArray"!==l.url&&w.editoptions&&w.editoptions.NullIfEmpty===!0&&""===v[p]&&(b[p]="null")}}),h[0]===!1){try{var y=e.jgrid.findPos(e("#"+e.jgrid.jqID(t),m.grid.bDiv)[0]);e.jgrid.info_dialog(e.jgrid.errors.errcap,h[1],e.jgrid.edit.bClose,{left:y[0],top:y[1]})}catch(q){alert(h[1])}return g}var x,D,$;if(D=m.p.prmNames,$=D.oper,x=D.id,v&&(v[$]=D.editoper,v[x]=t,"undefined"==typeof m.p.inlineData&&(m.p.inlineData={}),v=e.extend({},v,m.p.inlineData,l.extraparam)),"clientArray"==l.url){v=e.extend({},v,j),m.p.autoencode&&e.each(v,function(t,i){v[t]=e.jgrid.htmlDecode(i)});var _=e(m).jqGrid("setRowData",t,v);e(f).attr("editable","0");for(var C=0;C<m.p.savedRow.length;C++)if(m.p.savedRow[C].id==t){u=C;break}u>=0&&m.p.savedRow.splice(u,1),e(m).triggerHandler("jqGridInlineAfterSaveRow",[t,_,v,l]),e.isFunction(l.aftersavefunc)&&l.aftersavefunc.call(m,t,_),g=!0,e(f).unbind("keydown")}else e("#lui_"+e.jgrid.jqID(m.p.id)).show(),b=e.extend({},v,b),b[x]=e.jgrid.stripPref(m.p.idPrefix,b[x]),e.ajax(e.extend({url:l.url,data:e.isFunction(m.p.serializeRowData)?m.p.serializeRowData.call(m,b):b,type:l.mtype,async:!1,complete:function(i,r){if(e("#lui_"+e.jgrid.jqID(m.p.id)).hide(),"success"===r){var a,o=!0;if(a=e(m).triggerHandler("jqGridInlineSuccessSaveRow",[i,t,l]),e.isArray(a)||(a=[!0,v]),a[0]&&e.isFunction(l.successfunc)&&(a=l.successfunc.call(m,i)),e.isArray(a)?(o=a[0],v=a[1]?a[1]:v):o=a,o===!0){m.p.autoencode&&e.each(v,function(t,i){v[t]=e.jgrid.htmlDecode(i)}),v=e.extend({},v,j),e(m).jqGrid("setRowData",t,v),e(f).attr("editable","0");for(var s=0;s<m.p.savedRow.length;s++)if(m.p.savedRow[s].id==t){u=s;break}u>=0&&m.p.savedRow.splice(u,1),e(m).triggerHandler("jqGridInlineAfterSaveRow",[t,i,v,l]),e.isFunction(l.aftersavefunc)&&l.aftersavefunc.call(m,t,i),g=!0,e(f).unbind("keydown")}else e(m).triggerHandler("jqGridInlineErrorSaveRow",[t,i,r,null,l]),e.isFunction(l.errorfunc)&&l.errorfunc.call(m,t,i,r,null),l.restoreAfterError===!0&&e(m).jqGrid("restoreRow",t,l.afterrestorefunc)}},error:function(i,r,a){if(e("#lui_"+e.jgrid.jqID(m.p.id)).hide(),e(m).triggerHandler("jqGridInlineErrorSaveRow",[t,i,r,a,l]),e.isFunction(l.errorfunc))l.errorfunc.call(m,t,i,r,a);else try{e.jgrid.info_dialog(e.jgrid.errors.errcap,'<div class="ui-state-error">'+i.responseText+"</div>",e.jgrid.edit.bClose,{buttonalign:"right"})}catch(o){alert(i.responseText)}l.restoreAfterError===!0&&e(m).jqGrid("restoreRow",t,l.afterrestorefunc)}},e.jgrid.ajaxOptions,m.p.ajaxRowOptions||{}))}return g},restoreRow:function(t,i){var r=e.makeArray(arguments).slice(1),a={};return"object"===e.type(r[0])?a=r[0]:e.isFunction(i)&&(a.afterrestorefunc=i),a=e.extend(!0,e.jgrid.inlineEdit,a),this.each(function(){var i,r,o=this,s={};if(o.grid&&(r=e(o).jqGrid("getInd",t,!0),r!==!1)){for(var n=0;n<o.p.savedRow.length;n++)if(o.p.savedRow[n].id==t){i=n;break}if(i>=0){if(e.isFunction(e.fn.datepicker))try{e("input.hasDatepicker","#"+e.jgrid.jqID(r.id)).datepicker("hide")}catch(d){}e.each(o.p.colModel,function(){this.editable===!0&&this.name in o.p.savedRow[i]&&(s[this.name]=o.p.savedRow[i][this.name])}),e(o).jqGrid("setRowData",t,s),e(r).attr("editable","0").unbind("keydown"),o.p.savedRow.splice(i,1),e("#"+e.jgrid.jqID(t),"#"+e.jgrid.jqID(o.p.id)).hasClass("jqgrid-new-row")&&setTimeout(function(){e(o).jqGrid("delRowData",t)},0)}e(o).triggerHandler("jqGridInlineAfterRestoreRow",[t]),e.isFunction(a.afterrestorefunc)&&a.afterrestorefunc.call(o,t)}})},addRow:function(t){return t=e.extend(!0,{rowID:"new_row",initdata:{},position:"first",useDefValues:!0,useFormatter:!1,addRowParams:{extraparam:{}}},t||{}),this.each(function(){if(this.grid){var i=this;if(t.useDefValues===!0&&e(i.p.colModel).each(function(){if(this.editoptions&&this.editoptions.defaultValue){var r=this.editoptions.defaultValue,a=e.isFunction(r)?r.call(i):r;t.initdata[this.name]=a}}),e(i).jqGrid("addRowData",t.rowID,t.initdata,t.position),t.rowID=i.p.idPrefix+t.rowID,e("#"+e.jgrid.jqID(t.rowID),"#"+e.jgrid.jqID(i.p.id)).addClass("jqgrid-new-row"),t.useFormatter)e("#"+e.jgrid.jqID(t.rowID)+" .ui-inline-edit","#"+e.jgrid.jqID(i.p.id)).click();else{var r=i.p.prmNames,a=r.oper;t.addRowParams.extraparam[a]=r.addoper,e(i).jqGrid("editRow",t.rowID,t.addRowParams),e(i).jqGrid("setSelection",t.rowID)}}})},inlineNav:function(t,i){return i=e.extend({edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",save:!0,saveicon:"ui-icon-disk",cancel:!0,cancelicon:"ui-icon-cancel",addParams:{useFormatter:!1,rowID:"new_row"},editParams:{},restoreAfterSelect:!0},e.jgrid.nav,i||{}),this.each(function(){if(this.grid){var r,a=this,o=e.jgrid.jqID(a.p.id);if(a.p._inlinenav=!0,i.addParams.useFormatter===!0){var s,n=a.p.colModel;for(s=0;s<n.length;s++)if(n[s].formatter&&"actions"===n[s].formatter){if(n[s].formatoptions){var d={keys:!1,onEdit:null,onSuccess:null,afterSave:null,onError:null,afterRestore:null,extraparam:{},url:null},l=e.extend(d,n[s].formatoptions);i.addParams.addRowParams={keys:l.keys,oneditfunc:l.onEdit,successfunc:l.onSuccess,url:l.url,extraparam:l.extraparam,aftersavefunc:l.afterSavef,errorfunc:l.onError,afterrestorefunc:l.afterRestore}}break}}i.add&&e(a).jqGrid("navButtonAdd",t,{caption:i.addtext,title:i.addtitle,buttonicon:i.addicon,id:a.p.id+"_iladd",onClickButton:function(){e(a).jqGrid("addRow",i.addParams),i.addParams.useFormatter||(e("#"+o+"_ilsave").removeClass("ui-state-disabled"),e("#"+o+"_ilcancel").removeClass("ui-state-disabled"),e("#"+o+"_iladd").addClass("ui-state-disabled"),e("#"+o+"_iledit").addClass("ui-state-disabled"))}}),i.edit&&e(a).jqGrid("navButtonAdd",t,{caption:i.edittext,title:i.edittitle,buttonicon:i.editicon,id:a.p.id+"_iledit",onClickButton:function(){var t=e(a).jqGrid("getGridParam","selrow");t?(e(a).jqGrid("editRow",t,i.editParams),e("#"+o+"_ilsave").removeClass("ui-state-disabled"),e("#"+o+"_ilcancel").removeClass("ui-state-disabled"),e("#"+o+"_iladd").addClass("ui-state-disabled"),e("#"+o+"_iledit").addClass("ui-state-disabled")):(e.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+o,jqm:!0}),e("#jqg_alrt").focus())}}),i.save&&(e(a).jqGrid("navButtonAdd",t,{caption:i.savetext||"",title:i.savetitle||"Save row",buttonicon:i.saveicon,id:a.p.id+"_ilsave",onClickButton:function(){var t=a.p.savedRow[0].id;if(t){var r=a.p.prmNames,s=r.oper;i.editParams.extraparam||(i.editParams.extraparam={}),e("#"+e.jgrid.jqID(t),"#"+o).hasClass("jqgrid-new-row")?i.editParams.extraparam[s]=r.addoper:i.editParams.extraparam[s]=r.editoper,e(a).jqGrid("saveRow",t,i.editParams)&&e(a).jqGrid("showAddEditButtons")}else e.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+o,jqm:!0}),e("#jqg_alrt").focus()}}),e("#"+o+"_ilsave").addClass("ui-state-disabled")),i.cancel&&(e(a).jqGrid("navButtonAdd",t,{caption:i.canceltext||"",title:i.canceltitle||"Cancel row editing",buttonicon:i.cancelicon,id:a.p.id+"_ilcancel",onClickButton:function(){var t=a.p.savedRow[0].id;t?(e(a).jqGrid("restoreRow",t,i.editParams),e(a).jqGrid("showAddEditButtons")):(e.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+o,jqm:!0}),e("#jqg_alrt").focus())}}),e("#"+o+"_ilcancel").addClass("ui-state-disabled")),i.restoreAfterSelect===!0&&(r=e.isFunction(a.p.beforeSelectRow)?a.p.beforeSelectRow:!1,a.p.beforeSelectRow=function(t,o){var s=!0;return a.p.savedRow.length>0&&a.p._inlinenav===!0&&t!==a.p.selrow&&null!==a.p.selrow&&(a.p.selrow==i.addParams.rowID?e(a).jqGrid("delRowData",a.p.selrow):e(a).jqGrid("restoreRow",a.p.selrow,i.editParams),e(a).jqGrid("showAddEditButtons")),r&&(s=r.call(a,t,o)),s})}})},showAddEditButtons:function(){return this.each(function(){if(this.grid){var t=e.jgrid.jqID(this.p.id);e("#"+t+"_ilsave").addClass("ui-state-disabled"),e("#"+t+"_ilcancel").addClass("ui-state-disabled"),e("#"+t+"_iladd").removeClass("ui-state-disabled"),e("#"+t+"_iledit").removeClass("ui-state-disabled")}})}})}(jQuery),function(e){"use strict";e.jgrid.extend({editCell:function(t,i,r){return this.each(function(){var a,o,s,n,d=this;if(d.grid&&d.p.cellEdit===!0){if(i=parseInt(i,10),d.p.selrow=d.rows[t].id,d.p.knv||e(d).jqGrid("GridNav"),d.p.savedRow.length>0){if(r===!0&&t==d.p.iRow&&i==d.p.iCol)return;e(d).jqGrid("saveCell",d.p.savedRow[0].id,d.p.savedRow[0].ic)}else window.setTimeout(function(){e("#"+e.jgrid.jqID(d.p.knv)).attr("tabindex","-1").focus()},0);if(n=d.p.colModel[i],a=n.name,"subgrid"!=a&&"cb"!=a&&"rn"!=a){if(s=e("td:eq("+i+")",d.rows[t]),n.editable!==!0||r!==!0||s.hasClass("not-editable-cell"))parseInt(d.p.iCol,10)>=0&&parseInt(d.p.iRow,10)>=0&&(e("td:eq("+d.p.iCol+")",d.rows[d.p.iRow]).removeClass("edit-cell ui-state-highlight"),e(d.rows[d.p.iRow]).removeClass("selected-row ui-state-hover")),s.addClass("edit-cell ui-state-highlight"),e(d.rows[t]).addClass("selected-row ui-state-hover"),o=s.html().replace(/\&#160\;/gi,""),e(d).triggerHandler("jqGridSelectCell",[d.rows[t].id,a,o,t,i]),e.isFunction(d.p.onSelectCell)&&d.p.onSelectCell.call(d,d.rows[t].id,a,o,t,i);else{parseInt(d.p.iCol,10)>=0&&parseInt(d.p.iRow,10)>=0&&(e("td:eq("+d.p.iCol+")",d.rows[d.p.iRow]).removeClass("edit-cell ui-state-highlight"),e(d.rows[d.p.iRow]).removeClass("selected-row ui-state-hover")),e(s).addClass("edit-cell ui-state-highlight"),e(d.rows[t]).addClass("selected-row ui-state-hover");try{o=e.unformat.call(d,s,{rowId:d.rows[t].id,colModel:n},i)}catch(l){o=n.edittype&&"textarea"==n.edittype?e(s).text():e(s).html()}if(d.p.autoencode&&(o=e.jgrid.htmlDecode(o)),n.edittype||(n.edittype="text"),d.p.savedRow.push({id:t,ic:i,name:a,v:o}),("&nbsp;"===o||"&#160;"===o||1===o.length&&160===o.charCodeAt(0))&&(o=""),e.isFunction(d.p.formatCell)){var p=d.p.formatCell.call(d,d.rows[t].id,a,o,t,i);void 0!==p&&(o=p)}var c=e.extend({},n.editoptions||{},{id:t+"_"+a,name:a}),u=e.jgrid.createEl.call(d,n.edittype,c,o,!0,e.extend({},e.jgrid.ajaxOptions,d.p.ajaxSelectOptions||{}));e(d).triggerHandler("jqGridBeforeEditCell",[d.rows[t].id,a,o,t,i]),e.isFunction(d.p.beforeEditCell)&&d.p.beforeEditCell.call(d,d.rows[t].id,a,o,t,i),e(s).html("").append(u).attr("tabindex","0"),window.setTimeout(function(){e(u).focus()},0),e("input, select, textarea",s).bind("keydown",function(r){if(27===r.keyCode&&(e("input.hasDatepicker",s).length>0?e(".ui-datepicker").is(":hidden")?e(d).jqGrid("restoreCell",t,i):e("input.hasDatepicker",s).datepicker("hide"):e(d).jqGrid("restoreCell",t,i)),13===r.keyCode)return e(d).jqGrid("saveCell",t,i),!1;if(9===r.keyCode){if(d.grid.hDiv.loading)return!1;r.shiftKey?e(d).jqGrid("prevCell",t,i):e(d).jqGrid("nextCell",t,i)}r.stopPropagation()}),e(d).triggerHandler("jqGridAfterEditCell",[d.rows[t].id,a,o,t,i]),e.isFunction(d.p.afterEditCell)&&d.p.afterEditCell.call(d,d.rows[t].id,a,o,t,i)}d.p.iCol=i,d.p.iRow=t}}})},saveCell:function(t,i){return this.each(function(){var r,a=this;if(a.grid&&a.p.cellEdit===!0){if(r=a.p.savedRow.length>=1?0:null,null!=r){var o,s,n=e("td:eq("+i+")",a.rows[t]),d=a.p.colModel[i],l=d.name,p=e.jgrid.jqID(l);switch(d.edittype){case"select":if(d.editoptions.multiple){var c=e("#"+t+"_"+p,a.rows[t]),u=[];o=e(c).val(),o?o.join(","):o="",e("option:selected",c).each(function(t,i){u[t]=e(i).text()}),s=u.join(",")}else o=e("#"+t+"_"+p+" option:selected",a.rows[t]).val(),s=e("#"+t+"_"+p+" option:selected",a.rows[t]).text();d.formatter&&(s=o);break;case"checkbox":var h=["Yes","No"];d.editoptions&&(h=d.editoptions.value.split(":")),o=e("#"+t+"_"+p,a.rows[t]).is(":checked")?h[0]:h[1],s=o;break;case"password":case"text":case"textarea":case"button":o=e("#"+t+"_"+p,a.rows[t]).val(),s=o;break;case"custom":try{if(!d.editoptions||!e.isFunction(d.editoptions.custom_value))throw"e1";if(o=d.editoptions.custom_value.call(a,e(".customelement",n),"get"),void 0===o)throw"e2";s=o}catch(f){"e1"==f&&e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose),"e2"==f?e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+e.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose):e.jgrid.info_dialog(jQuery.jgrid.errors.errcap,f.message,jQuery.jgrid.edit.bClose)}}if(s!==a.p.savedRow[r].v){var g=e(a).triggerHandler("jqGridBeforeSaveCell",[a.rows[t].id,l,o,t,i]);if(g&&(o=g,s=g),e.isFunction(a.p.beforeSaveCell)){var m=a.p.beforeSaveCell.call(a,a.rows[t].id,l,o,t,i);m&&(o=m,s=m)}var v=e.jgrid.checkValues(o,i,a);if(v[0]===!0){var j=e(a).triggerHandler("jqGridBeforeSubmitCell",[a.rows[t].id,l,o,t,i])||{};if(e.isFunction(a.p.beforeSubmitCell)&&(j=a.p.beforeSubmitCell.call(a,a.rows[t].id,l,o,t,i),j||(j={})),e("input.hasDatepicker",n).length>0&&e("input.hasDatepicker",n).datepicker("hide"),"remote"==a.p.cellsubmit)if(a.p.cellurl){var b={};a.p.autoencode&&(o=e.jgrid.htmlEncode(o)),b[l]=o;var w,y,q;q=a.p.prmNames,w=q.id,y=q.oper,b[w]=e.jgrid.stripPref(a.p.idPrefix,a.rows[t].id),b[y]=q.editoper,b=e.extend(j,b),e("#lui_"+e.jgrid.jqID(a.p.id)).show(),a.grid.hDiv.loading=!0,e.ajax(e.extend({url:a.p.cellurl,data:e.isFunction(a.p.serializeCellData)?a.p.serializeCellData.call(a,b):b,type:"POST",complete:function(r,d){if(e("#lui_"+a.p.id).hide(),a.grid.hDiv.loading=!1,"success"==d){var p=e(a).triggerHandler("jqGridAfterSubmitCell",[a,r,b.id,l,o,t,i])||[!0,""];p[0]===!0&&e.isFunction(a.p.afterSubmitCell)&&(p=a.p.afterSubmitCell.call(a,r,b.id,l,o,t,i)),p[0]===!0?(e(n).empty(),e(a).jqGrid("setCell",a.rows[t].id,i,s,!1,!1,!0),e(n).addClass("dirty-cell"),e(a.rows[t]).addClass("edited"),e(a).triggerHandler("jqGridAfterSaveCell",[a.rows[t].id,l,o,t,i]),e.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,a.rows[t].id,l,o,t,i),a.p.savedRow.splice(0,1)):(e.jgrid.info_dialog(e.jgrid.errors.errcap,p[1],e.jgrid.edit.bClose),e(a).jqGrid("restoreCell",t,i))}},error:function(r,o,s){e("#lui_"+e.jgrid.jqID(a.p.id)).hide(),a.grid.hDiv.loading=!1,e(a).triggerHandler("jqGridErrorCell",[r,o,s]),e.isFunction(a.p.errorCell)?(a.p.errorCell.call(a,r,o,s),e(a).jqGrid("restoreCell",t,i)):(e.jgrid.info_dialog(e.jgrid.errors.errcap,r.status+" : "+r.statusText+"<br/>"+o,e.jgrid.edit.bClose),e(a).jqGrid("restoreCell",t,i))}},e.jgrid.ajaxOptions,a.p.ajaxCellOptions||{}))}else try{e.jgrid.info_dialog(e.jgrid.errors.errcap,e.jgrid.errors.nourl,e.jgrid.edit.bClose),e(a).jqGrid("restoreCell",t,i)}catch(f){}"clientArray"==a.p.cellsubmit&&(e(n).empty(),e(a).jqGrid("setCell",a.rows[t].id,i,s,!1,!1,!0),e(n).addClass("dirty-cell"),e(a.rows[t]).addClass("edited"),e(a).triggerHandler("jqGridAfterSaveCell",[a.rows[t].id,l,o,t,i]),e.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,a.rows[t].id,l,o,t,i),a.p.savedRow.splice(0,1))}else try{window.setTimeout(function(){e.jgrid.info_dialog(e.jgrid.errors.errcap,o+" "+v[1],e.jgrid.edit.bClose)},100),e(a).jqGrid("restoreCell",t,i)}catch(f){}}else e(a).jqGrid("restoreCell",t,i)}e.browser.opera?e("#"+e.jgrid.jqID(a.p.knv)).attr("tabindex","-1").focus():window.setTimeout(function(){e("#"+e.jgrid.jqID(a.p.knv)).attr("tabindex","-1").focus()},0)}})},restoreCell:function(t,i){return this.each(function(){var r,a=this;if(a.grid&&a.p.cellEdit===!0){if(r=a.p.savedRow.length>=1?0:null,null!=r){var o=e("td:eq("+i+")",a.rows[t]);if(e.isFunction(e.fn.datepicker))try{e("input.hasDatepicker",o).datepicker("hide")}catch(s){}e(o).empty().attr("tabindex","-1"),e(a).jqGrid("setCell",a.rows[t].id,i,a.p.savedRow[r].v,!1,!1,!0),e(a).triggerHandler("jqGridAfterRestoreCell",[a.rows[t].id,a.p.savedRow[r].v,t,i]),e.isFunction(a.p.afterRestoreCell)&&a.p.afterRestoreCell.call(a,a.rows[t].id,a.p.savedRow[r].v,t,i),a.p.savedRow.splice(0,1)}window.setTimeout(function(){e("#"+a.p.knv).attr("tabindex","-1").focus()},0)}})},nextCell:function(t,i){return this.each(function(){var r=this,a=!1;if(r.grid&&r.p.cellEdit===!0){for(var o=i+1;o<r.p.colModel.length;o++)if(r.p.colModel[o].editable===!0){a=o;break}a!==!1?e(r).jqGrid("editCell",t,a,!0):r.p.savedRow.length>0&&e(r).jqGrid("saveCell",t,i)}})},prevCell:function(t,i){return this.each(function(){var r=this,a=!1;if(r.grid&&r.p.cellEdit===!0){for(var o=i-1;o>=0;o--)if(r.p.colModel[o].editable===!0){a=o;break}a!==!1?e(r).jqGrid("editCell",t,a,!0):r.p.savedRow.length>0&&e(r).jqGrid("saveCell",t,i)}})},GridNav:function(){return this.each(function(){function t(t,i,a){if("v"==a.substr(0,1)){var o=e(r.grid.bDiv)[0].clientHeight,s=e(r.grid.bDiv)[0].scrollTop,n=r.rows[t].offsetTop+r.rows[t].clientHeight,d=r.rows[t].offsetTop;"vd"==a&&n>=o&&(e(r.grid.bDiv)[0].scrollTop=e(r.grid.bDiv)[0].scrollTop+r.rows[t].clientHeight),"vu"==a&&s>d&&(e(r.grid.bDiv)[0].scrollTop=e(r.grid.bDiv)[0].scrollTop-r.rows[t].clientHeight)}if("h"==a){var l=e(r.grid.bDiv)[0].clientWidth,p=e(r.grid.bDiv)[0].scrollLeft,c=r.rows[t].cells[i].offsetLeft+r.rows[t].cells[i].clientWidth,u=r.rows[t].cells[i].offsetLeft;c>=l+parseInt(p,10)?e(r.grid.bDiv)[0].scrollLeft=e(r.grid.bDiv)[0].scrollLeft+r.rows[t].cells[i].clientWidth:p>u&&(e(r.grid.bDiv)[0].scrollLeft=e(r.grid.bDiv)[0].scrollLeft-r.rows[t].cells[i].clientWidth)}}function i(e,t){var i,a;if("lft"==t)for(i=e+1,a=e;a>=0;a--)if(r.p.colModel[a].hidden!==!0){i=a;break}if("rgt"==t)for(i=e-1,a=e;a<r.p.colModel.length;a++)if(r.p.colModel[a].hidden!==!0){i=a;break}return i}var r=this;if(r.grid&&r.p.cellEdit===!0){r.p.knv=r.p.id+"_kn";var a,o,s=e("<span style='width:0px;height:0px;background-color:black;' tabindex='0'><span tabindex='-1' style='width:0px;height:0px;background-color:grey' id='"+r.p.knv+"'></span></span>");e(s).insertBefore(r.grid.cDiv),e("#"+r.p.knv).focus().keydown(function(s){switch(o=s.keyCode,"rtl"==r.p.direction&&(37===o?o=39:39===o&&(o=37)),o){case 38:r.p.iRow-1>0&&(t(r.p.iRow-1,r.p.iCol,"vu"),e(r).jqGrid("editCell",r.p.iRow-1,r.p.iCol,!1));break;case 40:r.p.iRow+1<=r.rows.length-1&&(t(r.p.iRow+1,r.p.iCol,"vd"),e(r).jqGrid("editCell",r.p.iRow+1,r.p.iCol,!1));break;case 37:r.p.iCol-1>=0&&(a=i(r.p.iCol-1,"lft"),t(r.p.iRow,a,"h"),e(r).jqGrid("editCell",r.p.iRow,a,!1));break;case 39:r.p.iCol+1<=r.p.colModel.length-1&&(a=i(r.p.iCol+1,"rgt"),t(r.p.iRow,a,"h"),e(r).jqGrid("editCell",r.p.iRow,a,!1));break;case 13:parseInt(r.p.iCol,10)>=0&&parseInt(r.p.iRow,10)>=0&&e(r).jqGrid("editCell",r.p.iRow,r.p.iCol,!0);break;default:return!0}return!1})}})},getChangedCells:function(t){var i=[];return t||(t="all"),this.each(function(){var r,a=this;a.grid&&a.p.cellEdit===!0&&e(a.rows).each(function(o){var s={};e(this).hasClass("edited")&&(e("td",this).each(function(i){if(r=a.p.colModel[i].name,"cb"!==r&&"subgrid"!==r)if("dirty"==t){if(e(this).hasClass("dirty-cell"))try{s[r]=e.unformat.call(a,this,{rowId:a.rows[o].id,colModel:a.p.colModel[i]},i)}catch(n){s[r]=e.jgrid.htmlDecode(e(this).html())}}else try{s[r]=e.unformat.call(a,this,{rowId:a.rows[o].id,colModel:a.p.colModel[i]},i)}catch(n){s[r]=e.jgrid.htmlDecode(e(this).html())}}),s.id=this.id,i.push(s))})}),i}})}(jQuery),function(e){"use strict";e.jgrid.extend({setSubGrid:function(){return this.each(function(){var t,i=this,r={plusicon:"ui-icon-plus",minusicon:"ui-icon-minus",openicon:"ui-icon-carat-1-sw",expandOnLoad:!1,delayOnLoad:50,selectOnExpand:!1,reloadOnExpand:!0};if(i.p.subGridOptions=e.extend(r,i.p.subGridOptions||{}),i.p.colNames.unshift(""),i.p.colModel.unshift({name:"subgrid",width:e.browser.safari?i.p.subGridWidth+i.p.cellLayout:i.p.subGridWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,fixed:!0}),t=i.p.subGridModel,t[0]){t[0].align=e.extend([],t[0].align||[]);for(var a=0;a<t[0].name.length;a++)t[0].align[a]=t[0].align[a]||"left"}})},addSubGridCell:function(e,t){var i,r,a="";return this.each(function(){a=this.formatCol(e,t),r=this.p.id,i=this.p.subGridOptions.plusicon}),'<td role="gridcell" aria-describedby="'+r+'_subgrid" class="ui-sgcollapsed sgcollapsed" '+a+"><a href='javascript:void(0);'><span class='ui-icon "+i+"'></span></a></td>"},addSubGrid:function(t,i){return this.each(function(){var r=this;if(r.grid){var a,o,s,n,d,l=function(t,i,a){var o=e("<td align='"+r.p.subGridModel[0].align[a]+"'></td>").html(i);e(t).append(o)},p=function(t,i){var a,o,s,n=e("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),d=e("<tr></tr>");for(o=0;o<r.p.subGridModel[0].name.length;o++)a=e("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-"+r.p.direction+"'></th>"),e(a).html(r.p.subGridModel[0].name[o]),e(a).width(r.p.subGridModel[0].width[o]),e(d).append(a);e(n).append(d),t&&(s=r.p.xmlReader.subgrid,e(s.root+" "+s.row,t).each(function(){if(d=e("<tr class='ui-widget-content ui-subtblcell'></tr>"),s.repeatitems===!0)e(s.cell,this).each(function(t){l(d,e(this).text()||"&#160;",t)});else{var t=r.p.subGridModel[0].mapping||r.p.subGridModel[0].name;if(t)for(o=0;o<t.length;o++)l(d,e(t[o],this).text()||"&#160;",o)}e(n).append(d)}));var p=e("table:first",r.grid.bDiv).attr("id")+"_";return e("#"+e.jgrid.jqID(p+i)).append(n),r.grid.hDiv.loading=!1,e("#load_"+e.jgrid.jqID(r.p.id)).hide(),!1},c=function(t,i){var a,o,s,n,d,p,c=e("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),u=e("<tr></tr>");for(s=0;s<r.p.subGridModel[0].name.length;s++)a=e("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-"+r.p.direction+"'></th>"),e(a).html(r.p.subGridModel[0].name[s]),e(a).width(r.p.subGridModel[0].width[s]),e(u).append(a);if(e(c).append(u),t&&(d=r.p.jsonReader.subgrid,o=t[d.root],"undefined"!=typeof o))for(s=0;s<o.length;s++){if(n=o[s],u=e("<tr class='ui-widget-content ui-subtblcell'></tr>"),d.repeatitems===!0)for(d.cell&&(n=n[d.cell]),p=0;p<n.length;p++)l(u,n[p]||"&#160;",p);else{var h=r.p.subGridModel[0].mapping||r.p.subGridModel[0].name;if(h.length)for(p=0;p<h.length;p++)l(u,n[h[p]]||"&#160;",p)}e(c).append(u)}var f=e("table:first",r.grid.bDiv).attr("id")+"_";return e("#"+e.jgrid.jqID(f+i)).append(c),r.grid.hDiv.loading=!1,e("#load_"+e.jgrid.jqID(r.p.id)).hide(),!1},u=function(t){var i,a,o,s;if(i=e(t).attr("id"),a={nd_:(new Date).getTime()},a[r.p.prmNames.subgridid]=i,!r.p.subGridModel[0])return!1;if(r.p.subGridModel[0].params)for(s=0;s<r.p.subGridModel[0].params.length;s++)for(o=0;o<r.p.colModel.length;o++)r.p.colModel[o].name===r.p.subGridModel[0].params[s]&&(a[r.p.colModel[o].name]=e("td:eq("+o+")",t).text().replace(/\&#160\;/gi,""));if(!r.grid.hDiv.loading)switch(r.grid.hDiv.loading=!0,e("#load_"+e.jgrid.jqID(r.p.id)).show(),r.p.subgridtype||(r.p.subgridtype=r.p.datatype),e.isFunction(r.p.subgridtype)?r.p.subgridtype.call(r,a):r.p.subgridtype=r.p.subgridtype.toLowerCase(),r.p.subgridtype){case"xml":case"json":e.ajax(e.extend({type:r.p.mtype,url:r.p.subGridUrl,dataType:r.p.subgridtype,data:e.isFunction(r.p.serializeSubGridData)?r.p.serializeSubGridData.call(r,a):a,complete:function(t){"xml"===r.p.subgridtype?p(t.responseXML,i):c(e.jgrid.parse(t.responseText),i),t=null}},e.jgrid.ajaxOptions,r.p.ajaxSubgridOptions||{}))}return!1},h=0;e.each(r.p.colModel,function(){(this.hidden===!0||"rn"===this.name||"cb"===this.name)&&h++});var f=r.rows.length,g=1;for(void 0!==i&&i>0&&(g=i,f=i+1);f>g;)e(r.rows[g]).hasClass("jqgrow")&&e(r.rows[g].cells[t]).bind("click",function(){var i=e(this).parent("tr")[0];if(d=i.nextSibling,e(this).hasClass("sgcollapsed")){if(o=r.p.id,a=i.id,r.p.subGridOptions.reloadOnExpand===!0||r.p.subGridOptions.reloadOnExpand===!1&&!e(d).hasClass("ui-subgrid")){if(s=t>=1?"<td colspan='"+t+"'>&#160;</td>":"",n=e(r).triggerHandler("jqGridSubGridBeforeExpand",[o+"_"+a,a]),n=n===!1||"stop"===n?!1:!0,n&&e.isFunction(r.p.subGridBeforeExpand)&&(n=r.p.subGridBeforeExpand.call(r,o+"_"+a,a)),n===!1)return!1;e(i).after("<tr role='row' class='ui-subgrid'>"+s+"<td class='ui-widget-content subgrid-cell'><span class='ui-icon "+r.p.subGridOptions.openicon+"'></span></td><td colspan='"+parseInt(r.p.colNames.length-1-h,10)+"' class='ui-widget-content subgrid-data'><div id="+o+"_"+a+" class='tablediv'></div></td></tr>"),e(r).triggerHandler("jqGridSubGridRowExpanded",[o+"_"+a,a]),e.isFunction(r.p.subGridRowExpanded)?r.p.subGridRowExpanded.call(r,o+"_"+a,a):u(i)}else e(d).show();e(this).html("<a href='javascript:void(0);'><span class='ui-icon "+r.p.subGridOptions.minusicon+"'></span></a>").removeClass("sgcollapsed").addClass("sgexpanded"),r.p.subGridOptions.selectOnExpand&&e(r).jqGrid("setSelection",a)}else if(e(this).hasClass("sgexpanded")){if(n=e(r).triggerHandler("jqGridSubGridRowColapsed",[o+"_"+a,a]),n=n===!1||"stop"===n?!1:!0,n&&e.isFunction(r.p.subGridRowColapsed)&&(a=i.id,n=r.p.subGridRowColapsed.call(r,o+"_"+a,a)),n===!1)return!1;r.p.subGridOptions.reloadOnExpand===!0?e(d).remove(".ui-subgrid"):e(d).hasClass("ui-subgrid")&&e(d).hide(),e(this).html("<a href='javascript:void(0);'><span class='ui-icon "+r.p.subGridOptions.plusicon+"'></span></a>").removeClass("sgexpanded").addClass("sgcollapsed")}return!1}),g++;r.p.subGridOptions.expandOnLoad===!0&&e(r.rows).filter(".jqgrow").each(function(t,i){e(i.cells[0]).click()}),r.subGridXml=function(e,t){p(e,t)},r.subGridJson=function(e,t){c(e,t)}}})},expandSubGridRow:function(t){return this.each(function(){var i=this;if((i.grid||t)&&i.p.subGrid===!0){var r=e(this).jqGrid("getInd",t,!0);if(r){var a=e("td.sgcollapsed",r)[0];a&&e(a).trigger("click")}}})},collapseSubGridRow:function(t){return this.each(function(){var i=this;if((i.grid||t)&&i.p.subGrid===!0){var r=e(this).jqGrid("getInd",t,!0);if(r){var a=e("td.sgexpanded",r)[0];a&&e(a).trigger("click")}}})},toggleSubGridRow:function(t){return this.each(function(){var i=this;if((i.grid||t)&&i.p.subGrid===!0){var r=e(this).jqGrid("getInd",t,!0);if(r){var a=e("td.sgcollapsed",r)[0];a?e(a).trigger("click"):(a=e("td.sgexpanded",r)[0],a&&e(a).trigger("click"))}}})}})}(jQuery),function(e){"use strict";e.jgrid.extend({setTreeNode:function(t,i){return this.each(function(){var r=this;if(r.grid&&r.p.treeGrid)for(var a,o,s,n,d,l,p,c,u=r.p.expColInd,h=r.p.treeReader.expanded_field,f=r.p.treeReader.leaf_field,g=r.p.treeReader.level_field,m=r.p.treeReader.icon_field,v=r.p.treeReader.loaded;i>t;){var j,b=r.rows[t].id,w=r.p._index[b];if(p=r.p.data[w],"nested"==r.p.treeGridModel&&(p[f]||(a=parseInt(p[r.p.treeReader.left_field],10),o=parseInt(p[r.p.treeReader.right_field],10),p[f]=o===a+1?"true":"false",r.rows[t].cells[r.p._treeleafpos].innerHTML=p[f])),s=parseInt(p[g],10),0===r.p.tree_root_level?(n=s+1,d=s):(n=s,d=s-1),l="<div class='tree-wrap tree-wrap-"+r.p.direction+"' style='width:"+18*n+"px;'>",l+="<div style='"+("rtl"==r.p.direction?"right:":"left:")+18*d+"px;' class='ui-icon ",void 0!==p[v]&&("true"==p[v]||p[v]===!0?p[v]=!0:p[v]=!1),"true"==p[f]||p[f]===!0?(l+=(void 0!==p[m]&&""!==p[m]?p[m]:r.p.treeIcons.leaf)+" tree-leaf treeclick",p[f]=!0,c="leaf"):(p[f]=!1,c=""),p[h]=("true"==p[h]||p[h]===!0?!0:!1)&&p[v],l+=p[h]===!1?p[f]===!0?"'":r.p.treeIcons.plus+" tree-plus treeclick'":p[f]===!0?"'":r.p.treeIcons.minus+" tree-minus treeclick'",l+="></div></div>",e(r.rows[t].cells[u]).wrapInner("<span class='cell-wrapper"+c+"'></span>").prepend(l),s!==parseInt(r.p.tree_root_level,10)){var y=e(r).jqGrid("getNodeParent",p);j=y&&y.hasOwnProperty(h)?y[h]:!0,j||e(r.rows[t]).css("display","none")}e(r.rows[t].cells[u]).find("div.treeclick").bind("click",function(t){var i=t.target||t.srcElement,a=e(i,r.rows).closest("tr.jqgrow")[0].id,o=r.p._index[a];return r.p.data[o][f]||(r.p.data[o][h]?(e(r).jqGrid("collapseRow",r.p.data[o]),e(r).jqGrid("collapseNode",r.p.data[o])):(e(r).jqGrid("expandRow",r.p.data[o]),e(r).jqGrid("expandNode",r.p.data[o]))),!1}),r.p.ExpandColClick===!0&&e(r.rows[t].cells[u]).find("span.cell-wrapper").css("cursor","pointer").bind("click",function(t){var i=t.target||t.srcElement,a=e(i,r.rows).closest("tr.jqgrow")[0].id,o=r.p._index[a];return r.p.data[o][f]||(r.p.data[o][h]?(e(r).jqGrid("collapseRow",r.p.data[o]),e(r).jqGrid("collapseNode",r.p.data[o])):(e(r).jqGrid("expandRow",r.p.data[o]),e(r).jqGrid("expandNode",r.p.data[o]))),e(r).jqGrid("setSelection",a),!1}),t++}})},setTreeGrid:function(){return this.each(function(){var t,i,r,a=this,o=0,s=!1,n=[];if(a.p.treeGrid){a.p.treedatatype||e.extend(a.p,{treedatatype:a.p.datatype}),a.p.subGrid=!1,a.p.altRows=!1,a.p.pgbuttons=!1,a.p.pginput=!1,a.p.gridview=!0,null===a.p.rowTotal&&(a.p.rowNum=1e4),a.p.multiselect=!1,a.p.rowList=[],a.p.expColInd=0,t="ui-icon-triangle-1-"+("rtl"==a.p.direction?"w":"e"),a.p.treeIcons=e.extend({plus:t,minus:"ui-icon-triangle-1-s",leaf:"ui-icon-radio-off"},a.p.treeIcons||{}),"nested"==a.p.treeGridModel?a.p.treeReader=e.extend({level_field:"level",left_field:"lft",right_field:"rgt",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},a.p.treeReader):"adjacency"==a.p.treeGridModel&&(a.p.treeReader=e.extend({level_field:"level",parent_id_field:"parent",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},a.p.treeReader));for(r in a.p.colModel)if(a.p.colModel.hasOwnProperty(r)){i=a.p.colModel[r].name,i!=a.p.ExpandColumn||s||(s=!0,a.p.expColInd=o),o++;for(var d in a.p.treeReader)a.p.treeReader[d]==i&&n.push(i)}e.each(a.p.treeReader,function(t,i){i&&-1===e.inArray(i,n)&&("leaf_field"===t&&(a.p._treeleafpos=o),o++,a.p.colNames.push(i),a.p.colModel.push({name:i,width:1,hidden:!0,sortable:!1,resizable:!1,hidedlg:!0,editable:!0,search:!1}))})}})},expandRow:function(t){this.each(function(){var i=this;if(i.grid&&i.p.treeGrid){var r=e(i).jqGrid("getNodeChildren",t),a=i.p.treeReader.expanded_field,o=i.rows;e(r).each(function(){var t=e.jgrid.getAccessor(this,i.p.localReader.id);e(o.namedItem(t)).css("display",""),this[a]&&e(i).jqGrid("expandRow",this)})}})},collapseRow:function(t){this.each(function(){var i=this;if(i.grid&&i.p.treeGrid){var r=e(i).jqGrid("getNodeChildren",t),a=i.p.treeReader.expanded_field,o=i.rows;e(r).each(function(){var t=e.jgrid.getAccessor(this,i.p.localReader.id);e(o.namedItem(t)).css("display","none"),this[a]&&e(i).jqGrid("collapseRow",this)})}})},getRootNodes:function(){var t=[];return this.each(function(){var i=this;if(i.grid&&i.p.treeGrid)switch(i.p.treeGridModel){case"nested":var r=i.p.treeReader.level_field;e(i.p.data).each(function(){parseInt(this[r],10)===parseInt(i.p.tree_root_level,10)&&t.push(this)});break;case"adjacency":var a=i.p.treeReader.parent_id_field;e(i.p.data).each(function(){(null===this[a]||"null"==String(this[a]).toLowerCase())&&t.push(this);
})}}),t},getNodeDepth:function(t){var i=null;return this.each(function(){if(this.grid&&this.p.treeGrid){var r=this;switch(r.p.treeGridModel){case"nested":var a=r.p.treeReader.level_field;i=parseInt(t[a],10)-parseInt(r.p.tree_root_level,10);break;case"adjacency":i=e(r).jqGrid("getNodeAncestors",t).length}}}),i},getNodeParent:function(t){var i=null;return this.each(function(){var r=this;if(r.grid&&r.p.treeGrid)switch(r.p.treeGridModel){case"nested":var a=r.p.treeReader.left_field,o=r.p.treeReader.right_field,s=r.p.treeReader.level_field,n=parseInt(t[a],10),d=parseInt(t[o],10),l=parseInt(t[s],10);e(this.p.data).each(function(){return parseInt(this[s],10)===l-1&&parseInt(this[a],10)<n&&parseInt(this[o],10)>d?(i=this,!1):void 0});break;case"adjacency":var p=r.p.treeReader.parent_id_field,c=r.p.localReader.id;e(this.p.data).each(function(){return this[c]==t[p]?(i=this,!1):void 0})}}),i},getNodeChildren:function(t){var i=[];return this.each(function(){var r=this;if(r.grid&&r.p.treeGrid)switch(r.p.treeGridModel){case"nested":var a=r.p.treeReader.left_field,o=r.p.treeReader.right_field,s=r.p.treeReader.level_field,n=parseInt(t[a],10),d=parseInt(t[o],10),l=parseInt(t[s],10);e(this.p.data).each(function(){parseInt(this[s],10)===l+1&&parseInt(this[a],10)>n&&parseInt(this[o],10)<d&&i.push(this)});break;case"adjacency":var p=r.p.treeReader.parent_id_field,c=r.p.localReader.id;e(this.p.data).each(function(){this[p]==t[c]&&i.push(this)})}}),i},getFullTreeNode:function(t){var i=[];return this.each(function(){var r,a=this;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case"nested":var o=a.p.treeReader.left_field,s=a.p.treeReader.right_field,n=a.p.treeReader.level_field,d=parseInt(t[o],10),l=parseInt(t[s],10),p=parseInt(t[n],10);e(this.p.data).each(function(){parseInt(this[n],10)>=p&&parseInt(this[o],10)>=d&&parseInt(this[o],10)<=l&&i.push(this)});break;case"adjacency":if(t){i.push(t);var c=a.p.treeReader.parent_id_field,u=a.p.localReader.id;e(this.p.data).each(function(e){for(r=i.length,e=0;r>e;e++)if(i[e][u]==this[c]){i.push(this);break}})}}}),i},getNodeAncestors:function(t){var i=[];return this.each(function(){if(this.grid&&this.p.treeGrid)for(var r=e(this).jqGrid("getNodeParent",t);r;)i.push(r),r=e(this).jqGrid("getNodeParent",r)}),i},isVisibleNode:function(t){var i=!0;return this.each(function(){var r=this;if(r.grid&&r.p.treeGrid){var a=e(r).jqGrid("getNodeAncestors",t),o=r.p.treeReader.expanded_field;e(a).each(function(){return i=i&&this[o],i?void 0:!1})}}),i},isNodeLoaded:function(t){var i;return this.each(function(){var r=this;if(r.grid&&r.p.treeGrid){var a=r.p.treeReader.leaf_field;i=void 0!==t?void 0!==t.loaded?t.loaded:t[a]||e(r).jqGrid("getNodeChildren",t).length>0?!0:!1:!1}}),i},expandNode:function(t){return this.each(function(){if(this.grid&&this.p.treeGrid){var i=this.p.treeReader.expanded_field,r=this.p.treeReader.parent_id_field,a=this.p.treeReader.loaded,o=this.p.treeReader.level_field,s=this.p.treeReader.left_field,n=this.p.treeReader.right_field;if(!t[i]){var d=e.jgrid.getAccessor(t,this.p.localReader.id),l=e("#"+e.jgrid.jqID(d),this.grid.bDiv)[0],p=this.p._index[d];e(this).jqGrid("isNodeLoaded",this.p.data[p])?(t[i]=!0,e("div.treeclick",l).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus")):this.grid.hDiv.loading||(t[i]=!0,e("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?e(this).jqGrid("setGridParam",{postData:{nodeid:d,n_left:t[s],n_right:t[n],n_level:t[o]}}):e(this).jqGrid("setGridParam",{postData:{nodeid:d,parentid:t[r],n_level:t[o]}}),e(this).trigger("reloadGrid"),t[a]=!0,"nested"==this.p.treeGridModel?e(this).jqGrid("setGridParam",{postData:{nodeid:"",n_left:"",n_right:"",n_level:""}}):e(this).jqGrid("setGridParam",{postData:{nodeid:"",parentid:"",n_level:""}}))}}})},collapseNode:function(t){return this.each(function(){if(this.grid&&this.p.treeGrid){var i=this.p.treeReader.expanded_field;if(t[i]){t[i]=!1;var r=e.jgrid.getAccessor(t,this.p.localReader.id),a=e("#"+e.jgrid.jqID(r),this.grid.bDiv)[0];e("div.treeclick",a).removeClass(this.p.treeIcons.minus+" tree-minus").addClass(this.p.treeIcons.plus+" tree-plus")}}})},SortTree:function(t,i,r,a){return this.each(function(){if(this.grid&&this.p.treeGrid){var o,s,n,d,l,p=[],c=this,u=e(this).jqGrid("getRootNodes");for(d=e.jgrid.from(u),d.orderBy(t,i,r,a),l=d.select(),o=0,s=l.length;s>o;o++)n=l[o],p.push(n),e(this).jqGrid("collectChildrenSortTree",p,n,t,i,r,a);e.each(p,function(t){var i=e.jgrid.getAccessor(this,c.p.localReader.id);e("#"+e.jgrid.jqID(c.p.id)+" tbody tr:eq("+t+")").after(e("tr#"+e.jgrid.jqID(i),c.grid.bDiv))}),d=null,l=null,p=null}})},collectChildrenSortTree:function(t,i,r,a,o,s){return this.each(function(){if(this.grid&&this.p.treeGrid){var n,d,l,p,c,u;for(p=e(this).jqGrid("getNodeChildren",i),c=e.jgrid.from(p),c.orderBy(r,a,o,s),u=c.select(),n=0,d=u.length;d>n;n++)l=u[n],t.push(l),e(this).jqGrid("collectChildrenSortTree",t,l,r,a,o,s)}})},setTreeRow:function(t,i){var r=!1;return this.each(function(){var a=this;a.grid&&a.p.treeGrid&&(r=e(a).jqGrid("setRowData",t,i))}),r},delTreeNode:function(t){return this.each(function(){var i,r,a,o,s=this,n=s.p.localReader.id,d=s.p.treeReader.left_field,l=s.p.treeReader.right_field;if(s.grid&&s.p.treeGrid){var p=s.p._index[t];if(void 0!==p){i=parseInt(s.p.data[p][l],10),r=i-parseInt(s.p.data[p][d],10)+1;var c=e(s).jqGrid("getFullTreeNode",s.p.data[p]);if(c.length>0)for(var u=0;u<c.length;u++)e(s).jqGrid("delRowData",c[u][n]);if("nested"===s.p.treeGridModel){if(a=e.jgrid.from(s.p.data).greater(d,i,{stype:"integer"}).select(),a.length)for(o in a)a.hasOwnProperty(o)&&(a[o][d]=parseInt(a[o][d],10)-r);if(a=e.jgrid.from(s.p.data).greater(l,i,{stype:"integer"}).select(),a.length)for(o in a)a.hasOwnProperty(o)&&(a[o][l]=parseInt(a[o][l],10)-r)}}}})},addChildNode:function(t,i,r){var a=this[0];if(r){var o,s,n,d,l,p,c,u,h=a.p.treeReader.expanded_field,f=a.p.treeReader.leaf_field,g=a.p.treeReader.level_field,m=a.p.treeReader.parent_id_field,v=a.p.treeReader.left_field,j=a.p.treeReader.right_field,b=a.p.treeReader.loaded,w=0,y=i;if("undefined"==typeof t||null===t){if(l=a.p.data.length-1,l>=0)for(;l>=0;)w=Math.max(w,parseInt(a.p.data[l][a.p.localReader.id],10)),l--;t=w+1}var q=e(a).jqGrid("getInd",i);if(c=!1,void 0===i||null===i||""===i)i=null,y=null,o="last",d=a.p.tree_root_level,l=a.p.data.length+1;else{o="after",s=a.p._index[i],n=a.p.data[s],i=n[a.p.localReader.id],d=parseInt(n[g],10)+1;var x=e(a).jqGrid("getFullTreeNode",n);x.length?(l=x[x.length-1][a.p.localReader.id],y=l,l=e(a).jqGrid("getInd",y)+1):l=e(a).jqGrid("getInd",i)+1,n[f]&&(c=!0,n[h]=!0,e(a.rows[q]).find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper").end().find("div.tree-leaf").removeClass(a.p.treeIcons.leaf+" tree-leaf").addClass(a.p.treeIcons.minus+" tree-minus"),a.p.data[s][f]=!1,n[b]=!0)}if(p=l+1,r[h]=!1,r[b]=!0,r[g]=d,r[f]=!0,"adjacency"===a.p.treeGridModel&&(r[m]=i),"nested"===a.p.treeGridModel){var D,$,_;if(null!=i){if(u=parseInt(n[j],10),D=e.jgrid.from(a.p.data),D=D.greaterOrEquals(j,u,{stype:"integer"}),$=D.select(),$.length)for(_ in $)$.hasOwnProperty(_)&&($[_][v]=$[_][v]>u?parseInt($[_][v],10)+2:$[_][v],$[_][j]=$[_][j]>=u?parseInt($[_][j],10)+2:$[_][j]);r[v]=u,r[j]=u+1}else{if(u=parseInt(e(a).jqGrid("getCol",j,!1,"max"),10),$=e.jgrid.from(a.p.data).greater(v,u,{stype:"integer"}).select(),$.length)for(_ in $)$.hasOwnProperty(_)&&($[_][v]=parseInt($[_][v],10)+2);if($=e.jgrid.from(a.p.data).greater(j,u,{stype:"integer"}).select(),$.length)for(_ in $)$.hasOwnProperty(_)&&($[_][j]=parseInt($[_][j],10)+2);r[v]=u+1,r[j]=u+2}}(null===i||e(a).jqGrid("isNodeLoaded",n)||c)&&(e(a).jqGrid("addRowData",t,r,o,y),e(a).jqGrid("setTreeNode",l,p)),n&&!n[h]&&e(a.rows[q]).find("div.treeclick").click()}}})}(jQuery),function(e){"use strict";e.extend(e.jgrid,{template:function(t){var i=e.makeArray(arguments).slice(1),r=1;return void 0===t&&(t=""),t.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,function(e,t){if(!isNaN(parseInt(t,10)))return r++,i[parseInt(t,10)];for(var a=i[r],o=a.length;o--;)if(t===a[o].nm)return a[o].v;r++})}}),e.jgrid.extend({groupingSetup:function(){return this.each(function(){var t=this,i=t.p.groupingView;if(null==i||"object"!=typeof i&&!e.isFunction(i))t.p.grouping=!1;else if(i.groupField.length){"undefined"==typeof i.visibiltyOnNextGrouping&&(i.visibiltyOnNextGrouping=[]),i.lastvalues=[],i.groups=[],i.counters=[];for(var r=0;r<i.groupField.length;r++)i.groupOrder[r]||(i.groupOrder[r]="asc"),i.groupText[r]||(i.groupText[r]="{0}"),"boolean"!=typeof i.groupColumnShow[r]&&(i.groupColumnShow[r]=!0),"boolean"!=typeof i.groupSummary[r]&&(i.groupSummary[r]=!1),i.groupColumnShow[r]===!0?(i.visibiltyOnNextGrouping[r]=!0,e(t).jqGrid("showCol",i.groupField[r])):(i.visibiltyOnNextGrouping[r]=e("#"+e.jgrid.jqID(t.p.id+"_"+i.groupField[r])).is(":visible"),e(t).jqGrid("hideCol",i.groupField[r]));i.summary=[];for(var a=t.p.colModel,o=0,s=a.length;s>o;o++)a[o].summaryType&&i.summary.push({nm:a[o].name,st:a[o].summaryType,v:"",sr:a[o].summaryRound,srt:a[o].summaryRoundType||"round"})}else t.p.grouping=!1})},groupingPrepare:function(t,i,r,a){return this.each(function(){for(var o,s,n=this.p.groupingView,d=this,l=n.groupField.length,p=0,c=0;l>c;c++)o=n.groupField[c],s=r[o],void 0!==s&&(0===a?(n.groups.push({idx:c,dataIndex:o,value:s,startRow:a,cnt:1,summary:[]}),n.lastvalues[c]=s,n.counters[c]={cnt:1,pos:n.groups.length-1,summary:e.extend(!0,[],n.summary)},e.each(n.counters[c].summary,function(){e.isFunction(this.st)?this.v=this.st.call(d,this.v,this.nm,r):this.v=e(d).jqGrid("groupingCalculations.handler",this.st,this.v,this.nm,this.sr,this.srt,r)}),n.groups[n.counters[c].pos].summary=n.counters[c].summary):"object"!=typeof s&&n.lastvalues[c]!==s?(n.groups.push({idx:c,dataIndex:o,value:s,startRow:a,cnt:1,summary:[]}),n.lastvalues[c]=s,p=1,n.counters[c]={cnt:1,pos:n.groups.length-1,summary:e.extend(!0,[],n.summary)},e.each(n.counters[c].summary,function(){e.isFunction(this.st)?this.v=this.st.call(d,this.v,this.nm,r):this.v=e(d).jqGrid("groupingCalculations.handler",this.st,this.v,this.nm,this.sr,this.srt,r)}),n.groups[n.counters[c].pos].summary=n.counters[c].summary):1===p?(n.groups.push({idx:c,dataIndex:o,value:s,startRow:a,cnt:1,summary:[]}),n.lastvalues[c]=s,n.counters[c]={cnt:1,pos:n.groups.length-1,summary:e.extend(!0,[],n.summary)},e.each(n.counters[c].summary,function(){e.isFunction(this.st)?this.v=this.st.call(d,this.v,this.nm,r):this.v=e(d).jqGrid("groupingCalculations.handler",this.st,this.v,this.nm,this.sr,this.srt,r)}),n.groups[n.counters[c].pos].summary=n.counters[c].summary):(n.counters[c].cnt+=1,n.groups[n.counters[c].pos].cnt=n.counters[c].cnt,e.each(n.counters[c].summary,function(){e.isFunction(this.st)?this.v=this.st.call(d,this.v,this.nm,r):this.v=e(d).jqGrid("groupingCalculations.handler",this.st,this.v,this.nm,this.sr,this.srt,r)}),n.groups[n.counters[c].pos].summary=n.counters[c].summary));i.push(t)}),i},groupingToggle:function(t){return this.each(function(){var i=this,r=i.p.groupingView,a=t.split("_"),o=parseInt(a[a.length-2],10);a.splice(a.length-2,2);var s=a.join("_"),n=r.minusicon,d=r.plusicon,l=e("#"+e.jgrid.jqID(t)),p=l.length?l[0].nextSibling:null,c=e("#"+e.jgrid.jqID(t)+" span.tree-wrap-"+i.p.direction),u=!1;if(c.hasClass(n)){if(r.showSummaryOnHide){if(p)for(;p&&!e(p).hasClass("jqfoot");)e(p).hide(),p=p.nextSibling}else if(p)for(;p&&!e(p).hasClass(s+"_"+String(o))&&!e(p).hasClass(s+"_"+String(o-1));)e(p).hide(),p=p.nextSibling;c.removeClass(n).addClass(d),u=!0}else{if(p)for(;p&&!e(p).hasClass(s+"_"+String(o))&&!e(p).hasClass(s+"_"+String(o-1));)e(p).show(),p=p.nextSibling;c.removeClass(d).addClass(n)}e(i).triggerHandler("jqGridGroupingClickGroup",[t,u]),e.isFunction(i.p.onClickGroup)&&i.p.onClickGroup.call(i,t,u)}),!1},groupingRender:function(t,i){return this.each(function(){function r(e,t,i){if(0===t)return i[e];var r=i[e].idx;if(0===r)return i[e];for(var a=e;a>=0;a--)if(i[a].idx===r-t)return i[a]}var a,o,s,n,d=this,l=d.p.groupingView,p="",c="",u=l.groupCollapse?l.plusicon:l.minusicon,h=[],f=l.groupField.length;u+=" tree-wrap-"+d.p.direction,n=0,e.each(d.p.colModel,function(e,t){for(var i=0;f>i;i++)if(l.groupField[i]===t.name){h[i]=e;break}});var g=0,m=l.groupSummary;m.reverse(),e.each(l.groups,function(n,v){g++,o=d.p.id+"ghead_"+v.idx,a=o+"_"+n,c="<span style='cursor:pointer;' class='ui-icon "+u+"' onclick=\"jQuery('#"+e.jgrid.jqID(d.p.id)+"').jqGrid('groupingToggle','"+a+"');return false;\"></span>";try{s=d.formatter(a,v.value,h[v.idx],v.value)}catch(j){s=v.value}p+='<tr id="'+a+'" role="row" class= "ui-widget-content jqgroup ui-row-'+d.p.direction+" "+o+'"><td style="padding-left:'+12*v.idx+'px;" colspan="'+i+'">'+c+e.jgrid.template(l.groupText[v.idx],s,v.cnt,v.summary)+"</td></tr>";var b=f-1===v.idx;if(b){for(var w=l.groups[n+1],y=void 0!==w?l.groups[n+1].startRow:t.length,q=v.startRow;y>q;q++)p+=t[q].join("");var x;if(void 0!==w){for(x=0;x<l.groupField.length&&w.dataIndex!==l.groupField[x];x++);g=l.groupField.length-x}for(var D=0;g>D;D++)if(m[D]){var $="";l.groupCollapse&&!l.showSummaryOnHide&&($=' style="display:none;"'),p+="<tr"+$+' role="row" class="ui-widget-content jqfoot ui-row-'+d.p.direction+'">';for(var _,C=r(n,D,l.groups),I=d.p.colModel,G=C.cnt,F=0;i>F;F++){var k="<td "+d.formatCol(F,1,"")+">&#160;</td>",S="{0}";e.each(C.summary,function(){if(this.nm===I[F].name){I[F].summaryTpl&&(S=I[F].summaryTpl),"avg"===this.st.toLowerCase()&&this.v&&G>0&&(this.v=this.v/G);try{_=d.formatter("",this.v,F,this)}catch(t){_=this.v}return k="<td "+d.formatCol(F,1,"")+">"+e.jgrid.format(S,_)+"</td>",!1}}),p+=k}p+="</tr>"}g=x}}),e("#"+e.jgrid.jqID(d.p.id)+" tbody:first").append(p),p=null})},groupingGroupBy:function(t,i){return this.each(function(){var r=this;"string"==typeof t&&(t=[t]);var a=r.p.groupingView;r.p.grouping=!0,"undefined"==typeof a.visibiltyOnNextGrouping&&(a.visibiltyOnNextGrouping=[]);var o;for(o=0;o<a.groupField.length;o++)!a.groupColumnShow[o]&&a.visibiltyOnNextGrouping[o]&&e(r).jqGrid("showCol",a.groupField[o]);for(o=0;o<t.length;o++)a.visibiltyOnNextGrouping[o]=e("#"+e.jgrid.jqID(r.p.id)+"_"+e.jgrid.jqID(t[o])).is(":visible");r.p.groupingView=e.extend(r.p.groupingView,i||{}),a.groupField=t,e(r).trigger("reloadGrid")})},groupingRemove:function(t){return this.each(function(){var i=this;if("undefined"==typeof t&&(t=!0),i.p.grouping=!1,t===!0){for(var r=i.p.groupingView,a=0;a<r.groupField.length;a++)!r.groupColumnShow[a]&&r.visibiltyOnNextGrouping[a]&&e(i).jqGrid("showCol",r.groupField);e("tr.jqgroup, tr.jqfoot","#"+e.jgrid.jqID(i.p.id)+" tbody:first").remove(),e("tr.jqgrow:hidden","#"+e.jgrid.jqID(i.p.id)+" tbody:first").show()}else e(i).trigger("reloadGrid")})},groupingCalculations:{handler:function(e,t,i,r,a,o){var s={sum:function(){return parseFloat(t||0)+parseFloat(o[i]||0)},min:function(){return""===t?parseFloat(o[i]||0):Math.min(parseFloat(t),parseFloat(o[i]||0))},max:function(){return""===t?parseFloat(o[i]||0):Math.max(parseFloat(t),parseFloat(o[i]||0))},count:function(){return""===t&&(t=0),o.hasOwnProperty(i)?t+1:0},avg:function(){return s.sum()}};if(!s[e])throw"jqGrid Grouping No such method: "+e;var n=s[e]();if(null!=r)if("fixed"==a)n=n.toFixed(r);else{var d=Math.pow(10,r);n=Math.round(n*d)/d}return n}}})}(jQuery),function(e){"use strict";e.jgrid.extend({jqGridImport:function(t){return t=e.extend({imptype:"xml",impstring:"",impurl:"",mtype:"GET",impData:{},xmlGrid:{config:"roots>grid",data:"roots>rows"},jsonGrid:{config:"grid",data:"data"},ajaxOptions:{}},t||{}),this.each(function(){var i=this,r=function(t,r){var a,o,s=e(r.xmlGrid.config,t)[0],n=e(r.xmlGrid.data,t)[0];if(xmlJsonClass.xml2json&&e.jgrid.parse){a=xmlJsonClass.xml2json(s," "),a=e.jgrid.parse(a);for(var d in a)a.hasOwnProperty(d)&&(o=a[d]);if(n){var l=a.grid.datatype;a.grid.datatype="xmlstring",a.grid.datastr=t,e(i).jqGrid(o).jqGrid("setGridParam",{datatype:l})}else e(i).jqGrid(o);a=null,o=null}else alert("xml2json or parse are not present")},a=function(t,r){if(t&&"string"==typeof t){var a=!1;e.jgrid.useJSON&&(e.jgrid.useJSON=!1,a=!0);var o=e.jgrid.parse(t);a&&(e.jgrid.useJSON=!0);var s=o[r.jsonGrid.config],n=o[r.jsonGrid.data];if(n){var d=s.datatype;s.datatype="jsonstring",s.datastr=n,e(i).jqGrid(s).jqGrid("setGridParam",{datatype:d})}else e(i).jqGrid(s)}};switch(t.imptype){case"xml":e.ajax(e.extend({url:t.impurl,type:t.mtype,data:t.impData,dataType:"xml",complete:function(a,o){"success"==o&&(r(a.responseXML,t),e(i).triggerHandler("jqGridImportComplete",[a,t]),e.isFunction(t.importComplete)&&t.importComplete(a)),a=null}},t.ajaxOptions));break;case"xmlstring":if(t.impstring&&"string"==typeof t.impstring){var o=e.jgrid.stringToDoc(t.impstring);o&&(r(o,t),e(i).triggerHandler("jqGridImportComplete",[o,t]),e.isFunction(t.importComplete)&&t.importComplete(o),t.impstring=null),o=null}break;case"json":e.ajax(e.extend({url:t.impurl,type:t.mtype,data:t.impData,dataType:"json",complete:function(r){try{a(r.responseText,t),e(i).triggerHandler("jqGridImportComplete",[r,t]),e.isFunction(t.importComplete)&&t.importComplete(r)}catch(o){}r=null}},t.ajaxOptions));break;case"jsonstring":t.impstring&&"string"==typeof t.impstring&&(a(t.impstring,t),e(i).triggerHandler("jqGridImportComplete",[t.impstring,t]),e.isFunction(t.importComplete)&&t.importComplete(t.impstring),t.impstring=null)}})},jqGridExport:function(t){t=e.extend({exptype:"xmlstring",root:"grid",ident:"	"},t||{});var i=null;return this.each(function(){if(this.grid){var r=e.extend(!0,{},e(this).jqGrid("getGridParam"));if(r.rownumbers&&(r.colNames.splice(0,1),r.colModel.splice(0,1)),r.multiselect&&(r.colNames.splice(0,1),r.colModel.splice(0,1)),r.subGrid&&(r.colNames.splice(0,1),r.colModel.splice(0,1)),r.knv=null,r.treeGrid)for(var a in r.treeReader)r.treeReader.hasOwnProperty(a)&&(r.colNames.splice(r.colNames.length-1),r.colModel.splice(r.colModel.length-1));switch(t.exptype){case"xmlstring":i="<"+t.root+">"+xmlJsonClass.json2xml(r,t.ident)+"</"+t.root+">";break;case"jsonstring":i="{"+xmlJsonClass.toJson(r,t.root,t.ident,!1)+"}",void 0!==r.postData.filters&&(i=i.replace(/filters":"/,'filters":'),i=i.replace(/}]}"/,"}]}"))}}}),i},excelExport:function(t){return t=e.extend({exptype:"remote",url:null,oper:"oper",tag:"excel",exportOptions:{}},t||{}),this.each(function(){if(this.grid){var i;if("remote"==t.exptype){var r=e.extend({},this.p.postData);r[t.oper]=t.tag;var a=jQuery.param(r);i=-1!=t.url.indexOf("?")?t.url+"&"+a:t.url+"?"+a,window.location=i}}})}})}(jQuery),function($){if($.browser.msie&&8==$.browser.version&&($.expr[":"].hidden=function(e){return 0===e.offsetWidth||0===e.offsetHeight||"none"==e.style.display}),$.jgrid._multiselect=!1,$.ui&&$.ui.multiselect){if($.ui.multiselect.prototype._setSelected){var setSelected=$.ui.multiselect.prototype._setSelected;$.ui.multiselect.prototype._setSelected=function(e,t){var i=setSelected.call(this,e,t);if(t&&this.selectedList){var r=this.element;this.selectedList.find("li").each(function(){$(this).data("optionLink")&&$(this).data("optionLink").remove().appendTo(r)})}return i}}$.ui.multiselect.prototype.destroy&&($.ui.multiselect.prototype.destroy=function(){this.element.show(),this.container.remove(),void 0===$.Widget?$.widget.prototype.destroy.apply(this,arguments):$.Widget.prototype.destroy.apply(this,arguments)}),$.jgrid._multiselect=!0}$.jgrid.extend({sortableColumns:function(e){return this.each(function(){function t(){i.p.disableClick=!0}var i=this,r=$.jgrid.jqID(i.p.id),a={tolerance:"pointer",axis:"x",scrollSensitivity:"1",items:">th:not(:has(#jqgh_"+r+"_cb,#jqgh_"+r+"_rn,#jqgh_"+r+"_subgrid),:hidden)",placeholder:{element:function(e){var t=$(document.createElement(e[0].nodeName)).addClass(e[0].className+" ui-sortable-placeholder ui-state-highlight").removeClass("ui-sortable-helper")[0];return t},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(),a=$(">th",r),o=i.p.colModel,s={},n=i.p.id+"_";$.each(o,function(e){s[this.name]=e});var d=[];a.each(function(){var e=$(">div",this).get(0).id.replace(/^jqgh_/,"").replace(n,"");e in s&&d.push(s[e])}),$(i).jqGrid("remapColumns",d,!0,!0),$.isFunction(i.p.sortable.update)&&i.p.sortable.update(d),setTimeout(function(){i.p.disableClick=!1},50)}};if(i.p.sortable.options?$.extend(a,i.p.sortable.options):$.isFunction(i.p.sortable)&&(i.p.sortable={update:i.p.sortable}),a.start){var o=a.start;a.start=function(e,i){t(),o.call(this,e,i)}}else a.start=t;i.p.sortable.exclude&&(a.items+=":not("+i.p.sortable.exclude+")"),e.sortable(a).data("sortable").floating=!0})},columnChooser:function(e){function t(e,t,i){if(t>=0){var r=e.slice(),a=r.splice(t,Math.max(e.length-t,t));return t>e.length&&(t=e.length),r[t]=i,r.concat(a)}}function i(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)))}var r=this;if(!$("#colchooser_"+$.jgrid.jqID(r[0].p.id)).length){var a=$('<div id="colchooser_'+r[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>'),o=$("select",a);if(e=$.extend({width:420,height:240,classname:null,done:function(e){e&&r.jqGrid("remapColumns",e,!0)},msel:"multiselect",dlog:"dialog",dialog_opts:{minWidth:470},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?e.modal:!1,resizable:e.resizable?e.resizable:!0,width:e.width+20},e.dialog_opts||{})},apply_perm:function(){$("option",o).each(function(){this.selected?r.jqGrid("showCol",s[this.value].name):r.jqGrid("hideCol",s[this.value].name)});var i=[];$("option:selected",o).each(function(){i.push(parseInt(this.value,10))}),$.each(i,function(){delete d[s[parseInt(this,10)].name]}),$.each(d,function(){var e=parseInt(this,10);i=t(i,e,e)}),e.done&&e.done.call(r,i)},cleanup:function(t){i(e.dlog,a,"destroy"),i(e.msel,o,"destroy"),a.remove(),t&&e.done&&e.done.call(r)},msel_opts:{}},$.jgrid.col,e||{}),$.ui&&$.ui.multiselect&&"multiselect"==e.msel){if(!$.jgrid._multiselect)return void alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");e.msel_opts=$.extend($.ui.multiselect.defaults,e.msel_opts)}e.caption&&a.attr("title",e.caption),e.classname&&(a.addClass(e.classname),o.addClass(e.classname)),e.width&&($(">div",a).css({width:e.width,margin:"0 auto"}),o.css("width",e.width)),e.height&&($(">div",a).css("height",e.height),o.css("height",e.height-10));var s=r.jqGrid("getGridParam","colModel"),n=r.jqGrid("getGridParam","colNames"),d={},l=[];o.empty(),$.each(s,function(e){return d[this.name]=e,this.hidedlg?void(this.hidden||l.push(e)):void o.append("<option value='"+e+"' "+(this.hidden?"":"selected='selected'")+">"+jQuery.jgrid.stripHtml(n[e])+"</option>")});var p=$.isFunction(e.dlog_opts)?e.dlog_opts.call(r,e):e.dlog_opts;i(e.dlog,a,p);var c=$.isFunction(e.msel_opts)?e.msel_opts.call(r,e):e.msel_opts;i(e.msel,o,c)}},sortableRows:function(e){return this.each(function(){var t=this;t.grid&&(t.p.treeGrid||$.fn.sortable&&(e=$.extend({cursor:"move",axis:"y",items:".jqgrow"},e||{}),e.start&&$.isFunction(e.start)?(e._start_=e.start,delete e.start):e._start_=!1,e.update&&$.isFunction(e.update)?(e._update_=e.update,delete e.update):e._update_=!1,e.start=function(i,r){if($(r.item).css("border-width","0px"),$("td",r.item).each(function(e){this.style.width=t.grid.cols[e].style.width}),t.p.subGrid){var a=$(r.item).attr("id");try{$(t).jqGrid("collapseSubGridRow",a)}catch(o){}}e._start_&&e._start_.apply(this,[i,r])},e.update=function(i,r){$(r.item).css("border-width",""),t.p.rownumbers===!0&&$("td.jqgrid-rownum",t.rows).each(function(e){$(this).html(e+1+(parseInt(t.p.page,10)-1)*parseInt(t.p.rowNum,10))}),e._update_&&e._update_.apply(this,[i,r])},$("tbody:first",t).sortable(e),$("tbody:first",t).disableSelection()))})},gridDnD:function(e){return this.each(function(){function t(){var e=$.data(i,"dnd");$("tr.jqgrow:not(.ui-draggable)",i).draggable($.isFunction(e.drag)?e.drag.call($(i),e):e.drag)}var i=this;if(i.grid&&!i.p.treeGrid&&$.fn.draggable&&$.fn.droppable){var r="<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>";if(null===$("#jqgrid_dnd").html()&&$("body").append(r),"string"==typeof e&&"updateDnD"==e&&i.p.jqgdnd===!0)return void t();if(e=$.extend({drag:function(e){return $.extend({start:function(t,r){if(i.p.subGrid){var a=$(r.helper).attr("id");try{$(i).jqGrid("collapseSubGridRow",a)}catch(o){}}for(var s=0;s<$.data(i,"dnd").connectWith.length;s++)"0"==$($.data(i,"dnd").connectWith[s]).jqGrid("getGridParam","reccount")&&$($.data(i,"dnd").connectWith[s]).jqGrid("addRowData","jqg_empty_row",{});r.helper.addClass("ui-state-highlight"),$("td",r.helper).each(function(e){this.style.width=i.grid.headers[e].width+"px"}),e.onstart&&$.isFunction(e.onstart)&&e.onstart.call($(i),t,r)},stop:function(t,r){if(r.helper.dropped&&!e.dragcopy){var a=$(r.helper).attr("id");void 0===a&&(a=$(this).attr("id")),$(i).jqGrid("delRowData",a)}for(var o=0;o<$.data(i,"dnd").connectWith.length;o++)$($.data(i,"dnd").connectWith[o]).jqGrid("delRowData","jqg_empty_row");e.onstop&&$.isFunction(e.onstop)&&e.onstop.call($(i),t,r)}},e.drag_opts||{})},drop:function(e){return $.extend({accept:function(e){if(!$(e).hasClass("jqgrow"))return e;var t=$(e).closest("table.ui-jqgrid-btable");if(t.length>0&&void 0!==$.data(t[0],"dnd")){var i=$.data(t[0],"dnd").connectWith;return-1!=$.inArray("#"+$.jgrid.jqID(this.id),i)?!0:!1}return!1},drop:function(t,r){if($(r.draggable).hasClass("jqgrow")){var a=$(r.draggable).attr("id"),o=r.draggable.parent().parent().jqGrid("getRowData",a);if(!e.dropbyname){var s,n=0,d={},l=$("#"+$.jgrid.jqID(this.id)).jqGrid("getGridParam","colModel");try{for(var p in o)s=l[n].name,"cb"!=s&&"rn"!=s&&"subgrid"!=s&&o.hasOwnProperty(p)&&l[n]&&(d[s]=o[p]),n++;o=d}catch(c){}}if(r.helper.dropped=!0,e.beforedrop&&$.isFunction(e.beforedrop)){var u=e.beforedrop.call(this,t,r,o,$("#"+$.jgrid.jqID(i.p.id)),$(this));"undefined"!=typeof u&&null!=u&&"object"==typeof u&&(o=u)}if(r.helper.dropped){var h;e.autoid&&($.isFunction(e.autoid)?h=e.autoid.call(this,o):(h=Math.ceil(1e3*Math.random()),h=e.autoidprefix+h)),$("#"+$.jgrid.jqID(this.id)).jqGrid("addRowData",h,o,e.droppos)}e.ondrop&&$.isFunction(e.ondrop)&&e.ondrop.call(this,t,r,o)}}},e.drop_opts||{})},onstart:null,onstop:null,beforedrop:null,ondrop:null,drop_opts:{activeClass:"ui-state-active",hoverClass:"ui-state-hover"},drag_opts:{revert:"invalid",helper:"clone",cursor:"move",appendTo:"#jqgrid_dnd",zIndex:5e3},dragcopy:!1,dropbyname:!1,droppos:"first",autoid:!0,autoidprefix:"dnd_"},e||{}),e.connectWith){e.connectWith=e.connectWith.split(","),e.connectWith=$.map(e.connectWith,function(e){return $.trim(e)}),$.data(i,"dnd",e),"0"==i.p.reccount||i.p.jqgdnd||t(),i.p.jqgdnd=!0;for(var a=0;a<e.connectWith.length;a++){var o=e.connectWith[a];$(o).droppable($.isFunction(e.drop)?e.drop.call($(i),e):e.drop)}}}})},gridResize:function(opts){return this.each(function(){var $t=this,gID=$.jgrid.jqID($t.p.id);if($t.grid&&$.fn.resizable){if(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)},opts._alsoResize_){var optstest="{'#gview_"+gID+" .ui-jqgrid-bdiv':true,'"+opts._alsoResize_+"':true}";opts.alsoResize=eval("("+optstest+")")}else opts.alsoResize=$(".ui-jqgrid-bdiv","#gview_"+gID);delete opts._alsoResize_,$("#gbox_"+gID).resizable(opts)}})}})}(jQuery);
(function($){
/*
 * jqGrid methods without support. Use as you wish
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
 *
 * This list of deprecated methods.
 * If you instead want to use them, please include this file after the grid main file.
 * Some methods will be then overwritten.
 *
 */
/*global jQuery, $ */

$.jgrid.extend({
// This is the ols search Filter method used in navigator.
	searchGrid : function (p) {
		p = $.extend({
			recreateFilter: false,
			drag: true,
			sField:'searchField',
			sValue:'searchString',
			sOper: 'searchOper',
			sFilter: 'filters',
            loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only.
			beforeShowSearch: null,
			afterShowSearch : null,
			onInitializeSearch: null,
			closeAfterSearch : false,
			closeAfterReset: false,
			closeOnEscape : false,
			multipleSearch : false,
			cloneSearchRowOnAdd: true,
			// translation
			// if you want to change or remove the order change it in sopt
			// ['bw','eq','ne','lt','le','gt','ge','ew','cn']
			sopt: null,
			// Note: stringResult is intentionally declared "undefined by default".
			//  you are velcome to define stringResult expressly in the options you pass to searchGrid()
			//  stringResult is a "safeguard" measure to insure we post sensible data when communicated as form-encoded
			//  see http://github.com/tonytomov/jqGrid/issues/#issue/36
			//
			//  If this value is not expressly defined in the incoming options,
			// lower in the code we will infer the value based on value of multipleSearch
			stringResult: undefined,
			onClose : null,
			// useDataProxy allows ADD, EDIT and DEL code to bypass calling $.ajax
			// directly when grid's 'dataProxy' property (grid.p.dataProxy) is a function.
			// Used for "editGridRow" and "delGridRow" below and automatically flipped to TRUE
			// when ajax setting's 'url' (grid's 'editurl') property is undefined.
			// When 'useDataProxy' is true, instead of calling $.ajax.call(gridDOMobj, o, i) we call
			// gridDOMobj.p.dataProxy.call(gridDOMobj, o, i)
			//
			// Behavior is extremely similar to when 'datatype' is a function, but arguments are slightly different.
			// Normally the following is fed to datatype.call(a, b, c):
			//   a = Pointer to grid's table DOM element, b = grid.p.postdata, c = "load_"+grid's ID
			// In cases of "edit" and "del" the following is fed:
			//   a = Pointer to grid's table DOM element (same),
			//   b = extended Ajax Options including postdata in "data" property. (different object type)
			//   c = "set_"+grid's ID in case of "edit" and "del_"+grid's ID in case of "del" (same type, different content)
			// The major difference is that complete ajax options object, with attached "complete" and "error"
			// callback functions is fed instead of only post data.
			// This allows you to emulate a $.ajax call (including calling "complete"/"error"),
			// while retrieving the data locally in the browser.
			useDataProxy: false,
			overlay : true
		}, $.jgrid.search, p || {});
		return this.each(function() {
			var $t = this;
			if(!$t.grid) {return;}
			var fid = "fbox_"+$t.p.id,
			showFrm = true;
            function applyDefaultFilters(gridDOMobj, filterSettings) {
				/*
                gridDOMobj = ointer to grid DOM object ( $(#list)[0] )
                What we need from gridDOMobj:
                gridDOMobj.SearchFilter is the pointer to the Search box, once it's created.
                gridDOMobj.p.postData - dictionary of post settings. These can be overriden at grid creation to
                contain default filter settings. We will parse these and will populate the search with defaults.
                filterSettings - same settings object you (would) pass to $().jqGrid('searchGrid', filterSettings);
                */

                // Pulling default filter settings out of postData property of grid's properties.:
                var defaultFilters = gridDOMobj.p.postData[filterSettings.sFilter];
                // example of what we might get: {"groupOp":"and","rules":[{"field":"amount","op":"eq","data":"100"}]}
				// suppose we have imported this with grid import, the this is a string.
				if(typeof(defaultFilters) == "string") {
					defaultFilters = $.jgrid.parse(defaultFilters);
				}
                if (defaultFilters) {
                    if (defaultFilters.groupOp) {
                        gridDOMobj.SearchFilter.setGroupOp(defaultFilters.groupOp);
                    }
                    if (defaultFilters.rules) {
                        var f, i = 0, li = defaultFilters.rules.length, success = false;
                        for (; i < li; i++) {
                            f = defaultFilters.rules[i];
                            // we are not trying to counter all issues with filter declaration here. Just the basics to avoid lookup exceptions.
                            if (f.field !== undefined && f.op !== undefined && f.data !== undefined) {
                                success = gridDOMobj.SearchFilter.setFilter({
                                    'sfref':gridDOMobj.SearchFilter.$.find(".sf:last"),
                                    'filter':$.extend({},f)
                                });
								if (success) { gridDOMobj.SearchFilter.add(); }
                            }
                        }
                    }
				}
            } // end of applyDefaultFilters
			function hideFilter(selector) {
				if(p.onClose){
					var fclm = p.onClose(selector);
					if(typeof fclm == 'boolean' && !fclm) { return; }
				}
				selector.hide();
				if(p.overlay === true) {
					$(".jqgrid-overlay:first","#gbox_"+$t.p.id).hide();
				}
			}
			function showFilter(){
				var fl = $(".ui-searchFilter").length;
				if(fl > 1) {
					var zI = $("#"+fid).css("zIndex");
					$("#"+fid).css({zIndex:parseInt(zI,10)+fl});
				}
				$("#"+fid).show();
				if(p.overlay === true) {
					$(".jqgrid-overlay:first","#gbox_"+$t.p.id).show();
				}
				try{$(':input:visible',"#"+fid)[0].focus();}catch(_){}
			}
			function searchFilters(filters) {
				var hasFilters = (filters !== undefined),
				grid = $("#"+$t.p.id),
				sdata={};
				if(p.multipleSearch===false) {
					sdata[p.sField] = filters.rules[0].field;
					sdata[p.sValue] = filters.rules[0].data;
					sdata[p.sOper] = filters.rules[0].op;
					if(sdata.hasOwnProperty(p.sFilter) ) {
						delete sdata[p.sFilter];
					}
				} else {
					sdata[p.sFilter] = filters;
					$.each([p.sField, p.sValue, p.sOper], function(i, n){
						if(sdata.hasOwnProperty(n)) { delete sdata[n];}
					});
				}
				grid[0].p.search = hasFilters;
				$.extend(grid[0].p.postData,sdata);
				grid.trigger("reloadGrid",[{page:1}]);
				if(p.closeAfterSearch) { hideFilter($("#"+fid)); }
			}
			function resetFilters(op) {
				var reload = op && op.hasOwnProperty("reload") ? op.reload : true,
				grid = $("#"+$t.p.id),
				sdata={};
				grid[0].p.search = false;
				if(p.multipleSearch===false) {
					sdata[p.sField] = sdata[p.sValue] = sdata[p.sOper] = "";
				} else {
					sdata[p.sFilter] = "";
				}
				$.extend(grid[0].p.postData,sdata);
				if(reload) {
					grid.trigger("reloadGrid",[{page:1}]);
				}
				if(p.closeAfterReset) { hideFilter($("#"+fid)); }
			}
			if($.fn.searchFilter) {
				if(p.recreateFilter===true) {$("#"+fid).remove();}
				if( $("#"+fid).html() !== null ) {
					if ( $.isFunction(p.beforeShowSearch) ) {
						showFrm = p.beforeShowSearch($("#"+fid));
						if(typeof(showFrm) == "undefined") {
							showFrm = true;
						}
					}
					if(showFrm === false) { return; }
					showFilter();
					if( $.isFunction(p.afterShowSearch) ) { p.afterShowSearch($("#"+fid)); }
				} else {
					var fields = [],
					colNames = $("#"+$t.p.id).jqGrid("getGridParam","colNames"),
					colModel = $("#"+$t.p.id).jqGrid("getGridParam","colModel"),
					stempl = ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'],
					j,pos,k,oprtr=[];
					if (p.sopt !==null) {
						k=0;
						for(j=0;j<p.sopt.length;j++) {
							if( (pos= $.inArray(p.sopt[j],stempl)) != -1 ){
								oprtr[k] = {op:p.sopt[j],text: p.odata[pos]};
								k++;
							}
						}
					} else {
						for(j=0;j<stempl.length;j++) {
							oprtr[j] = {op:stempl[j],text: p.odata[j]};
						}
					}
				    $.each(colModel, function(i, v) {
				        var searchable = (typeof v.search === 'undefined') ?  true: v.search ,
				        hidden = (v.hidden === true),
						soptions = $.extend({}, {text: colNames[i], itemval: v.index || v.name}, this.searchoptions),
						ignoreHiding = (soptions.searchhidden === true);
						if(typeof soptions.sopt !== 'undefined') {
							k=0;
							soptions.ops =[];
							if(soptions.sopt.length>0) {
								for(j=0;j<soptions.sopt.length;j++) {
									if( (pos= $.inArray(soptions.sopt[j],stempl)) != -1 ){
										soptions.ops[k] = {op:soptions.sopt[j],text: p.odata[pos]};
										k++;
									}
								}
							}
						}
						if(typeof(this.stype) === 'undefined') { this.stype='text'; }
						if(this.stype == 'select') {
							if ( soptions.dataUrl !== undefined) {}
							else {
								var eov;
								if(soptions.value) {
									eov = soptions.value;
								} else if(this.editoptions) {
									eov = this.editoptions.value;
								}
								if(eov) {
									soptions.dataValues =[];
									if(typeof(eov) === 'string') {
										var so = eov.split(";"),sv;
										for(j=0;j<so.length;j++) {
											sv = so[j].split(":");
											soptions.dataValues[j] ={value:sv[0],text:sv[1]};
										}
									} else if (typeof(eov) === 'object') {
										j=0;
										for (var key in eov) {
											if(eov.hasOwnProperty(key)) {
												soptions.dataValues[j] ={value:key,text:eov[key]};
												j++;
											}
										}
									}
								}
							}
						}
				        if ((ignoreHiding && searchable) || (searchable && !hidden)) {
							fields.push(soptions);
						}
					});
					if(fields.length>0){
						$("<div id='"+fid+"' role='dialog' tabindex='-1'></div>").insertBefore("#gview_"+$t.p.id);
						// Before we create searchFilter we need to decide if we want to get back a string or a JS object.
						//  see http://github.com/tonytomov/jqGrid/issues/#issue/36 for background on the issue.
						// If p.stringResult is defined, it was explisitly passed to us by user. Honor the choice, whatever it is.
						if (p.stringResult===undefined) {
							// to provide backward compatibility, inferring stringResult value from multipleSearch
							p.stringResult = p.multipleSearch;
						}
						// we preserve the return value here to retain access to .add() and other good methods of search form.
						$t.SearchFilter = $("#"+fid).searchFilter(fields, { groupOps: p.groupOps, operators: oprtr, onClose:hideFilter, resetText: p.Reset, searchText: p.Find, windowTitle: p.caption,  rulesText:p.rulesText, matchText:p.matchText, onSearch: searchFilters, onReset: resetFilters,stringResult:p.stringResult, ajaxSelectOptions: $.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions ||{}), clone: p.cloneSearchRowOnAdd });
						$(".ui-widget-overlay","#"+fid).remove();
						if($t.p.direction=="rtl") { $(".ui-closer","#"+fid).css("float","left"); }
						if (p.drag===true) {
							$("#"+fid+" table thead tr:first td:first").css('cursor','move');
							if(jQuery.fn.jqDrag) {
								$("#"+fid).jqDrag($("#"+fid+" table thead tr:first td:first"));
							} else {
								try {
									$("#"+fid).draggable({handle: $("#"+fid+" table thead tr:first td:first")});
								} catch (e) {}
							}
						}
						if(p.multipleSearch === false) {
							$(".ui-del, .ui-add, .ui-del, .ui-add-last, .matchText, .rulesText", "#"+fid).hide();
							$("select[name='groupOp']","#"+fid).hide();
						}
                        if (p.multipleSearch === true && p.loadDefaults === true) {
                            applyDefaultFilters($t, p);
                        }
						if ( $.isFunction(p.onInitializeSearch) ) { p.onInitializeSearch( $("#"+fid) ); }
						if ( $.isFunction(p.beforeShowSearch) ) {
							showFrm = p.beforeShowSearch($("#"+fid));
							if(typeof(showFrm) == "undefined") {
								showFrm = true;
							}
						}
						if(showFrm === false) { return; }
						showFilter();
						if( $.isFunction(p.afterShowSearch) ) { p.afterShowSearch($("#"+fid)); }
						if(p.closeOnEscape===true){
							$("#"+fid).keydown( function( e ) {
								if( e.which == 27 ) {
									hideFilter($("#"+fid));
								}
								if (e.which == 13) {
									$(".ui-search", this).click();
								}
							});
						}
					}
				}
			}
		});
	},
	// methods taken from grid.custom.
	updateGridRows : function (data, rowidname, jsonreader) {
		var nm, success=false, title;
		this.each(function(){
			var t = this, vl, ind, srow, sid;
			if(!t.grid) {return false;}
			if(!rowidname) { rowidname = "id"; }
			if( data  && data.length >0 ) {
				$(data).each(function(j){
					srow = this;
					ind = t.rows.namedItem(srow[rowidname]);
					if(ind) {
						sid = srow[rowidname];
						if(jsonreader === true){
							if(t.p.jsonReader.repeatitems === true) {
								if(t.p.jsonReader.cell) {srow = srow[t.p.jsonReader.cell];}
								for (var k=0;k<srow.length;k++) {
									vl = t.formatter( sid, srow[k], k, srow, 'edit');
									title = t.p.colModel[k].title ? {"title":$.jgrid.stripHtml(vl)} : {};
									if(t.p.treeGrid===true && nm == t.p.ExpandColumn) {
										$("td:eq("+k+") > span:first",ind).html(vl).attr(title);
									} else {
										$("td:eq("+k+")",ind).html(vl).attr(title);
									}
								}
								success = true;
								return true;
							}
						}
						$(t.p.colModel).each(function(i){
							nm = jsonreader===true ? this.jsonmap || this.name :this.name;
							if( srow[nm] !== undefined) {
								vl = t.formatter( sid, srow[nm], i, srow, 'edit');
								title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {};
								if(t.p.treeGrid===true && nm == t.p.ExpandColumn) {
									$("td:eq("+i+") > span:first",ind).html(vl).attr(title);
								} else {
									$("td:eq("+i+")",ind).html(vl).attr(title);
								}
								success = true;
							}
						});
					}
				});
			}
		});
		return success;
	},
	// Form search - sorry for this method. Instead use ne jqFilter method.
	filterGrid : function(gridid,p){
		p = $.extend({
			gridModel : false,
			gridNames : false,
			gridToolbar : false,
			filterModel: [], // label/name/stype/defval/surl/sopt
			formtype : "horizontal", // horizontal/vertical
			autosearch: true, // if set to false a serch button should be enabled.
			formclass: "filterform",
			tableclass: "filtertable",
			buttonclass: "filterbutton",
			searchButton: "Search",
			clearButton: "Clear",
			enableSearch : false,
			enableClear: false,
			beforeSearch: null,
			afterSearch: null,
			beforeClear: null,
			afterClear: null,
			url : '',
			marksearched: true
		},p  || {});
		return this.each(function(){
			var self = this;
			this.p = p;
			if(this.p.filterModel.length === 0 && this.p.gridModel===false) { alert("No filter is set"); return;}
			if( !gridid) {alert("No target grid is set!"); return;}
			this.p.gridid = gridid.indexOf("#") != -1 ? gridid : "#"+gridid;
			var gcolMod = $(this.p.gridid).jqGrid("getGridParam",'colModel');
			if(gcolMod) {
				if( this.p.gridModel === true) {
					var thegrid = $(this.p.gridid)[0];
					var sh;
					// we should use the options search, edittype, editoptions
					// additionally surl and defval can be added in grid colModel
					$.each(gcolMod, function (i,n) {
						var tmpFil = [];
						this.search = this.search === false ? false : true;
						if(this.editrules && this.editrules.searchhidden === true) {
							sh = true;
						} else {
							if(this.hidden === true ) {
								sh = false;
							} else {
								sh = true;
							}
						}
						if( this.search === true && sh === true) {
							if(self.p.gridNames===true) {
								tmpFil.label = thegrid.p.colNames[i];
							} else {
								tmpFil.label = '';
							}
							tmpFil.name = this.name;
							tmpFil.index = this.index || this.name;
							// we support only text and selects, so all other to text
							tmpFil.stype = this.edittype || 'text';
							if(tmpFil.stype != 'select' ) {
								tmpFil.stype = 'text';
							}
							tmpFil.defval = this.defval || '';
							tmpFil.surl = this.surl || '';
							tmpFil.sopt = this.editoptions || {};
							tmpFil.width = this.width;
							self.p.filterModel.push(tmpFil);
						}
					});
				} else {
					$.each(self.p.filterModel,function(i,n) {
						for(var j=0;j<gcolMod.length;j++) {
							if(this.name == gcolMod[j].name) {
								this.index = gcolMod[j].index || this.name;
								break;
							}
						}
						if(!this.index) {
							this.index = this.name;
						}
					});
				}
			} else {
				alert("Could not get grid colModel"); return;
			}
			var triggerSearch = function() {
				var sdata={}, j=0, v;
				var gr = $(self.p.gridid)[0], nm;
                gr.p.searchdata = {};
				if($.isFunction(self.p.beforeSearch)){self.p.beforeSearch();}
				$.each(self.p.filterModel,function(i,n){
                    nm = this.index;
					if(this.stype === 'select') {
						v = $("select[name="+nm+"]",self).val();
						if(v) {
							sdata[nm] = v;
							if(self.p.marksearched){
								$("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell");
							}
							j++;
						} else {
							if(self.p.marksearched){
								$("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell");
							}
                               try {
                                   delete gr.p.postData[this.index];
                               } catch (e) {}
						}
					} else {
						v = $("input[name="+nm+"]",self).val();
						if(v) {
							sdata[nm] = v;
							if(self.p.marksearched){
								$("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell");
							}
							j++;
						} else {
							if(self.p.marksearched){
								$("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell");
							}
								try {
									delete gr.p.postData[this.index];
                            } catch(x) {}
						}
					}
				});
				var sd =  j>0 ? true : false;
                $.extend(gr.p.postData,sdata);
				var saveurl;
				if(self.p.url) {
					saveurl = $(gr).jqGrid("getGridParam",'url');
					$(gr).jqGrid("setGridParam",{url:self.p.url});
				}
			    $(gr).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]);
				if(saveurl) {$(gr).jqGrid("setGridParam",{url:saveurl});}
				if($.isFunction(self.p.afterSearch)){self.p.afterSearch();}
			};
			var clearSearch = function(){
				var sdata={}, v, j=0;
				var gr = $(self.p.gridid)[0], nm;
				if($.isFunction(self.p.beforeClear)){self.p.beforeClear();}
				$.each(self.p.filterModel,function(i,n){
                    nm = this.index;
					v = (this.defval) ? this.defval : "";
					if(!this.stype){this.stype='text';}
					switch (this.stype) {
						case 'select' :
							var v1;
							$("select[name="+nm+"] option",self).each(function (i){
                                if(i===0) { this.selected = true; }
								if ($(this).text() == v) {
									this.selected = true;
									v1 = $(this).val();
									return false;
								}
							});
							if(v1) {
								// post the key and not the text
								sdata[nm] = v1;
								if(self.p.marksearched){
									$("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell");
								}
								j++;
							} else {
								if(self.p.marksearched){
									$("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell");
								}
                                try {
                                    delete gr.p.postData[this.index];
                                } catch (e) {}
							}
							break;
						case 'text':
							$("input[name="+nm+"]",self).val(v);
							if(v) {
								sdata[nm] = v;
								if(self.p.marksearched){
									$("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell");
								}
								j++;
							} else {
								if(self.p.marksearched){
									$("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell");
								}
                                try {
                                    delete gr.p.postData[this.index];
                                } catch (k) {}
							}
                            break;
					}
				});
				var sd =  j>0 ? true : false;
                $.extend(gr.p.postData,sdata);
				var saveurl;
				if(self.p.url) {
					saveurl = $(gr).jqGrid("getGridParam",'url');
					$(gr).jqGrid("setGridParam",{url:self.p.url});
				}
				$(gr).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]);
				if(saveurl) {$(gr).jqGrid("setGridParam",{url:saveurl});}
				if($.isFunction(self.p.afterClear)){self.p.afterClear();}
			};
			var tbl;
			var formFill = function(){
				var tr = document.createElement("tr");
				var tr1, sb, cb,tl,td;
				if(self.p.formtype=='horizontal'){
					$(tbl).append(tr);
				}
				$.each(self.p.filterModel,function(i,n){
					tl = document.createElement("td");
					$(tl).append("<label for='"+this.name+"'>"+this.label+"</label>");
					td = document.createElement("td");
					var $t=this;
					if(!this.stype) { this.stype='text';}
					switch (this.stype)
					{
					case "select":
						if(this.surl) {
							// data returned should have already constructed html select
							$(td).load(this.surl,function(){
								if($t.defval) { $("select",this).val($t.defval); }
								$("select",this).attr({name:$t.index || $t.name, id: "sg_"+$t.name});
								if($t.sopt) { $("select",this).attr($t.sopt); }
								if(self.p.gridToolbar===true && $t.width) {
									$("select",this).width($t.width);
								}
								if(self.p.autosearch===true){
									$("select",this).change(function(e){
										triggerSearch();
										return false;
									});
								}
							});
						} else {
							// sopt to construct the values
							if($t.sopt.value) {
								var oSv = $t.sopt.value;
								var elem = document.createElement("select");
								$(elem).attr({name:$t.index || $t.name, id: "sg_"+$t.name}).attr($t.sopt);
								var so, sv, ov;
								if(typeof oSv === "string") {
									so = oSv.split(";");
									for(var k=0; k<so.length;k++){
										sv = so[k].split(":");
										ov = document.createElement("option");
										ov.value = sv[0]; ov.innerHTML = sv[1];
										if (sv[1]==$t.defval) { ov.selected ="selected"; }
										elem.appendChild(ov);
									}
								} else if(typeof oSv === "object" ) {
									for ( var key in oSv) {
										if(oSv.hasOwnProperty(key)) {
											i++;
											ov = document.createElement("option");
											ov.value = key; ov.innerHTML = oSv[key];
											if (oSv[key]==$t.defval) { ov.selected ="selected"; }
											elem.appendChild(ov);
										}
									}
								}
								if(self.p.gridToolbar===true && $t.width) {
									$(elem).width($t.width);
								}
								$(td).append(elem);
								if(self.p.autosearch===true){
									$(elem).change(function(e){
										triggerSearch();
										return false;
									});
								}
							}
						}
						break;
					case 'text':
						var df = this.defval ? this.defval: "";
						$(td).append("<input type='text' name='"+(this.index || this.name)+"' id='sg_"+this.name+"' value='"+df+"'/>");
						if($t.sopt) { $("input",td).attr($t.sopt); }
						if(self.p.gridToolbar===true && $t.width) {
							if($.browser.msie) {
								$("input",td).width($t.width-4);
							} else {
								$("input",td).width($t.width-2);
							}
						}
						if(self.p.autosearch===true){
							$("input",td).keypress(function(e){
								var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
								if(key == 13){
									triggerSearch();
									return false;
								}
								return this;
							});
						}
						break;
					}
					if(self.p.formtype=='horizontal'){
						if(self.p.gridToolbar===true && self.p.gridNames===false) {
							$(tr).append(td);
						} else {
							$(tr).append(tl).append(td);
						}
						$(tr).append(td);
					} else {
						tr1 = document.createElement("tr");
						$(tr1).append(tl).append(td);
						$(tbl).append(tr1);
					}
				});
				td = document.createElement("td");
				if(self.p.enableSearch === true){
					sb = "<input type='button' id='sButton' class='"+self.p.buttonclass+"' value='"+self.p.searchButton+"'/>";
					$(td).append(sb);
					$("input#sButton",td).click(function(){
						triggerSearch();
						return false;
					});
				}
				if(self.p.enableClear === true) {
					cb = "<input type='button' id='cButton' class='"+self.p.buttonclass+"' value='"+self.p.clearButton+"'/>";
					$(td).append(cb);
					$("input#cButton",td).click(function(){
						clearSearch();
						return false;
					});
				}
				if(self.p.enableClear === true || self.p.enableSearch === true) {
					if(self.p.formtype=='horizontal') {
						$(tr).append(td);
					} else {
						tr1 = document.createElement("tr");
						$(tr1).append("<td>&#160;</td>").append(td);
						$(tbl).append(tr1);
					}
				}
			};
			var frm = $("<form name='SearchForm' style=display:inline;' class='"+this.p.formclass+"'></form>");
			tbl =$("<table class='"+this.p.tableclass+"' cellspacing='0' cellpading='0' border='0'><tbody></tbody></table>");
			$(frm).append(tbl);
			formFill();
			$(this).append(frm);
			this.triggerSearch = triggerSearch;
			this.clearSearch = clearSearch;
		});
	}

});
})(jQuery);
/**
 * TableDnD plug-in for JQuery, allows you to drag and drop table rows
 * You can set up various options to control how the system will work
 * Copyright (c) Denis Howlett <denish@isocra.com>
 * Licensed like jQuery, see http://docs.jquery.com/License.
 *
 * Configuration options:
 * 
 * onDragStyle
 *     This is the style that is assigned to the row during drag. There are limitations to the styles that can be
 *     associated with a row (such as you can't assign a border--well you can, but it won't be
 *     displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
 *     a map (as used in the jQuery css(...) function).
 * onDropStyle
 *     This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
 *     to what you can do. Also this replaces the original style, so again consider using onDragClass which
 *     is simply added and then removed on drop.
 * onDragClass
 *     This class is added for the duration of the drag and then removed when the row is dropped. It is more
 *     flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
 *     is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
 *     stylesheet.
 * onDrop
 *     Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
 *     and the row that was dropped. You can work out the new order of the rows by using
 *     table.rows.
 * onDragStart
 *     Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
 *     table and the row which the user has started to drag.
 * onAllowDrop
 *     Pass a function that will be called as a row is over another row. If the function returns true, allow 
 *     dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
 *     the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
 * scrollAmount
 *     This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
 *     window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
 *     FF3 beta
 * dragHandle
 *     This is the name of a class that you assign to one or more cells in each row that is draggable. If you
 *     specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
 *     will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
 *     the whole row is draggable.
 * 
 * Other ways to control behaviour:
 *
 * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
 * that you don't want to be draggable.
 *
 * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
 * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
 * an ID as must all the rows.
 *
 * Other methods:
 *
 * $("...").tableDnDUpdate() 
 * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
 * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
 * The table maintains the original configuration (so you don't have to specify it again).
 *
 * $("...").tableDnDSerialize()
 * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
 * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
 *
 * Known problems:
 * - Auto-scoll has some problems with IE7  (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
 * 
 * Version 0.2: 2008-02-20 First public version
 * Version 0.3: 2008-02-07 Added onDragStart option
 *                         Made the scroll amount configurable (default is 5 as before)
 * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
 *                         Added onAllowDrop to control dropping
 *                         Fixed a bug which meant that you couldn't set the scroll amount in both directions
 *                         Added serialize method
 * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
 *                         draggable
 *                         Improved the serialize method to use a default (and settable) regular expression.
 *                         Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
 */
jQuery.tableDnD = {
    /** Keep hold of the current table being dragged */
    currentTable : null,
    /** Keep hold of the current drag object if any */
    dragObject: null,
    /** The current mouse offset */
    mouseOffset: null,
    /** Remember the old value of Y so that we don't do too much processing */
    oldY: 0,

    /** Actually build the structure */
    build: function(options) {
        // Set up the defaults if any

        this.each(function() {
            // This is bound to each matching table, set up the defaults and override with user options
            this.tableDnDConfig = jQuery.extend({
                onDragStyle: null,
                onDropStyle: null,
				// Add in the default class for whileDragging
				onDragClass: "tDnD_whileDrag",
                onDrop: null,
                onDragStart: null,
                scrollAmount: 5,
				serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
				serializeParamName: null, // If you want to specify another parameter name instead of the table ID
                dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
            }, options || {});
            // Now make the rows draggable
            jQuery.tableDnD.makeDraggable(this);
        });

        // Now we need to capture the mouse up and mouse move event
        // We can use bind so that we don't interfere with other event handlers
        jQuery(document)
            .bind('mousemove', jQuery.tableDnD.mousemove)
            .bind('mouseup', jQuery.tableDnD.mouseup);

        // Don't break the chain
        return this;
    },

    /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
    makeDraggable: function(table) {
        var config = table.tableDnDConfig;
		if (table.tableDnDConfig.dragHandle) {
			// We only need to add the event to the specified cells
			var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
			cells.each(function() {
				// The cell is bound to "this"
                jQuery(this).mousedown(function(ev) {
                    jQuery.tableDnD.dragObject = this.parentNode;
                    jQuery.tableDnD.currentTable = table;
                    jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                    if (config.onDragStart) {
                        // Call the onDrop method if there is one
                        config.onDragStart(table, this);
                    }
                    return false;
                });
			})
		} else {
			// For backwards compatibility, we add the event to the whole row
	        var rows = jQuery("tr", table); // get all the rows as a wrapped set
	        rows.each(function() {
				// Iterate through each row, the row is bound to "this"
				var row = jQuery(this);
				if (! row.hasClass("nodrag")) {
	                row.mousedown(function(ev) {
	                    if (ev.target.tagName == "TD") {
	                        jQuery.tableDnD.dragObject = this;
	                        jQuery.tableDnD.currentTable = table;
	                        jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
	                        if (config.onDragStart) {
	                            // Call the onDrop method if there is one
	                            config.onDragStart(table, this);
	                        }
	                        return false;
	                    }
	                }).css("cursor", "move"); // Store the tableDnD object
				}
			});
		}
	},

	updateTables: function() {
		this.each(function() {
			// this is now bound to each matching table
			if (this.tableDnDConfig) {
				jQuery.tableDnD.makeDraggable(this);
			}
		})
	},

    /** Get the mouse coordinates from the event (allowing for browser differences) */
    mouseCoords: function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    },

    /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
    getMouseOffset: function(target, ev) {
        ev = ev || window.event;

        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    },

    /** Get the position of an element by going up the DOM tree and adding up all the offsets */
    getPosition: function(e){
        var left = 0;
        var top  = 0;
        /** Safari fix -- thanks to Luis Chato for this! */
        if (e.offsetHeight == 0) {
            /** Safari 2 doesn't correctly grab the offsetTop of a table row
            this is detailed here:
            http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
            the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
            note that firefox will return a text node as a first child, so designing a more thorough
            solution may need to take that into account, for now this seems to work in firefox, safari, ie */
            e = e.firstChild; // a table cell
        }
		if (e && e.offsetParent) {
        	while (e.offsetParent){
            	left += e.offsetLeft;
            	top  += e.offsetTop;
            	e     = e.offsetParent;
        	}

        	left += e.offsetLeft;
        	top  += e.offsetTop;
        }

        return {x:left, y:top};
    },

    mousemove: function(ev) {
        if (jQuery.tableDnD.dragObject == null) {
            return;
        }

        var dragObj = jQuery(jQuery.tableDnD.dragObject);
        var config = jQuery.tableDnD.currentTable.tableDnDConfig;
        var mousePos = jQuery.tableDnD.mouseCoords(ev);
        var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
        //auto scroll the window
	    var yOffset = window.pageYOffset;
	 	if (document.all) {
	        // Windows version
	        //yOffset=document.body.scrollTop;
	        if (typeof document.compatMode != 'undefined' &&
	             document.compatMode != 'BackCompat') {
	           yOffset = document.documentElement.scrollTop;
	        }
	        else if (typeof document.body != 'undefined') {
	           yOffset=document.body.scrollTop;
	        }

	    }
		    
		if (mousePos.y-yOffset < config.scrollAmount) {
	    	window.scrollBy(0, -config.scrollAmount);
	    } else {
            var windowHeight = window.innerHeight ? window.innerHeight
                    : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
            if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
                window.scrollBy(0, config.scrollAmount);
            }
        }


        if (y != jQuery.tableDnD.oldY) {
            // work out if we're going up or down...
            var movingDown = y > jQuery.tableDnD.oldY;
            // update the old value
            jQuery.tableDnD.oldY = y;
            // update the style to show we're dragging
			if (config.onDragClass) {
				dragObj.addClass(config.onDragClass);
			} else {
	            dragObj.css(config.onDragStyle);
			}
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
            if (currentRow) {
                // TODO worry about what happens when there are multiple TBODIES
                if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
                } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
                }
            }
        }

        return false;
    },

    /** We're only worried about the y position really, because we can only move rows up and down */
    findDropTargetRow: function(draggedRow, y) {
        var rows = jQuery.tableDnD.currentTable.rows;
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            var rowY    = this.getPosition(row).y;
            var rowHeight = parseInt(row.offsetHeight)/2;
            if (row.offsetHeight == 0) {
                rowY = this.getPosition(row.firstChild).y;
                rowHeight = parseInt(row.firstChild.offsetHeight)/2;
            }
            // Because we always have to insert before, we need to offset the height a bit
            if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                // that's the row we're over
				// If it's the same as the current row, ignore it
				if (row == draggedRow) {return null;}
                var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                if (config.onAllowDrop) {
                    if (config.onAllowDrop(draggedRow, row)) {
                        return row;
                    } else {
                        return null;
                    }
                } else {
					// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
                    var nodrop = jQuery(row).hasClass("nodrop");
                    if (! nodrop) {
                        return row;
                    } else {
                        return null;
                    }
                }
                return row;
            }
        }
        return null;
    },

    mouseup: function(e) {
        if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
            var droppedRow = jQuery.tableDnD.dragObject;
            var config = jQuery.tableDnD.currentTable.tableDnDConfig;
            // If we have a dragObject, then we need to release it,
            // The row will already have been moved to the right place so we just reset stuff
			if (config.onDragClass) {
	            jQuery(droppedRow).removeClass(config.onDragClass);
			} else {
	            jQuery(droppedRow).css(config.onDropStyle);
			}
            jQuery.tableDnD.dragObject   = null;
            if (config.onDrop) {
                // Call the onDrop method if there is one
                config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
            }
            jQuery.tableDnD.currentTable = null; // let go of the table too
        }
    },

    serialize: function() {
        if (jQuery.tableDnD.currentTable) {
            return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
        } else {
            return "Error: No Table id set, you need to set an id on your table and every row";
        }
    },

	serializeTable: function(table) {
        var result = "";
        var tableId = table.id;
        var rows = table.rows;
        for (var i=0; i<rows.length; i++) {
            if (result.length > 0) result += "&";
            var rowId = rows[i].id;
            if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
                rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
            }

            result += tableId + '[]=' + rowId;
        }
        return result;
	},

	serializeTables: function() {
        var result = "";
        this.each(function() {
			// this is now bound to each matching table
			result += jQuery.tableDnD.serializeTable(this);
		});
        return result;
    }

}

jQuery.fn.extend(
	{
		tableDnD : jQuery.tableDnD.build,
		tableDnDUpdate : jQuery.tableDnD.updateTables,
		tableDnDSerialize: jQuery.tableDnD.serializeTables
	}
);
/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */

(function($) {

 	var menu, shadow, content, hash, currentTarget;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '1px',
      margin: '0px',
      backgroundColor: '#fff',
      border: '1px solid #999',
      width: '100px'
    },
    itemStyle: {
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'default',
      padding: '3px',
      border: '1px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '1px solid #0a246a',
      backgroundColor: '#b6bdd2'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : true,
    onContextMenu: null,
    onShowMenu: null
 	};

  $.fn.contextMenu = function(id, options) {
    if (!menu) {                                      // Create singleton menu
      menu = $('<div id="jqContextMenu"></div>')
               .hide()
               .css({position:'absolute', zIndex:'500'})
               .appendTo('body')
               .bind('click', function(e) {
                 e.stopPropagation();
               });
    }
    if (!shadow) {
      shadow = $('<div></div>')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
    hash = hash || [];
    hash.push({
      id : id,
      menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
      itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
      itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
      bindings: options.bindings || {},
      shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
      onContextMenu: options.onContextMenu || defaults.onContextMenu,
      onShowMenu: options.onShowMenu || defaults.onShowMenu,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY
    });

    var index = hash.length - 1;
    $(this).bind('contextmenu', function(e) {
      // Check if onContextMenu() defined
      var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
	  currentTarget = e.target;
      if (bShowContext) {
		display(index, this, e );
		return false;
	  }
    });
    return this;
  };

  function display(index, trigger, e ) {
    var cur = hash[index];
    content = $('#'+cur.id).find('ul:first').clone(true);
    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
        $(this).css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

    // Send the content to the menu
    menu.html(content);

    // if there's an onShowMenu, run it now -- must run after content has been added
		// if you try to alter the content variable before the menu.html(), IE6 has issues
		// updating the content
    if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu);

    $.each(cur.bindings, function(id, func) {
      $('#'+id, menu).bind('click', function() {
        hide();
        func(trigger, currentTarget);
      });
    });

    menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
    if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
    $(document).one('click', hide);
  }

  function hide() {
    menu.hide();
    shadow.hide();
  }

  // Apply defaults
  $.contextMenu = {
    defaults : function(userDefaults) {
      $.each(userDefaults, function(i, val) {
        if (typeof val == 'object' && defaults[i]) {
          $.extend(defaults[i], val);
        }
        else defaults[i] = val;
      });
    }
  };

})(jQuery);

$(function() {
  $('div.contextMenu').hide();
});
/**







 */;
/*
Shameless port of a shameless port
@defunkt => @janl => @aq

See http://github.com/defunkt/mustache for more info.
*/

;(function($) {

/*
  mustache.js — Logic-less templates in JavaScript

  See http://mustache.github.com/ for more info.
*/

var Mustache = function() {
  var regexCache = {};
  var Renderer = function() {};

  Renderer.prototype = {
    otag: "{{",
    ctag: "}}",
    pragmas: {},
    buffer: [],
    pragmas_implemented: {
      "IMPLICIT-ITERATOR": true
    },
    context: {},

    render: function(template, context, partials, in_recursion) {
      // reset buffer & set context
      if(!in_recursion) {
        this.context = context;
        this.buffer = []; // TODO: make this non-lazy
      }

      // fail fast
      if(!this.includes("", template)) {
        if(in_recursion) {
          return template;
        } else {
          this.send(template);
          return;
        }
      }

      // get the pragmas together
      template = this.render_pragmas(template);

      // render the template
      var html = this.render_section(template, context, partials);

      // render_section did not find any sections, we still need to render the tags
      if (html === false) {
        html = this.render_tags(template, context, partials, in_recursion);
      }

      if (in_recursion) {
        return html;
      } else {
        this.sendLines(html);
      }
    },

    /*
      Sends parsed lines
    */
    send: function(line) {
      if(line !== "") {
        this.buffer.push(line);
      }
    },

    sendLines: function(text) {
      if (text) {
        var lines = text.split("\n");
        for (var i = 0; i < lines.length; i++) {
          this.send(lines[i]);
        }
      }
    },

    /*
      Looks for %PRAGMAS
    */
    render_pragmas: function(template) {
      // no pragmas
      if(!this.includes("%", template)) {
        return template;
      }

      var that = this;
      var regex = this.getCachedRegex("render_pragmas", function(otag, ctag) {
        return new RegExp(otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + ctag, "g");
      });

      return template.replace(regex, function(match, pragma, options) {
        if(!that.pragmas_implemented[pragma]) {
          throw({message:
            "This implementation of mustache doesn't understand the '" +
            pragma + "' pragma"});
        }
        that.pragmas[pragma] = {};
        if(options) {
          var opts = options.split("=");
          that.pragmas[pragma][opts[0]] = opts[1];
        }
        return "";
        // ignore unknown pragmas silently
      });
    },

    /*
      Tries to find a partial in the curent scope and render it
    */
    render_partial: function(name, context, partials) {
      name = this.trim(name);
      if(!partials || partials[name] === undefined) {
        throw({message: "unknown_partial '" + name + "'"});
      }
      if(typeof(context[name]) != "object") {
        return this.render(partials[name], context, partials, true);
      }
      return this.render(partials[name], context[name], partials, true);
    },

    /*
      Renders inverted (^) and normal (#) sections
    */
    render_section: function(template, context, partials) {
      if(!this.includes("#", template) && !this.includes("^", template)) {
        // did not render anything, there were no sections
        return false;
      }

      var that = this;

      var regex = this.getCachedRegex("render_section", function(otag, ctag) {
        // This regex matches _the first_ section ({{#foo}}{{/foo}}), and captures the remainder
        return new RegExp(
          "^([\\s\\S]*?)" +         // all the crap at the beginning that is not {{*}} ($1)

          otag +                    // {{
          "(\\^|\\#)\\s*(.+)\\s*" + //  #foo (# == $2, foo == $3)
          ctag +                    // }}

          "\n*([\\s\\S]*?)" +       // between the tag ($2). leading newlines are dropped

          otag +                    // {{
          "\\/\\s*\\3\\s*" +        //  /foo (backreference to the opening tag).
          ctag +                    // }}

          "\\s*([\\s\\S]*)$",       // everything else in the string ($4). leading whitespace is dropped.

        "g");
      });


      // for each {{#foo}}{{/foo}} section do...
      return template.replace(regex, function(match, before, type, name, content, after) {
        // before contains only tags, no sections
        var renderedBefore = before ? that.render_tags(before, context, partials, true) : "",

        // after may contain both sections and tags, so use full rendering function
            renderedAfter = after ? that.render(after, context, partials, true) : "",

        // will be computed below
            renderedContent,

            value = that.find(name, context);

        if (type === "^") { // inverted section
          if (!value || that.is_array(value) && value.length === 0) {
            // false or empty list, render it
            renderedContent = that.render(content, context, partials, true);
          } else {
            renderedContent = "";
          }
        } else if (type === "#") { // normal section
          if (that.is_array(value)) { // Enumerable, Let's loop!
            renderedContent = that.map(value, function(row) {
              return that.render(content, that.create_context(row), partials, true);
            }).join("");
          } else if (that.is_object(value)) { // Object, Use it as subcontext!
            renderedContent = that.render(content, that.create_context(value),
              partials, true);
          } else if (typeof value === "function") {
            // higher order section
            renderedContent = value.call(context, content, function(text) {
              return that.render(text, context, partials, true);
            });
          } else if (value) { // boolean section
            renderedContent = that.render(content, context, partials, true);
          } else {
            renderedContent = "";
          }
        }

        return renderedBefore + renderedContent + renderedAfter;
      });
    },

    /*
      Replace {{foo}} and friends with values from our view
    */
    render_tags: function(template, context, partials, in_recursion) {
      // tit for tat
      var that = this;



      var new_regex = function() {
        return that.getCachedRegex("render_tags", function(otag, ctag) {
          return new RegExp(otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + ctag + "+", "g");
        });
      };

      var regex = new_regex();
      var tag_replace_callback = function(match, operator, name) {
        switch(operator) {
        case "!": // ignore comments
          return "";
        case "=": // set new delimiters, rebuild the replace regexp
          that.set_delimiters(name);
          regex = new_regex();
          return "";
        case ">": // render partial
          return that.render_partial(name, context, partials);
        case "{": // the triple mustache is unescaped
          return that.find(name, context);
        default: // escape the value
          return that.escape(that.find(name, context));
        }
      };
      var lines = template.split("\n");
      for(var i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(regex, tag_replace_callback, this);
        if(!in_recursion) {
          this.send(lines[i]);
        }
      }

      if(in_recursion) {
        return lines.join("\n");
      }
    },

    set_delimiters: function(delimiters) {
      var dels = delimiters.split(" ");
      this.otag = this.escape_regex(dels[0]);
      this.ctag = this.escape_regex(dels[1]);
    },

    escape_regex: function(text) {
      // thank you Simon Willison
      if(!arguments.callee.sRE) {
        var specials = [
          '/', '.', '*', '+', '?', '|',
          '(', ')', '[', ']', '{', '}', '\\'
        ];
        arguments.callee.sRE = new RegExp(
          '(\\' + specials.join('|\\') + ')', 'g'
        );
      }
      return text.replace(arguments.callee.sRE, '\\$1');
    },

    /*
      find `name` in current `context`. That is find me a value
      from the view object
    */
    find: function(name, context) {
      name = this.trim(name);

      // Checks whether a value is thruthy or false or 0
      function is_kinda_truthy(bool) {
        return bool === false || bool === 0 || bool;
      }

      var value;

			// check for dot notation eg. foo.bar
			if(name.match(/([a-z_]+)\./ig)){
				value = is_kinda_truthy(this.walk_context(name, context));
			}
			else{
				if(is_kinda_truthy(context[name])) {
	        value = context[name];
	      } else if(is_kinda_truthy(this.context[name])) {
	        value = this.context[name];
	      }
			}

      if(typeof value === "function") {
        return value.apply(context);
      }
      if(value !== undefined) {
        return value;
      }
      // silently ignore unkown variables
      return "";
    },

		walk_context: function(name, context){
			var path = name.split('.');
			// if the var doesn't exist in current context, check the top level context
			var value_context = (context[path[0]] != undefined) ? context : this.context;
			var value = value_context[path.shift()];
			while(value != undefined && path.length > 0){
				value_context = value;
				value = value[path.shift()];
			}
			// if the value is a function, call it, binding the correct context
			if(typeof value === "function") {
        return value.apply(value_context);
      }
			return value;
		},

    // Utility methods

    /* includes tag */
    includes: function(needle, haystack) {
      return haystack.indexOf(this.otag + needle) != -1;
    },

    /*
      Does away with nasty characters
    */
    escape: function(s) {
      s = String(s === null ? "" : s);
      return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) {
        switch(s) {
        case "&": return "&amp;";
        case '"': return '&quot;';
        case "'": return '&#39;';
        case "<": return "&lt;";
        case ">": return "&gt;";
        default: return s;
        }
      });
    },

    // by @langalex, support for arrays of strings
    create_context: function(_context) {
      if(this.is_object(_context)) {
        return _context;
      } else {
        var iterator = ".";
        if(this.pragmas["IMPLICIT-ITERATOR"]) {
          iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
        }
        var ctx = {};
        ctx[iterator] = _context;
        return ctx;
      }
    },

    is_object: function(a) {
      return a && typeof a == "object";
    },

    is_array: function(a) {
      return Object.prototype.toString.call(a) === '[object Array]';
    },

    /*
      Gets rid of leading and trailing whitespace
    */
    trim: function(s) {
      return s.replace(/^\s*|\s*$/g, "");
    },

    /*
      Why, why, why? Because IE. Cry, cry cry.
    */
    map: function(array, fn) {
      if (typeof array.map == "function") {
        return array.map(fn);
      } else {
        var r = [];
        var l = array.length;
        for(var i = 0; i < l; i++) {
          r.push(fn(array[i]));
        }
        return r;
      }
    },

    getCachedRegex: function(name, generator) {
      var byOtag = regexCache[this.otag];
      if (!byOtag) {
        byOtag = regexCache[this.otag] = {};
      }

      var byCtag = byOtag[this.ctag];
      if (!byCtag) {
        byCtag = byOtag[this.ctag] = {};
      }

      var regex = byCtag[name];
      if (!regex) {
        regex = byCtag[name] = generator(this.otag, this.ctag);
      }

      return regex;
    }
  };

  return({
    name: "mustache.js",
    version: "0.4.0-dev",

    /*
      Turns a template and view into HTML
    */
    to_html: function(template, view, partials, send_fun) {
      var renderer = new Renderer();
      if(send_fun) {
        renderer.send = send_fun;
      }
      renderer.render(template, view || {}, partials);
      if(!send_fun) {
        return renderer.buffer.join("\n");
      }
    }
  });
}();
  $.mustache = function(template, view, partials) {
    return Mustache.to_html(template, view, partials);
  };

})(jQuery);
/*
	Watermark v3.1.3 (March 22, 2011) plugin for jQuery
	http://jquery-watermark.googlecode.com/
	Copyright (c) 2009-2011 Todd Northrop
	http://www.speednet.biz/
	Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function(a,h,y){var w="function",v="password",j="maxLength",n="type",b="",c=true,u="placeholder",i=false,t="watermark",g=t,f="watermarkClass",q="watermarkFocus",l="watermarkSubmit",o="watermarkMaxLength",e="watermarkPassword",d="watermarkText",k=/\r/g,s="input:data("+g+"),textarea:data("+g+")",m="input:text,input:password,input[type=search],input:not([type]),textarea",p=["Page_ClientValidate"],r=i,x=u in document.createElement("input");a.watermark=a.watermark||{version:"3.1.3",runOnce:c,options:{className:t,useNative:c,hideBeforeUnload:c},hide:function(b){a(b).filter(s).each(function(){a.watermark._hide(a(this))})},_hide:function(a,r){var p=a[0],q=(p.value||b).replace(k,b),l=a.data(d)||b,m=a.data(o)||0,i=a.data(f);if(l.length&&q==l){p.value=b;if(a.data(e))if((a.attr(n)||b)==="text"){var g=a.data(e)||[],c=a.parent()||[];if(g.length&&c.length){c[0].removeChild(a[0]);c[0].appendChild(g[0]);a=g}}if(m){a.attr(j,m);a.removeData(o)}if(r){a.attr("autocomplete","off");h.setTimeout(function(){a.select()},1)}}i&&a.removeClass(i)},show:function(b){a(b).filter(s).each(function(){a.watermark._show(a(this))})},_show:function(g){var p=g[0],u=(p.value||b).replace(k,b),h=g.data(d)||b,s=g.attr(n)||b,t=g.data(f);if((u.length==0||u==h)&&!g.data(q)){r=c;if(g.data(e))if(s===v){var m=g.data(e)||[],l=g.parent()||[];if(m.length&&l.length){l[0].removeChild(g[0]);l[0].appendChild(m[0]);g=m;g.attr(j,h.length);p=g[0]}}if(s==="text"||s==="search"){var i=g.attr(j)||0;if(i>0&&h.length>i){g.data(o,i);g.attr(j,h.length)}}t&&g.addClass(t);p.value=h}else a.watermark._hide(g)},hideAll:function(){if(r){a.watermark.hide(m);r=i}},showAll:function(){a.watermark.show(m)}};a.fn.watermark=a.fn.watermark||function(p,o){var t="string";if(!this.length)return this;var s=i,r=typeof p===t;if(r)p=p.replace(k,b);if(typeof o==="object"){s=typeof o.className===t;o=a.extend({},a.watermark.options,o)}else if(typeof o===t){s=c;o=a.extend({},a.watermark.options,{className:o})}else o=a.watermark.options;if(typeof o.useNative!==w)o.useNative=o.useNative?function(){return c}:function(){return i};return this.each(function(){var B="dragleave",A="dragenter",z=this,i=a(z);if(!i.is(m))return;if(i.data(g)){if(r||s){a.watermark._hide(i);r&&i.data(d,p);s&&i.data(f,o.className)}}else{if(x&&o.useNative.call(z,i)&&(i.attr("tagName")||b)!=="TEXTAREA"){r&&i.attr(u,p);return}i.data(d,r?p:b);i.data(f,o.className);i.data(g,1);if((i.attr(n)||b)===v){var C=i.wrap("<span>").parent(),t=a(C.html().replace(/type=["']?password["']?/i,'type="text"'));t.data(d,i.data(d));t.data(f,i.data(f));t.data(g,1);t.attr(j,p.length);t.focus(function(){a.watermark._hide(t,c)}).bind(A,function(){a.watermark._hide(t)}).bind("dragend",function(){h.setTimeout(function(){t.blur()},1)});i.blur(function(){a.watermark._show(i)}).bind(B,function(){a.watermark._show(i)});t.data(e,i);i.data(e,t)}else i.focus(function(){i.data(q,1);a.watermark._hide(i,c)}).blur(function(){i.data(q,0);a.watermark._show(i)}).bind(A,function(){a.watermark._hide(i)}).bind(B,function(){a.watermark._show(i)}).bind("dragend",function(){h.setTimeout(function(){a.watermark._show(i)},1)}).bind("drop",function(e){var c=i[0],a=e.originalEvent.dataTransfer.getData("Text");if((c.value||b).replace(k,b).replace(a,b)===i.data(d))c.value=a;i.focus()});if(z.form){var w=z.form,y=a(w);if(!y.data(l)){y.submit(a.watermark.hideAll);if(w.submit){y.data(l,w.submit);w.submit=function(c,b){return function(){var d=b.data(l);a.watermark.hideAll();if(d.apply)d.apply(c,Array.prototype.slice.call(arguments));else d()}}(w,y)}else{y.data(l,1);w.submit=function(b){return function(){a.watermark.hideAll();delete b.submit;b.submit()}}(w)}}}}a.watermark._show(i)})};if(a.watermark.runOnce){a.watermark.runOnce=i;a.extend(a.expr[":"],{data:function(c,d,b){return!!a.data(c,b[3])}});(function(c){a.fn.val=function(){var e=this;if(!e.length)return arguments.length?e:y;if(!arguments.length)if(e.data(g)){var f=(e[0].value||b).replace(k,b);return f===(e.data(d)||b)?b:f}else return c.apply(e,arguments);else{c.apply(e,arguments);a.watermark.show(e);return e}}})(a.fn.val);p.length&&a(function(){for(var b,c,d=p.length-1;d>=0;d--){b=p[d];c=h[b];if(typeof c===w)h[b]=function(b){return function(){a.watermark.hideAll();return b.apply(null,Array.prototype.slice.call(arguments))}}(c)}});a(h).bind("beforeunload",function(){a.watermark.options.hideBeforeUnload&&a.watermark.hideAll()})}})(jQuery,window);
// Instantiate the object
var I18n = I18n || {};

// Set default locale to english
I18n.defaultLocale = "en";

// Set default handling of translation fallbacks to false
I18n.fallbacks = true;

// Set default separator
I18n.defaultSeparator = ".";

// Set current locale to null
I18n.locale = null;

// Set the placeholder format. Accepts `{{placeholder}}` and `%{placeholder}`.
I18n.PLACEHOLDER = /(?:\{\{|%\{)(.*?)(?:\}\}?)/gm;

I18n.isValidNode = function(obj, node, undefined) {
    return obj[node] !== null && obj[node] !== undefined;
}

I18n.lookup = function(scope, options) {
  var options = options || {}
    , lookupInitialScope = scope
    , translations = this.prepareOptions(I18n.translations)
    , messages = translations[options.locale || I18n.currentLocale()]
    , options = this.prepareOptions(options)
    , currentScope
  ;

  if (!messages){
    return;
  }

  if (typeof(scope) == "object") {
    scope = scope.join(this.defaultSeparator);
  }

  if (options.scope) {
    scope = options.scope.toString() + this.defaultSeparator + scope;
  }

  scope = scope.split(this.defaultSeparator);

  while (scope.length > 0) {
    currentScope = scope.shift();
    messages = messages[currentScope];

    if (!messages) {
      if (I18n.fallbacks && !options.fallback) {
        messages = I18n.lookup(lookupInitialScope, this.prepareOptions({ locale: I18n.defaultLocale, fallback: true }, options));
      }
      break;
    }
  }

  if (!messages && this.isValidNode(options, "defaultValue")) {
    messages = options.defaultValue;
  }

  return messages;
};

// Merge serveral hash options, checking if value is set before
// overwriting any value. The precedence is from left to right.
//
//   I18n.prepareOptions({name: "John Doe"}, {name: "Mary Doe", role: "user"});
//   #=> {name: "John Doe", role: "user"}
//
I18n.prepareOptions = function() {
  var options = {}
    , opts
    , count = arguments.length
  ;

  for (var i = 0; i < count; i++) {
    opts = arguments[i];

    if (!opts) {
      continue;
    }

    for (var key in opts) {
      if (!this.isValidNode(options, key)) {
        options[key] = opts[key];
      }
    }
  }

  return options;
};

I18n.interpolate = function(message, options) {
  options = this.prepareOptions(options);
  var matches = message.match(this.PLACEHOLDER)
    , placeholder
    , value
    , name
  ;

  if (!matches) {
    return message;
  }

  for (var i = 0; placeholder = matches[i]; i++) {
    name = placeholder.replace(this.PLACEHOLDER, "$1");

    value = options[name];

    if (!this.isValidNode(options, name)) {
      value = "[missing " + placeholder + " value]";
    }

    regex = new RegExp(placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}"));
    message = message.replace(regex, value);
  }

  return message;
};

I18n.translate = function(scope, options) {
  options = this.prepareOptions(options);
  var translation = this.lookup(scope, options);

  try {
    if (typeof(translation) == "object") {
      if (typeof(options.count) == "number") {
        return this.pluralize(options.count, scope, options);
      } else {
        return translation;
      }
    } else {
      return this.interpolate(translation, options);
    }
  } catch(err) {
    return this.missingTranslation(scope);
  }
};

I18n.localize = function(scope, value) {
  switch (scope) {
    case "currency":
      return this.toCurrency(value);
    case "number":
      scope = this.lookup("number.format");
      return this.toNumber(value, scope);
    case "percentage":
      return this.toPercentage(value);
    default:
      if (scope.match(/^(date|time)/)) {
        return this.toTime(scope, value);
      } else {
        return value.toString();
      }
  }
};

I18n.parseDate = function(date) {
  var matches, convertedDate;

  // we have a date, so just return it.
  if (typeof(date) == "object") {
    return date;
  };

  // it matches the following formats:
  //   yyyy-mm-dd
  //   yyyy-mm-dd[ T]hh:mm::ss
  //   yyyy-mm-dd[ T]hh:mm::ss
  //   yyyy-mm-dd[ T]hh:mm::ssZ
  //   yyyy-mm-dd[ T]hh:mm::ss+0000
  //
  matches = date.toString().match(/(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2}))?(Z|\+0000)?/);

  if (matches) {
    for (var i = 1; i <= 6; i++) {
      matches[i] = parseInt(matches[i], 10) || 0;
    }

    // month starts on 0
    matches[2] -= 1;

    if (matches[7]) {
      convertedDate = new Date(Date.UTC(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6]));
    } else {
      convertedDate = new Date(matches[1], matches[2], matches[3], matches[4], matches[5], matches[6]);
    }
  } else if (typeof(date) == "number") {
    // UNIX timestamp
    convertedDate = new Date();
    convertedDate.setTime(date);
  } else if (date.match(/\d+ \d+:\d+:\d+ [+-]\d+ \d+/)) {
    // a valid javascript format with timezone info
    convertedDate = new Date();
    convertedDate.setTime(Date.parse(date))
  } else {
    // an arbitrary javascript string
    convertedDate = new Date();
    convertedDate.setTime(Date.parse(date));
  }

  return convertedDate;
};

I18n.toTime = function(scope, d) {
  var date = this.parseDate(d)
    , format = this.lookup(scope)
  ;

  if (date.toString().match(/invalid/i)) {
    return date.toString();
  }

  if (!format) {
    return date.toString();
  }

  return this.strftime(date, format);
};

I18n.strftime = function(date, format) {
  var options = this.lookup("date");

  if (!options) {
    return date.toString();
  }

  options.meridian = options.meridian || ["AM", "PM"];

  var weekDay = date.getDay()
    , day = date.getDate()
    , year = date.getFullYear()
    , month = date.getMonth() + 1
    , hour = date.getHours()
    , hour12 = hour
    , meridian = hour > 11 ? 1 : 0
    , secs = date.getSeconds()
    , mins = date.getMinutes()
    , offset = date.getTimezoneOffset()
    , absOffsetHours = Math.floor(Math.abs(offset / 60))
    , absOffsetMinutes = Math.abs(offset) - (absOffsetHours * 60)
    , timezoneoffset = (offset > 0 ? "-" : "+") + (absOffsetHours.toString().length < 2 ? "0" + absOffsetHours : absOffsetHours) + (absOffsetMinutes.toString().length < 2 ? "0" + absOffsetMinutes : absOffsetMinutes)
  ;

  if (hour12 > 12) {
    hour12 = hour12 - 12;
  } else if (hour12 === 0) {
    hour12 = 12;
  }

  var padding = function(n) {
    var s = "0" + n.toString();
    return s.substr(s.length - 2);
  };

  var f = format;
  f = f.replace("%a", options.abbr_day_names[weekDay]);
  f = f.replace("%A", options.day_names[weekDay]);
  f = f.replace("%b", options.abbr_month_names[month]);
  f = f.replace("%B", options.month_names[month]);
  f = f.replace("%d", padding(day));
  f = f.replace("%e", day);
  f = f.replace("%-d", day);
  f = f.replace("%H", padding(hour));
  f = f.replace("%-H", hour);
  f = f.replace("%I", padding(hour12));
  f = f.replace("%-I", hour12);
  f = f.replace("%m", padding(month));
  f = f.replace("%-m", month);
  f = f.replace("%M", padding(mins));
  f = f.replace("%-M", mins);
  f = f.replace("%p", options.meridian[meridian]);
  f = f.replace("%S", padding(secs));
  f = f.replace("%-S", secs);
  f = f.replace("%w", weekDay);
  f = f.replace("%y", padding(year));
  f = f.replace("%-y", padding(year).replace(/^0+/, ""));
  f = f.replace("%Y", year);
  f = f.replace("%z", timezoneoffset);

  return f;
};

I18n.toNumber = function(number, options) {
  options = this.prepareOptions(
    options,
    this.lookup("number.format"),
    {precision: 3, separator: ".", delimiter: ",", strip_insignificant_zeros: false}
  );

  var negative = number < 0
    , string = Math.abs(number).toFixed(options.precision).toString()
    , parts = string.split(".")
    , precision
    , buffer = []
    , formattedNumber
  ;

  number = parts[0];
  precision = parts[1];

  while (number.length > 0) {
    buffer.unshift(number.substr(Math.max(0, number.length - 3), 3));
    number = number.substr(0, number.length -3);
  }

  formattedNumber = buffer.join(options.delimiter);

  if (options.precision > 0) {
    formattedNumber += options.separator + parts[1];
  }

  if (negative) {
    formattedNumber = "-" + formattedNumber;
  }

  if (options.strip_insignificant_zeros) {
    var regex = {
        separator: new RegExp(options.separator.replace(/\./, "\\.") + "$")
      , zeros: /0+$/
    };

    formattedNumber = formattedNumber
      .replace(regex.zeros, "")
      .replace(regex.separator, "")
    ;
  }

  return formattedNumber;
};

I18n.toCurrency = function(number, options) {
  options = this.prepareOptions(
    options,
    this.lookup("number.currency.format"),
    this.lookup("number.format"),
    {unit: "$", precision: 2, format: "%u%n", delimiter: ",", separator: "."}
  );

  number = this.toNumber(number, options);
  number = options.format
    .replace("%u", options.unit)
    .replace("%n", number)
  ;

  return number;
};

I18n.toHumanSize = function(number, options) {
  var kb = 1024
    , size = number
    , iterations = 0
    , unit
    , precision
  ;

  while (size >= kb && iterations < 4) {
    size = size / kb;
    iterations += 1;
  }

  if (iterations === 0) {
    unit = this.t("number.human.storage_units.units.byte", {count: size});
    precision = 0;
  } else {
    unit = this.t("number.human.storage_units.units." + [null, "kb", "mb", "gb", "tb"][iterations]);
    precision = (size - Math.floor(size) === 0) ? 0 : 1;
  }

  options = this.prepareOptions(
    options,
    {precision: precision, format: "%n%u", delimiter: ""}
  );

  number = this.toNumber(size, options);
  number = options.format
    .replace("%u", unit)
    .replace("%n", number)
  ;

  return number;
};

I18n.toPercentage = function(number, options) {
  options = this.prepareOptions(
    options,
    this.lookup("number.percentage.format"),
    this.lookup("number.format"),
    {precision: 3, separator: ".", delimiter: ""}
  );

  number = this.toNumber(number, options);
  return number + "%";
};

I18n.pluralize = function(count, scope, options) {
  var translation;

  try {
    translation = this.lookup(scope, options);
  } catch (error) {}

  if (!translation) {
    return this.missingTranslation(scope);
  }

  var message;
  options = this.prepareOptions(options);
  options.count = count.toString();

  switch(Math.abs(count)) {
    case 0:
      message = this.isValidNode(translation, "zero") ? translation.zero :
                this.isValidNode(translation, "none") ? translation.none :
                this.isValidNode(translation, "other") ? translation.other :
                this.missingTranslation(scope, "zero");
      break;
    case 1:
      message = this.isValidNode(translation, "one") ? translation.one : this.missingTranslation(scope, "one");
      break;
    default:
      message = this.isValidNode(translation, "other") ? translation.other : this.missingTranslation(scope, "other");
  }

  return this.interpolate(message, options);
};

I18n.missingTranslation = function() {
  var message = '[missing "' + this.currentLocale()
    , count = arguments.length
  ;

  for (var i = 0; i < count; i++) {
    message += "." + arguments[i];
  }

  message += '" translation]';

  return message;
};

I18n.currentLocale = function() {
  return (I18n.locale || I18n.defaultLocale);
};

// shortcuts
I18n.t = I18n.translate;
I18n.l = I18n.localize;
I18n.p = I18n.pluralize;
;(function($) {
  /**
   * An abstraction around data grids.
   *
   * It accepts all the options that jqGrid accepts, plus the following:
   *
   *   date_search:             "COLUMN" | {
   *                                        column: "COLUMN",
   *                                        defaultTo: "DEFAULT_DATE_MAX",
   *                                        defaultFrom: "DEFAULT_DATE_MIN"
   *                                      }
   *
   *                            This option adds a calendar search button
   *                            that will search on the specified COLUMN.
   *                            Specifying the second version allows you
   *                            to choose what value appears in the
   *                            search box by default. If you do not
   *                            specify they will default to 'From:' and
   *                            'To:'.
   *
   *   advanced_search:         "true"|"hidden"|"disabled"
   *
   *                            Sets the visibility of the search
   *                            container. Defaults to "hidden".
   *                            "disabled" prevents the search
   *                            container from showing up at all.
   *
   *   filter:                  [{
   *                               field:  COLUMN,
   *                               label:  LABEL,
   *                               type:   FILTER_TYPE,
   *                               hidden: true|false
   *                              },
   *                              …]
   *
   *                            Create a select filter for each of the
   *                            provided columns.
   *
   *                            FILTER_TYPE may be one of:
   *                               Simple        -- Simple input
   *                               CalendarRange -- Min/Max datepicker
   *                               TypeAhead     -- Autocomplete box
   *                               Select        -- Select dropdown
   *
   *   columns:                 [<list of column defs>]
   *
   *                            An Array of column definitions.
   *                            Accepts jqgrid fields, as well as column footer options (see below)
   *
   * All options are forwarded to the underlying grid object.
   *
   * EXAMPLE:
   *
   *     $("#document_gridz").backstopGrid({
   *       caption:     "Documents",
   *       sortname:    "doc_date",
   *       date_search: "doc_date",
   *
   *       advanced_search: "hidden",
   *       filter:          { "Title": "title" },
   *
   *       url:      "<%= request_entity_documents_json_path %>?q=1",
   *
   *       columns:  [
   *         { field: "id",       label: "id", hidden: true },
   *         { field: "doc_date", label: "Document Date", width: 20 },
   *         { field: "title",    label: "Title", width: 20 },
   *         { field: "associated_with", label: "Associated With",
   *           width: 60, search: false, sortable: false }
   *       ]
   *     });
   *
   * COLUMN FOOTER OPTIONS:
   *
   * Individual columns may specify a calculated value or static string to appear in the footer row.
   * Note that footer rows appear on every page, and only use values from the current page for calculations.
   * Footer values may be specified in the column definition using ONE of the following mutually-exclusive ways:
   *
   * column_footer: a function for calculating the footer cell value for this column,
   *                accepts array of column values as input
   *
   * OR
   *
   * column_footer_fixed: a static cell value for this column
   *
   * OR
   *
   * column_footer_total: calculate the sum of all column values in the format specified here
   *                      ('dollars' or simply true for standard decimals)
   *   column_footer_total_pre: a function for deriving a summable number from the column value,
   *                            accepts column value, defaults based on column_footer_total value
   *   column_footer_total_post: a function for formatting the calculated total,
   *                             accepts column total, defaults based on column_footer_total value
   *   column_footer_total_precision: round to this number of decimal places (default is not to round)
   *
   * COLUMN FOOTER STYLING:
   *
   * In order to override the defaults that jqGrid gives you for the footer row, you need to target:
   * .ui-jqgrid tr.footrow td{} (e.g. .ui-jqgrid tr.footrow td{ border: none; })
   *
   * EVENTS:
   *
   * A Backstop.Grid will fire the following events:
   *
   *   backstopgrid.loaded :
   *       Fired when the grid has loaded new data.  Callback handlers
   *       are passed an Event object and the JSON data that was loaded.
   *
   *   backstopgrid.initialized :
   *       Fired after the grid has been constructed but before the data
   *       has been loaded.
   *
   *   backstopgrid.cellselected :
   *       Fired whenever a table cell is selected.  Callback handlers
   *       are passed an Event object, the rowId, the column index
   *       (icol), and the contents of the selected cell.
   *
   *
   * A Backstop.Grid will respond to the following events:
   *
   *   reload :
   *       If the widget (the element the Grid is attached to) receives a
   *       'reload' event, the Grid will reload its data from the server.
   *
   */
  var Grid = {
    jqGridOptions: function() {
      var backstopGridId = this.bindings[0].id;
      var defaults = {
        ajaxGridOptions: {
          error: function( xhr, textStatus, errorThrown ) {
            if ( xhr.responseText === '' && xhr.status === 0 ) {
              // Leavng a page before loading is finished produces an empty error for some reason
              return;
            } try {
              var json = $.parseJSON( xhr.responseText );
              if ( !Backstop.isnull( json ) && json.redirect_to ) {
                window.location = json.redirect_to;
              } else {
                $('#load_'+backstopGridId+'_grid').html( '<p>An Error has occurred.</p><p>' +
                  json.error + '</p>'
                );
              }
            } catch ( e ) {
              $('#load_'+backstopGridId+'_grid').html( 'An Unknown Error has occurred. Data could not be loaded.' );
            }
          }
        },

        advanced_search: 'hidden',
        autowidth: true,
        cellEdit: false,
        cellurl: '',
        datatype: 'json',
        editurl: '',
        gridview: false,
        height: '100%',
        imgpath: '/images/themes/lightness/images',
        jsonReader: {
          root: 'rows',
          page: 'page',
          total: 'total',
          repeatitems: false,
          userdata: 'rows',
          id: 'id'
        },
        loadComplete: function( data ) {},
        multiselect: false,
        rowList: [10, 25, 50, 100],
        rowNum: 25,
        rownumbers: false,
        scrollrows: true,
        sortorder: 'DESC',
        subGrid: false,
        toppager: false,
        viewrecords: true
      };

      if (typeof this.options.ajaxGridOptions != 'undefined') {
        this.options.ajaxGridOptions = $.extend( defaults.ajaxGridOptions, this.options.ajaxGridOptions)
      }
      return $.extend( defaults, this.options );
    },

    // Widget Constructor
    _init: function() {
      var self = this;
      var dataSource = this.element.attr( 'data-src' );
      var title = this.element.attr( 'title' );

      if ( typeof dataSource === 'undefined' || dataSource === null ) {
        dataSource = '';
      }

      if ( typeof title === 'undefined' || title === null ) {
        title = '';
      }

      var o = $.extend( { url: dataSource, caption: title }, this.options );
      $.extend( o, this._parseColumns( this.options.columns ) );
      this.options = o;

      if ( typeof this.options.loadComplete == 'undefined' ) {
        this.options.loadComplete = function( data ) {
          self._trigger( '.loaded', null, data );
        };
      }

      if ( typeof this.options.onCellSelect == 'undefined' ) {
        this.options.onCellSelect = function( rowId, iCol, cellContent ) {
          self._trigger( '.cellselected', 0 , arguments );
        };
      }

      this.table = $('<table/>').addClass( 'scroll' ).
        attr( 'id', this.element.attr('id') + '_grid' );
      this.pager = $('<div/>').attr( 'id', this.pagerId() );
      this.options.pager = '#' + this.pagerId();

      if ( Backstop.isnull( this.options.url.match(/\?/) ) ) {
        this.options.url = this.options.url + '?q=1';
      }

      this.element.append( this.table );
      this.element.append( this.pager );

      this.element.bind( 'reload', function(e) { self.reload(); } );

      this._setup_jqgrid();

      this._addFilters( this.options.filter || {}, this.options.advanced_search );

      this._trigger( '.initialized', 0, self );
    },

    _create:  function() {},
    _destroy: function() {},

    gridId: function() {
      return this.table.attr('id');
    },

    pagerId: function() {
      var id = this.element.attr( 'id' );
      return id + '_pager';
    },

    /**
     * The HTML table element that the jqGrid is attached to.
     */
    gridTable: function() {
      return this.table;
    },

    /**
     * Set or get the current search scope by key.
     *
     * Examples:
     *
     *   Get the 'associated_with' search scope:
     *     $('#grid').backstopGrid( "searchScope", "associated_with" );
     *
     *   Set the 'associated_with' scope to 'foo':
     *     $('#grid').backstopGrid(
     *       "searchScope", "associated_with", "foo"
     *     );
     *
     */
    searchScope: function( key, value ) {
      if ( Backstop.isnull( key ) ) { throw 'Argument Error: No scope key provided.'; }

      if ( typeof value === 'undefined' ) {
        var match = this._regex(key).exec( this._gridUrl() );

        if ( typeof match === 'undefined' || match === null ) {
          return null;
        }
        var current_value = match[1];
        return current_value;
      }

      this._removeSearchScope( key );
      if ( value === null || value === '' ) {
        return this.element;
      }

      var url = this._gridUrl().replace( /&$/, '' ) +
        '&search_scope[' + key + ']=' + encodeURIComponent( value );

      this._gridUrl( url );

      return this.element;
    },

    selectedRowIds: function () {
      return this.table.getGridParam( 'selarrrow' );
    },

    selectedRows: function () {
      var table = this.table;
      var ids   = this.selectedRowIds();

      return $.map( ids, function ( id ) {
        var row  = table.jqGrid( 'getInd', id ) - 1;
        var data = table.getGridParam( 'userData' )[row];

        for (var attr in data) {
          var matches = /^(.*)_json$/.exec( attr );
          if ( matches ) {
            var json_attr = matches[0];
            var wonky_attr = matches[1];

            data[ wonky_attr ] = data[ json_attr ];
          }
        }

        return data;
      });
    },

    createFilter: function( type, options ) {
      var filters = this._currentFilters();
      if ( Backstop.isnull( options ) ) { return filters; }
      if ( Backstop.isnull( type ) )    { type = 'TypeAheadFilter'; }

      var column = options.field;
      if ( !Backstop.isnull( column ) && !filters[column] ) {
        filters[column] = new Backstop.Grid[type]( this.element, options);

        return filters[column];
      }

      return filters;
    },

    /**
     * Add a filter UI element for the given column.
     *
     * In order for some filters to work, the server must return JSON
     * data including the available values to filter on.  The data
     * should be in the JSON response in an attribute of the same name
     * as the filter column.
     *
     * If called with no argument, it returns the current list of
     * filters applied to this Grid.  Otherwise, it returns the newly
     * created filter.
     *
     */
    filter: function ( column, label ) {
      return this.createFilter( 'TypeAheadFilter', {
        field: column, label: label, advanced: true
      });
    },

    /**
     * Add a select filter UI element for the given column.
     *
     * This functions the same as #filter above, except that it generates
     * a select element instead of a type-ahead input.
     *
     * If called with no argument, it returns the current list of
     * filters applied to this Grid.
     *
     */
    select: function( column, label ) {
      return this.createFilter( 'SelectFilter', {
        field: column, label: label
      });
    },

    /**
     * Cause the grid to reload its data from the server.
     *
     * Easier, probably, to just trigger a 'reload' event on the Grid.
     *
     */
    reload: function() {
      this.gridTable().setGridParam({ page: 1 });
      return this.gridTable().trigger( 'reloadGrid' );
    },

    _currentFilters: function () {
      if ( Backstop.isnull( this.__current_filters ) ) { this.__current_filters = {}; }
      return this.__current_filters;
    },

    _setup_jqgrid: function() {
      var grid = this.table.jqGrid( this.jqGridOptions() );

      grid.navGrid(
        this.options.pager,
        { edit: false, add: false, del: false, search: false, refresh: true }
      );

      if ((this.options.search !== false)) {
        grid.navButtonAdd(
          this.options.pager,
          {
            caption: '',
            title: 'Toggle Search Toolbar',
            buttonicon: 'ui-icon-search',
            onClickButton: function() { grid[0].toggleToolbar(); }
          }
        );
      }

      grid.filterToolbar( this.options.beforeSearchAction || {} );

      if ( !this.options.showSearchByDefault ) {
        grid[0].toggleToolbar();
      }

      this.searchPanel = $(this.options.pager + '_left table').clone(true).attr( 'style', '' );
      this.element.find('.ui-jqgrid-titlebar-close').before(this.searchPanel);

      if (!Backstop.isnull(this.options.date_search)) {
        this._setup_calendar_search();
      }
    },

    _addFilters: function ( filters, advanced_search ) {
      var self = this;
      $.each( filters, function ( index, options ) {
        var type = options.type + 'Filter';
        self.createFilter( type, options );
      });

      var form = Backstop.form_for( this.element );
      form.submit( function ( event ) {
        event.preventDefault();
        $.each( self.filter(), function ( i, filter ) {
          filter.commit();
        });

        self.element.trigger( 'reload' );
      });

      form.find( '.buttons input.clear' ).click( function ( event ) {
        $.each( self.filter(), function ( i, filter ) {
          filter.reset();
        });
      });

      form.hide();
      form.find( '.advanced' ).hide();

      this.element.bind( 'backstopgrid.loaded', function ( event ) {
        self._applyToggleTo( form, advanced_search );
      });
    },

    _applyToggleTo: function ( form, advanced_search ) {
      var $form = $(form);
      var link  = $('a#toggle-' + $form.attr('id'));
      var form_has_advanced_fields =
          $form.find( 'fieldset.advanced input[type!="submit"]' ).size() > 0;
      var form_has_fields =
          $form.find( ':input[type!="submit"]' ).size() > 0;

      if ( form_has_fields ) {
        $(form).show();
      }

      if ( (parseInt(link.size()) === 0 || isNaN(parseInt(link.size()))) &&
          form_has_advanced_fields &&
          !(advanced_search && advanced_search === 'disabled' )) {

        link = $( '<a href="#"></a>' ).
            text(  I18n.t('attachables.show_advanced')).
            addClass( 'show-advanced' ).
            attr( 'id', 'toggle-' + $form.attr('id') ).
            click( function (event) {
              event.preventDefault();
              toggle_advanced();
            });

        var toggle_advanced = function () {
          $form.find('fieldset.advanced').toggle();

          if ( $form.find('fieldset.advanced').is( ':visible' ) ) {
            link.text(  I18n.t('attachables.hide_advanced') ).addClass( 'hide-advanced' );
          } else {
            link.text(  I18n.t('attachables.show_advanced') ).removeClass( 'hide-advanced' );
          }
        };

        if (advanced_search && advanced_search === 'true') {
          toggle_advanced();
        }

        $form.before( link );
      }

      return link;
    },

    _setup_calendar_search: function() {
      var search_column = this.options.date_search.column;
      var defaultFrom;
      var defaultTo;
      var searchByDate = I18n.t('attachables.search_by_date');

      if (!search_column) {
        search_column = this.options.date_search;
      } else {
        defaultFrom = this.options.date_search.defaultFrom;
        defaultTo = this.options.date_search.defaultTo;
      }

      this.createFilter( 'CalendarRangeFilter', {
        field: search_column,
        label: searchByDate,
        advanced: true,
        defaultFrom: defaultFrom,
        defaultTo: defaultTo
      });
    },

    _regex: function( key ) {
      return new RegExp( 'search_scope\\[' +
                         key.replace( /([\[\]])/g, '\\$1' ) +
                         '\\]=([^&]*)' );
    },

    _removeSearchScope: function( key ) {
      this._gridUrl( this._gridUrl().replace( this._regex(key), '' ) );
    },

    _gridUrl: function( new_url ) {
      if ( typeof new_url === 'undefined' ) {
        return this.gridTable().getGridParam( 'url' );
      }

      this.gridTable().jqGrid( 'setGridParam', { url: new_url } );

      return new_url;
    },

    _parseColumns: function( columns ) {
      var parsed = {};

      if ( columns === undefined ) {
        return parsed;
      }

      parsed.colNames = $.map( columns, function( column ) {
        return column.label;
      });

      parsed.colModel = columns.map( function( column ) {
        return $.extend( column, {
          name:  column.field,
          index: (column.index || column.field)
        });
      });

      var formatMoney = function(value, decimals, point, comma, currency, comma_every) {
        decimals = decimals === undefined ? 2 : decimals;
        point = point || '.';
        comma = comma || ',';
        currency = currency || '$';
        comma_every = comma_every || 3;
        var negative = value < 0 ? '-' : '';
        value = Math.abs(Number(value) || 0).toFixed(decimals);
        var int_part = String(parseInt(value));
        comma_every = (int_part.length) > comma_every ? int_part.length % comma_every : 0;

        var out = currency + negative;
        out = out + (comma_every ? int_part.substr(0, comma_every) + comma : '');
        out = out + int_part.substr(comma_every).replace(/(\d{3})(?=\d)/g, '$1' + comma);
        out = out + (decimals ? point + Math.abs(value - int_part).toFixed(decimals).slice(2) : '');
        return out;
      };

      var numberOnly = function( value ) {
        if (value === '-') {
          return 0;
        } else {
          return parseFloat(value.replace(/[^0-9.-]/g, ''));
        }
      };

      var echoResult = function( result ) {
        return result;
      };

      var footers = columns.filter(function( column ) {
        if (column) {
          if ( column.column_footer_fixed ) {
            column.column_footer = function() { return column.column_footer_fixed; };
            return column.column_footer;
          } else if ( column.column_footer_total ) {
            if (!column.column_footer_total_pre) {
              column.column_footer_total_pre = numberOnly;
            }
            if ( !column.column_footer_total_post ) {
              if ( column.column_footer_total == 'dollars' ) {
                if (column.column_footer_total_precision !== undefined) {
                  column.column_footer_total_post = function (value) {
                    return formatMoney( value, column.column_footer_total_precision );
                  };
                } else {
                  column.column_footer_total_post = formatMoney;
                }
              } else {
                if (column.column_footer_total_precision !== undefined) {
                  column.column_footer_total_post = function (value) {
                    return parseFloat(value).toFixed( column.column_footer_total_precision );
                  };
                } else {
                  column.column_footer_total_post = echoResult;
                }
              }
            }
            column.column_footer = function( values ) {
              return column.column_footer_total_post(
                values.map(
                  column.column_footer_total_pre
                ).reduce(
                  function (subtotal, value) {
                    return subtotal + value;
                  }, 0
                )
              );
            };
          }
          return column.column_footer;
        } else {
          return false;
        }
      });
      var this_grid = this;
      if (footers.length > 0) {
        parsed.footerrow = true;
        parsed.gridComplete = function() {
          footers.forEach(function ( column ) {
            var footerdata = {};
            footerdata[column.field] = column.column_footer(
              this_grid.gridTable().jqGrid('getCol', column.field, false)
            );
            this_grid.gridTable().jqGrid('footerData', 'set', footerdata);
          });
        };
      }

      return parsed;
    }
  };

  Backstop.Grid = Backstop.Grid ? Backstop.Grid : Grid;

  $.widget( 'bs.backstopGrid', Backstop.Grid );
  $.extend( $.bs.backstopGrid, {
    getter: ['gridTable', 'searchScope', 'selectedRows', 'selectedRowIds']
  });

  $(window).resize( function() {
    grid = $('.ui-jqgrid-btable:visible');
    grid.each(function(index) {
      gridId = $(this).attr('id');
      gridParentWidth = $('#gbox_' + gridId).parent().width();
      $('#' + gridId).setGridWidth(gridParentWidth);
    });
  });
}(window.jQuery));
;(function($) {
  Backstop.form_for = function (grid) {
    function createForm (id) {
      var template = '<form id="{{id}}" class="grid-filter">' +
        '<fieldset class="standard"></fieldset>' +
        '<fieldset class="advanced">' +
        '<fieldset class="buttons">' +
        '<input type="submit" class="filtersubmit submit applySubmit" />' +
        '<input type="submit" class="filtersubmit clear clearSubmit" />' +
        '</fieldset>' +
        '</fieldset>' +
        '</form>';

      var form  = $.mustache( template, { id: id } );
      return $(form);
    }

    $('input.applySubmit').val( I18n.t('attachables.apply') );
    $('input.clearSubmit').val( I18n.t('attachables.clear') );

    var $grid   = $(grid);
    var form_id = $grid.attr( 'id' ) + '-form';
    var $form   = $('form#' + form_id);

    if ($form.size() === 0) {
      $form = createForm( form_id );
      $grid.before( $form );
    }

    return $form;
  };
}(jQuery));
;(function ($) {
  Filter = function() {};
  Backstop.Grid.Filter = Filter;

  /**
   * Filter type for Backstop.Grid
   *
   * Extend this type to implement search filters.  Extend with the
   * helper +defineFilterType+.  Filters must implement the methods
   * +_createElements+ and +_updateFilterData+.
   *
   */
  Filter.prototype = {
    init: function( gridElement, options ) {
      var self     = this;
      this.options = options;
      this.grid    = $(gridElement);
      this.gridId  = this.grid.attr('id');

      if ( this.grid.size() === 0 ) {
        throw 'Attempted to filter a non-existent grid: ' + gridElement;
      }

      this.hidden     = options.hidden || false;
      this.columnName = options.field;
      this.labelText  = options.label;
      this.excluded_tags = options.excluded_tags;
      this.filterId   = this.columnName + '_' + this.grid.attr('id');
      this.defaultFrom   = options.defaultFrom;
      this.defaultTo   = options.defaultTo;

      this.grid.bind( 'backstopgrid.loaded', function( event, data ) {
        self._updateFilterData( this, data );
      });

      this.element = this._createElements(
        this.columnName, this.filterId, this.labelText, this.defaultFrom, this.defaultTo
      );

      return this;
    },

    commit: function () {
      var self   = this;
      var inputs = this.inputs();
      $.each( inputs, function ( i, input ) {
        var value = $(input).val();
        var name  = $(input).attr( 'name' );

        if ( typeof name !== 'undefined' ) {
          self.grid.backstopGrid( 'searchScope', name, value );
        }
      });
    },

    reset: function () {
      var inputs = this.inputs();
      $.each( inputs, function ( i, input ) { $(input).val(''); });
    },

    form: function() { return Backstop.form_for( this.grid ); },

    inputs: function () {
      return this.element.find( ':input[type!="submit"][type!="button"]' );
    },

    addToForm: function ( element, advanced ) {
      var form = this.form();
      if ( advanced ) {
        form.find( 'fieldset.advanced .buttons' ).before( element );
      } else {
        form.find( 'fieldset.standard' ).append( element );
      }
    },

    // ``Abstract'' properties:
    _createElements:    function() { throw new Error( 'undefined' ); },
    _updateFilterData: function() { throw new Error( 'undefined' ); }
  };

  Filter.defineFilterType = function( proto ) {
    function extendType ( Type, withPrototype ) {
      var subTypeConstructor = function () {
        Type.prototype.init.apply( this, arguments );
      };

      subTypeConstructor.prototype = $.extend( new Type(), withPrototype );
      subTypeConstructor.prototype.constructor = subTypeConstructor;

      return subTypeConstructor;
    }
    return extendType( Filter, proto );
  };
}(jQuery));
;(function($) {
  Backstop.Grid.CalendarRangeFilter = Backstop.Grid.Filter.defineFilterType({
    template:
    '<dl id="date_search_{{id}}" class="date-filter">' +
        '  <dt>{{label}}</dt>' +
        '  <dd><input name="{{column}}_min" class="filter date min"/></dd>' +
        '  <dd><input name="{{column}}_max" class="filter date max"/></dd>' +
        '  <dd><input type="submit" class="filtersubmit submit date-submit" /></dd>' +
        '</dl>',

    _createElements: function ( column, id, label, defaultFrom, defaultTo ) {
      var self = this;
      var view = {
        column: column,
        id: id,
        label: label
      };

      var fieldset = $( $.mustache( this.template, view ) );
      this.addToForm( fieldset, this.options.advanced  );

      fieldset.find( 'input.date' ).datepicker({
        dateFormat:  'yy/mm/dd',
        changeYear:  true,
        changeMonth: true
      }).addClass( 'magnifying-glass' );
      var fromText = I18n.t('attachables.from');
      var toText = I18n.t('attachables.to');
      var from = defaultFrom ? defaultFrom : fromText;
      var to = defaultTo ? defaultTo : toText;
      fieldset.find( 'input.date.min' ).watermark( from );
      fieldset.find( 'input.date.max' ).watermark( to );

      fieldset.find( '.clear' ).click( function (event) {
        fieldset.find( 'input.date' ).val('');
      });

      $('input.date-submit').val( I18n.t('attachables.set') );

      return fieldset;
    },

    _updateFilterData: function () { }
  });

}(jQuery));
;(function($) {
  var EditController = function ( grid, element ) {
    this.grid = grid;
    this.element = $(element);
    $(element).click( $.proxy( this.edit, this ) );
  };

  Backstop.Grid.EditController = EditController;

  EditController.prototype = {
    edit: function () {
      var ids  = this.grid.backstopGrid( 'selectedRowIds' );
      if ( ids.length === 0 ) { return undefined; }

      this.confirm( ids );
    },

    doDelete: function( ids ) {
      this.element.attr( 'disabled', true );
      this.grid.bind( 'backstopgrid.loaded', $.proxy( this.editComplete, this ) );

      $.ajax({
        type: 'DELETE',
        data: { ids: ids },
        url: this.element.data( 'href' ),
        context: this,

        error: function( jqXHR, textStatus, errorThrown ) {
          var error;
          try {
            error = jQuery.parseJSON( jqXHR.responseText ).messages;
          } catch ( e ) {
            error = textStatus;
          }

          var message = $('<p>' + (
            error || 'There was a problem deleting your documents.'
          ) + '</p>');

          $('#flash-div .error').html( message );
          message.fadeIn( 'fast' );
        },

        complete: function() {
          this.grid.trigger( 'reload' );
        }
      });
    },

    editComplete: function() {
      this.element.attr( 'disabled', false );
    },

    confirm: function( ids ) {
      var self = this;
      var template = '<p>You are about to delete {{count}} documents.</p>' +
          '<p>Are you sure?</p>';

      var dialog = $('<div/>').attr( 'title', 'Confirm Delete' ).
          html( $.mustache( template, {
            count: ids.length
          }));

      $(dialog).dialog({
        modal: true,
        closeText: '',
        buttons: {
          'Delete': function() {
            $(this).dialog('close');
            self.doDelete( ids );
          },
          'Cancel': function() { $(this).dialog('close'); }
        }
      });
    }
  };
}(jQuery));
Backstop.Grid.SelectFilter = Filter.defineFilterType({
  fieldsTemplate:
  '  <dl class="{{columnName}}">\n' +
      '    <dd><select name="{{columnName}}" id="{{filterId}}">\n' +
      '    </select>\n</dd>' +
      '  </dl>\n',

  _createElements: function( name, id ) {
    var self = this;
    var view = {
      columnName: name,
      filterId: this.filterId,
      text: this.labelText
    };

    var fields = $( $.mustache( this.fieldsTemplate, view ) ).hide();
    this.select = fields.find( 'select' );

    this.addToForm( fields, this.options.advanced  );

    this.select.change( function( event ) {
      event.preventDefault();
      self.commit();
      self.grid.trigger( 'reload' );
    });

    return fields;
  },

  _updateFilterData: function( grid, data ) {
    if ( Backstop.isnull( data ) || Backstop.isnull( data[this.columnName] ) ) { return; }

    var self = this;
    var values = $.unique( data[this.columnName] ).sort(
      function (a1, b1) {
        var a = ('' + a1.name).toLowerCase();
        var b = ('' + b1.name).toLowerCase();
        if (a > b) { return 1; }
        if (a < b) { return -1; }
        return 0;
      });

    var fieldset = this.form().find( '.' + this.columnName );

    fieldset.toggle( !this.hidden && values.length > 1 );

    this.select.empty();
    this.select.append( $('<option/>').text( this.labelText ).val( '' ) );

    $.each( values, function( index, value ) {
      if ( !self.excluded_tags || !self.excluded_tags.includes( value.name ) ) {
        var option = $('<option/>').text( value.name ).val( value.id );
        self.select.append( option );
      }
    });

    var currentFilterValue = $(grid).backstopGrid( 'searchScope', this.columnName );

    if ( !Backstop.isnull( currentFilterValue ) ) {
      this.select.val( String(currentFilterValue) );
    }
  }
});
/**
 * Simple input filter for Backstop.Grid columns.
 */
Backstop.Grid.SimpleFilter = Filter.defineFilterType({
  fieldsTemplate: '<dl class="{{column}}">' +
                  ' <dt><label for="{{id}}">{{label}}</label></dt>' +
                  ' <dd><input name="{{column}}" id="{{id}}" class="magnifying-glass"></input></dd>' +
                  '</dl>',
  _createElements: function ( column, id, label ) {
    var self = this;
    var view = {
      column: column,
      id: id,
      label: label
    };

    var fields = $( $.mustache( this.fieldsTemplate, view ) );
    this.addToForm( fields, this.options.advanced );

    fields.find( 'input' ).change( function ( event ) {
      event.preventDefault();
      self.commit();
      self.grid.trigger( 'reload' );
    });

    return fields;
  },

  _updateFilterData: function () {}
});
/**
 * Auto-complete filter input for Backstop.Grid columns.
 */
Backstop.Grid.TypeAheadFilter = Filter.defineFilterType({
  reset: function() {
    this.currentSelection = null;
    this.input.val( '' );
  },

  fieldsTemplate:
  '<dl class="{{name}}">\n' +
      '  <dt><label for="{{id}}">{{label}}</label>\n</dt>' +
      '  <dd><input id="{{id}}" name="{{name}}" ' +
      'class="filter magnifying-glass"/>\n</dd>' +
      '</dl>\n',

  commit: function () {
    if (!this.input.data('type-ahead-filter-already-selected')) {
      var e = jQuery.Event('keydown');
      e.keyCode = $.ui.keyCode.ENTER;
      this.input.trigger( e );
    }

    if ( this.currentSelection ) {
      this.grid.backstopGrid(
        'searchScope',
        this.columnName,
        this.currentSelection.value
      );
      this.grid.backstopGrid(
        'searchScope',
        this.currentSelection.name,
        this.currentSelection.extra_value
      );
    } else {
      var value = this.input.val();
      this.grid.backstopGrid( 'searchScope', 'link_type', '' );
      this.grid.backstopGrid( 'searchScope', 'link_type_plus_accounts_related_to_products', '' );
      this.grid.backstopGrid( 'searchScope', this.columnName, value );
    }
  },

  _createElements: function( name, id ) {
    var self = this;

    var data = {
      id:    id,
      name:  name,
      label: this.labelText
    };

    var fields = $( $.mustache( this.fieldsTemplate, data ) ).hide();

    this.input = fields.find( 'input.filter' ).
        change( function( e ) {
          if ( $(this).val() === '' ) {
            self.currentSelection = null;
          }
        }).
        autocomplete( {
          source: null,
          selectFirst:   true,
          matchContains: true
        });

    this.input.
    autocomplete( 'instance' )._renderItem = function( ul, item ) {
      return $( '<li>' )
        .append( '<div>' + item.value + ' (' + item.extra_value.match(/[A-Z][a-z]+|[0-9]+/g).join(' ') + ')' + '</div>')
        .appendTo( ul );
    };

    this.addToForm( fields, this.options.advanced  );

    return fields;
  },

  _updateFilterData: function( grid, data ) {
    if ( Backstop.isnull( data ) || Backstop.isnull( data[this.columnName] ) ) { return; }
    if ( !Backstop.isnull( this[this.columnName] ) ) { return; }
    var values   = $.unique( data[this.columnName] ).sort();
    var fieldset = this.form().find( '.' + this.columnName );

    if ( values[0] && typeof values[0] !== 'string' ) {
      this._create_additional_inputs( values[0], fieldset );
    }

    fieldset.toggle( !this.hidden && values.length > 1 );

    var current_filter_value =
        $(grid).backstopGrid( 'searchScope', this.columnName );
    if ( !Backstop.isnull( current_filter_value ) ) {
      this.input.val( current_filter_value );
    }

    this[this.columnName]   = values;

    this.input.autocomplete('option', 'source', values);
    this.input.autocomplete('option', 'selectFirst', true);
    this.input.autocomplete('option', 'matchContains', true );
  },

  _create_additional_inputs: function( data_object, element ) {
    if ( typeof data_object.extra_value === 'undefined' ) { return element; }
    var self = this;

    this.input.bind( 'autocompleteselect', function( event, data ) {
      self.currentSelection = data.item;
      self.input.val( data.item.value );
      self.input.data('type-ahead-filter-already-selected', true);
      self.form().submit();
    });

    return element;
  }
});
//  Backstop.Grid Manifest











;
/*
 Highcharts JS v9.1.0 (2021-05-03)

 (c) 2009-2021 Torstein Honsi

 License: www.highcharts.com/license
*/
(function(W,O){"object"===typeof module&&module.exports?(O["default"]=O,module.exports=W.document?O(W):O):"function"===typeof define&&define.amd?define("highcharts/highcharts",function(){return O(W)}):(W.Highcharts&&W.Highcharts.error(16,!0),W.Highcharts=O(W))})("undefined"!==typeof window?window:this,function(W){function O(D,b,e,z){D.hasOwnProperty(b)||(D[b]=z.apply(null,e))}var e={};O(e,"Core/Globals.js",[],function(){var D="undefined"!==typeof W?W:"undefined"!==typeof window?window:{},b;(function(b){b.SVG_NS=
"http://www.w3.org/2000/svg";b.product="Highcharts";b.version="9.1.0";b.win=D;b.doc=b.win.document;b.svg=b.doc&&b.doc.createElementNS&&!!b.doc.createElementNS(b.SVG_NS,"svg").createSVGRect;b.userAgent=b.win.navigator&&b.win.navigator.userAgent||"";b.isChrome=-1!==b.userAgent.indexOf("Chrome");b.isFirefox=-1!==b.userAgent.indexOf("Firefox");b.isMS=/(edge|msie|trident)/i.test(b.userAgent)&&!b.win.opera;b.isSafari=!b.isChrome&&-1!==b.userAgent.indexOf("Safari");b.isTouchDevice=/(Mobile|Android|Windows Phone)/.test(b.userAgent);
b.isWebKit=-1!==b.userAgent.indexOf("AppleWebKit");b.deg2rad=2*Math.PI/360;b.hasBidiBug=b.isFirefox&&4>parseInt(b.userAgent.split("Firefox/")[1],10);b.hasTouch=!!b.win.TouchEvent;b.marginNames=["plotTop","marginRight","marginBottom","plotLeft"];b.noop=function(){};b.supportsPassiveEvents=function(){var D=!1;if(!b.isMS){var e=Object.defineProperty({},"passive",{get:function(){D=!0}});b.win.addEventListener&&b.win.removeEventListener&&(b.win.addEventListener("testPassive",b.noop,e),b.win.removeEventListener("testPassive",
b.noop,e))}return D}();b.charts=[];b.dateFormats={};b.seriesTypes={};b.symbolSizes={}})(b||(b={}));return b});O(e,"Core/Utilities.js",[e["Core/Globals.js"]],function(D){function b(a,c,h,r){var y=c?"Highcharts error":"Highcharts warning";32===a&&(a=y+": Deprecated member");var d=w(a),M=d?y+" #"+a+": www.highcharts.com/errors/"+a+"/":a.toString();if("undefined"!==typeof r){var t="";d&&(M+="?");n(r,function(p,a){t+="\n - "+a+": "+p;d&&(M+=encodeURI(a)+"="+encodeURI(p))});M+=t}E(Highcharts,"displayError",
{chart:h,code:a,message:M,params:r},function(){if(c)throw Error(M);g.console&&-1===b.messages.indexOf(M)&&console.warn(M)});b.messages.push(M)}function e(a,c){var y={};n(a,function(g,h){if(C(a[h],!0)&&!a.nodeType&&c[h])g=e(a[h],c[h]),Object.keys(g).length&&(y[h]=g);else if(C(a[h])||a[h]!==c[h])y[h]=a[h]});return y}function z(a,c){return parseInt(a,c||10)}function H(a){return"string"===typeof a}function G(a){a=Object.prototype.toString.call(a);return"[object Array]"===a||"[object Array Iterator]"===
a}function C(a,c){return!!a&&"object"===typeof a&&(!c||!G(a))}function B(a){return C(a)&&"number"===typeof a.nodeType}function x(a){var c=a&&a.constructor;return!(!C(a,!0)||B(a)||!c||!c.name||"Object"===c.name)}function w(a){return"number"===typeof a&&!isNaN(a)&&Infinity>a&&-Infinity<a}function v(a){return"undefined"!==typeof a&&null!==a}function f(a,c,g){var y;H(c)?v(g)?a.setAttribute(c,g):a&&a.getAttribute&&((y=a.getAttribute(c))||"class"!==c||(y=a.getAttribute(c+"Name"))):n(c,function(c,y){a.setAttribute(y,
c)});return y}function d(a,c){var y;a||(a={});for(y in c)a[y]=c[y];return a}function q(){for(var a=arguments,c=a.length,g=0;g<c;g++){var h=a[g];if("undefined"!==typeof h&&null!==h)return h}}function k(a,c){D.isMS&&!D.svg&&c&&"undefined"!==typeof c.opacity&&(c.filter="alpha(opacity="+100*c.opacity+")");d(a.style,c)}function l(a,g,h,r,m){a=c.createElement(a);g&&d(a,g);m&&k(a,{padding:"0",border:"none",margin:"0"});h&&k(a,h);r&&r.appendChild(a);return a}function N(a,c){return parseFloat(a.toPrecision(c||
14))}function u(a,c,h){var y=D.getStyle||u;if("width"===c)return c=Math.min(a.offsetWidth,a.scrollWidth),h=a.getBoundingClientRect&&a.getBoundingClientRect().width,h<c&&h>=c-1&&(c=Math.floor(h)),Math.max(0,c-(y(a,"padding-left",!0)||0)-(y(a,"padding-right",!0)||0));if("height"===c)return Math.max(0,Math.min(a.offsetHeight,a.scrollHeight)-(y(a,"padding-top",!0)||0)-(y(a,"padding-bottom",!0)||0));g.getComputedStyle||b(27,!0);if(a=g.getComputedStyle(a,void 0)){var r=a.getPropertyValue(c);q(h,"opacity"!==
c)&&(r=z(r))}return r}function n(a,c,g){for(var h in a)Object.hasOwnProperty.call(a,h)&&c.call(g||a[h],a[h],h,a)}function J(a,c,g){function h(t,p){var c=a.removeEventListener||D.removeEventListenerPolyfill;c&&c.call(a,t,p,!1)}function y(t){var p;if(a.nodeName){if(c){var g={};g[c]=!0}else g=t;n(g,function(a,c){if(t[c])for(p=t[c].length;p--;)h(c,t[c][p].fn)})}}var r="function"===typeof a&&a.prototype||a;if(Object.hasOwnProperty.call(r,"hcEvents")){var M=r.hcEvents;c?(r=M[c]||[],g?(M[c]=r.filter(function(a){return g!==
a.fn}),h(c,g)):(y(M),M[c]=[])):(y(M),delete r.hcEvents)}}function E(a,g,h,r){h=h||{};if(c.createEvent&&(a.dispatchEvent||a.fireEvent&&a!==D)){var y=c.createEvent("Events");y.initEvent(g,!0,!0);h=d(y,h);a.dispatchEvent?a.dispatchEvent(h):a.fireEvent(g,h)}else if(a.hcEvents){h.target||d(h,{preventDefault:function(){h.defaultPrevented=!0},target:a,type:g});y=[];for(var m=a,M=!1;m.hcEvents;)Object.hasOwnProperty.call(m,"hcEvents")&&m.hcEvents[g]&&(y.length&&(M=!0),y.unshift.apply(y,m.hcEvents[g])),m=
Object.getPrototypeOf(m);M&&y.sort(function(a,p){return a.order-p.order});y.forEach(function(t){!1===t.fn.call(a,h)&&h.preventDefault()})}r&&!h.defaultPrevented&&r.call(a,h)}var m=D.charts,c=D.doc,g=D.win;"";(b||(b={})).messages=[];var a;Math.easeInOutSine=function(a){return-.5*(Math.cos(Math.PI*a)-1)};var h=Array.prototype.find?function(a,c){return a.find(c)}:function(a,c){var g,h=a.length;for(g=0;g<h;g++)if(c(a[g],g))return a[g]};n({map:"map",each:"forEach",grep:"filter",reduce:"reduce",some:"some"},
function(a,c){D[c]=function(g){var h;b(32,!1,void 0,(h={},h["Highcharts."+c]="use Array."+a,h));return Array.prototype[a].apply(g,[].slice.call(arguments,1))}});var r,A=function(){var a=Math.random().toString(36).substring(2,9)+"-",c=0;return function(){return"highcharts-"+(r?"":a)+c++}}();g.jQuery&&(g.jQuery.fn.highcharts=function(){var a=[].slice.call(arguments);if(this[0])return a[0]?(new (D[H(a[0])?a.shift():"Chart"])(this[0],a[0],a[1]),this):m[f(this[0],"data-highcharts-chart")]});return{addEvent:function(a,
c,g,h){void 0===h&&(h={});var r="function"===typeof a&&a.prototype||a;Object.hasOwnProperty.call(r,"hcEvents")||(r.hcEvents={});r=r.hcEvents;D.Point&&a instanceof D.Point&&a.series&&a.series.chart&&(a.series.chart.runTrackerClick=!0);var y=a.addEventListener||D.addEventListenerPolyfill;y&&y.call(a,c,g,D.supportsPassiveEvents?{passive:void 0===h.passive?-1!==c.indexOf("touch"):h.passive,capture:!1}:!1);r[c]||(r[c]=[]);r[c].push({fn:g,order:"number"===typeof h.order?h.order:Infinity});r[c].sort(function(a,
t){return a.order-t.order});return function(){J(a,c,g)}},arrayMax:function(a){for(var c=a.length,g=a[0];c--;)a[c]>g&&(g=a[c]);return g},arrayMin:function(a){for(var c=a.length,g=a[0];c--;)a[c]<g&&(g=a[c]);return g},attr:f,clamp:function(a,c,g){return a>c?a<g?a:g:c},cleanRecursively:e,clearTimeout:function(a){v(a)&&clearTimeout(a)},correctFloat:N,createElement:l,css:k,defined:v,destroyObjectProperties:function(a,c){n(a,function(g,h){g&&g!==c&&g.destroy&&g.destroy();delete a[h]})},discardElement:function(c){a||
(a=l("div"));c&&a.appendChild(c);a.innerHTML=""},erase:function(a,c){for(var g=a.length;g--;)if(a[g]===c){a.splice(g,1);break}},error:b,extend:d,extendClass:function(a,c){var g=function(){};g.prototype=new a;d(g.prototype,c);return g},find:h,fireEvent:E,getMagnitude:function(a){return Math.pow(10,Math.floor(Math.log(a)/Math.LN10))},getNestedProperty:function(a,c){for(a=a.split(".");a.length&&v(c);){var h=a.shift();if("undefined"===typeof h||"__proto__"===h)return;c=c[h];if(!v(c)||"function"===typeof c||
"number"===typeof c.nodeType||c===g)return}return c},getStyle:u,inArray:function(a,c,g){b(32,!1,void 0,{"Highcharts.inArray":"use Array.indexOf"});return c.indexOf(a,g)},isArray:G,isClass:x,isDOMElement:B,isFunction:function(a){return"function"===typeof a},isNumber:w,isObject:C,isString:H,keys:function(a){b(32,!1,void 0,{"Highcharts.keys":"use Object.keys"});return Object.keys(a)},merge:function(){var a,c=arguments,g={},h=function(a,c){"object"!==typeof a&&(a={});n(c,function(t,p){"__proto__"!==p&&
"constructor"!==p&&(!C(t,!0)||x(t)||B(t)?a[p]=c[p]:a[p]=h(a[p]||{},t))});return a};!0===c[0]&&(g=c[1],c=Array.prototype.slice.call(c,2));var r=c.length;for(a=0;a<r;a++)g=h(g,c[a]);return g},normalizeTickInterval:function(a,c,g,h,r){var d=a;g=q(g,1);var M=a/g;c||(c=r?[1,1.2,1.5,2,2.5,3,4,5,6,8,10]:[1,2,2.5,5,10],!1===h&&(1===g?c=c.filter(function(a){return 0===a%1}):.1>=g&&(c=[1/g])));for(h=0;h<c.length&&!(d=c[h],r&&d*g>=a||!r&&M<=(c[h]+(c[h+1]||c[h]))/2);h++);return d=N(d*g,-Math.round(Math.log(.001)/
Math.LN10))},objectEach:n,offset:function(a){var h=c.documentElement;a=a.parentElement||a.parentNode?a.getBoundingClientRect():{top:0,left:0,width:0,height:0};return{top:a.top+(g.pageYOffset||h.scrollTop)-(h.clientTop||0),left:a.left+(g.pageXOffset||h.scrollLeft)-(h.clientLeft||0),width:a.width,height:a.height}},pad:function(a,c,g){return Array((c||2)+1-String(a).replace("-","").length).join(g||"0")+a},pick:q,pInt:z,relativeLength:function(a,c,g){return/%$/.test(a)?c*parseFloat(a)/100+(g||0):parseFloat(a)},
removeEvent:J,splat:function(a){return G(a)?a:[a]},stableSort:function(a,c){var g=a.length,h,r;for(r=0;r<g;r++)a[r].safeI=r;a.sort(function(a,g){h=c(a,g);return 0===h?a.safeI-g.safeI:h});for(r=0;r<g;r++)delete a[r].safeI},syncTimeout:function(a,c,g){if(0<c)return setTimeout(a,c,g);a.call(0,g);return-1},timeUnits:{millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5},uniqueKey:A,useSerialIds:function(a){return r=q(a,r)},wrap:function(a,c,g){var h=a[c];a[c]=
function(){var a=Array.prototype.slice.call(arguments),c=arguments,r=this;r.proceed=function(){h.apply(r,arguments.length?arguments:c)};a.unshift(h);a=g.apply(this,a);r.proceed=null;return a}}}});O(e,"Core/Color/Color.js",[e["Core/Globals.js"],e["Core/Utilities.js"]],function(D,b){var e=b.isNumber,z=b.merge,H=b.pInt;"";b=function(){function b(e){this.parsers=[{regex:/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,parse:function(b){return[H(b[1]),H(b[2]),
H(b[3]),parseFloat(b[4],10)]}},{regex:/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,parse:function(b){return[H(b[1]),H(b[2]),H(b[3]),1]}}];this.rgba=[];if(D.Color!==b)return new D.Color(e);if(!(this instanceof b))return new b(e);this.init(e)}b.parse=function(e){return new b(e)};b.prototype.init=function(e){var B,x;if((this.input=e=b.names[e&&e.toLowerCase?e.toLowerCase():""]||e)&&e.stops)this.stops=e.stops.map(function(f){return new b(f[1])});else{if(e&&e.charAt&&"#"===e.charAt()){var w=
e.length;e=parseInt(e.substr(1),16);7===w?B=[(e&16711680)>>16,(e&65280)>>8,e&255,1]:4===w&&(B=[(e&3840)>>4|(e&3840)>>8,(e&240)>>4|e&240,(e&15)<<4|e&15,1])}if(!B)for(x=this.parsers.length;x--&&!B;){var v=this.parsers[x];(w=v.regex.exec(e))&&(B=v.parse(w))}}this.rgba=B||[]};b.prototype.get=function(b){var B=this.input,x=this.rgba;if("undefined"!==typeof this.stops){var w=z(B);w.stops=[].concat(w.stops);this.stops.forEach(function(v,f){w.stops[f]=[w.stops[f][0],v.get(b)]})}else w=x&&e(x[0])?"rgb"===
b||!b&&1===x[3]?"rgb("+x[0]+","+x[1]+","+x[2]+")":"a"===b?x[3]:"rgba("+x.join(",")+")":B;return w};b.prototype.brighten=function(b){var B,x=this.rgba;if(this.stops)this.stops.forEach(function(w){w.brighten(b)});else if(e(b)&&0!==b)for(B=0;3>B;B++)x[B]+=H(255*b),0>x[B]&&(x[B]=0),255<x[B]&&(x[B]=255);return this};b.prototype.setOpacity=function(b){this.rgba[3]=b;return this};b.prototype.tweenTo=function(b,e){var x=this.rgba,w=b.rgba;w.length&&x&&x.length?(b=1!==w[3]||1!==x[3],e=(b?"rgba(":"rgb(")+Math.round(w[0]+
(x[0]-w[0])*(1-e))+","+Math.round(w[1]+(x[1]-w[1])*(1-e))+","+Math.round(w[2]+(x[2]-w[2])*(1-e))+(b?","+(w[3]+(x[3]-w[3])*(1-e)):"")+")"):e=b.input||"none";return e};b.names={white:"#ffffff",black:"#000000"};return b}();D.Color=b;D.color=b.parse;return b});O(e,"Core/Color/Palette.js",[],function(){return{colors:"#7cb5ec #434348 #90ed7d #f7a35c #8085e9 #f15c80 #e4d354 #2b908f #f45b5b #91e8e1".split(" "),backgroundColor:"#ffffff",neutralColor100:"#000000",neutralColor80:"#333333",neutralColor60:"#666666",
neutralColor40:"#999999",neutralColor20:"#cccccc",neutralColor10:"#e6e6e6",neutralColor5:"#f2f2f2",neutralColor3:"#f7f7f7",highlightColor100:"#003399",highlightColor80:"#335cad",highlightColor60:"#6685c2",highlightColor20:"#ccd6eb",highlightColor10:"#e6ebf5",positiveColor:"#06b535",negativeColor:"#f21313"}});O(e,"Core/Time.js",[e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b){var D=e.win,z=b.defined,H=b.error,G=b.extend,C=b.isObject,B=b.merge,x=b.objectEach,w=b.pad,v=b.pick,f=b.splat,d=
b.timeUnits;"";b=function(){function q(d){this.options={};this.variableTimezone=this.useUTC=!1;this.Date=D.Date;this.getTimezoneOffset=this.timezoneOffsetFunction();this.update(d)}q.prototype.get=function(d,l){if(this.variableTimezone||this.timezoneOffset){var k=l.getTime(),u=k-this.getTimezoneOffset(l);l.setTime(u);d=l["getUTC"+d]();l.setTime(k);return d}return this.useUTC?l["getUTC"+d]():l["get"+d]()};q.prototype.set=function(d,l,f){if(this.variableTimezone||this.timezoneOffset){if("Milliseconds"===
d||"Seconds"===d||"Minutes"===d&&0===this.getTimezoneOffset(l)%36E5)return l["setUTC"+d](f);var u=this.getTimezoneOffset(l);u=l.getTime()-u;l.setTime(u);l["setUTC"+d](f);d=this.getTimezoneOffset(l);u=l.getTime()+d;return l.setTime(u)}return this.useUTC?l["setUTC"+d](f):l["set"+d](f)};q.prototype.update=function(d){var l=v(d&&d.useUTC,!0);this.options=d=B(!0,this.options||{},d);this.Date=d.Date||D.Date||Date;this.timezoneOffset=(this.useUTC=l)&&d.timezoneOffset;this.getTimezoneOffset=this.timezoneOffsetFunction();
this.variableTimezone=l&&!(!d.getTimezoneOffset&&!d.timezone)};q.prototype.makeTime=function(d,l,f,u,n,q){if(this.useUTC){var k=this.Date.UTC.apply(0,arguments);var m=this.getTimezoneOffset(k);k+=m;var c=this.getTimezoneOffset(k);m!==c?k+=c-m:m-36E5!==this.getTimezoneOffset(k-36E5)||e.isSafari||(k-=36E5)}else k=(new this.Date(d,l,v(f,1),v(u,0),v(n,0),v(q,0))).getTime();return k};q.prototype.timezoneOffsetFunction=function(){var d=this,l=this.options,f=l.moment||D.moment;if(!this.useUTC)return function(d){return 6E4*
(new Date(d.toString())).getTimezoneOffset()};if(l.timezone){if(f)return function(d){return 6E4*-f.tz(d,l.timezone).utcOffset()};H(25)}return this.useUTC&&l.getTimezoneOffset?function(d){return 6E4*l.getTimezoneOffset(d.valueOf())}:function(){return 6E4*(d.timezoneOffset||0)}};q.prototype.dateFormat=function(d,f,q){if(!z(f)||isNaN(f))return e.defaultOptions.lang&&e.defaultOptions.lang.invalidDate||"";d=v(d,"%Y-%m-%d %H:%M:%S");var l=this,n=new this.Date(f),k=this.get("Hours",n),N=this.get("Day",n),
m=this.get("Date",n),c=this.get("Month",n),g=this.get("FullYear",n),a=e.defaultOptions.lang,h=a&&a.weekdays,r=a&&a.shortWeekdays;n=G({a:r?r[N]:h[N].substr(0,3),A:h[N],d:w(m),e:w(m,2," "),w:N,b:a.shortMonths[c],B:a.months[c],m:w(c+1),o:c+1,y:g.toString().substr(2,2),Y:g,H:w(k),k:k,I:w(k%12||12),l:k%12||12,M:w(this.get("Minutes",n)),p:12>k?"AM":"PM",P:12>k?"am":"pm",S:w(n.getSeconds()),L:w(Math.floor(f%1E3),3)},e.dateFormats);x(n,function(a,c){for(;-1!==d.indexOf("%"+c);)d=d.replace("%"+c,"function"===
typeof a?a.call(l,f):a)});return q?d.substr(0,1).toUpperCase()+d.substr(1):d};q.prototype.resolveDTLFormat=function(d){return C(d,!0)?d:(d=f(d),{main:d[0],from:d[1],to:d[2]})};q.prototype.getTimeTicks=function(f,l,q,u){var n=this,k=[],N={};var m=new n.Date(l);var c=f.unitRange,g=f.count||1,a;u=v(u,1);if(z(l)){n.set("Milliseconds",m,c>=d.second?0:g*Math.floor(n.get("Milliseconds",m)/g));c>=d.second&&n.set("Seconds",m,c>=d.minute?0:g*Math.floor(n.get("Seconds",m)/g));c>=d.minute&&n.set("Minutes",m,
c>=d.hour?0:g*Math.floor(n.get("Minutes",m)/g));c>=d.hour&&n.set("Hours",m,c>=d.day?0:g*Math.floor(n.get("Hours",m)/g));c>=d.day&&n.set("Date",m,c>=d.month?1:Math.max(1,g*Math.floor(n.get("Date",m)/g)));if(c>=d.month){n.set("Month",m,c>=d.year?0:g*Math.floor(n.get("Month",m)/g));var h=n.get("FullYear",m)}c>=d.year&&n.set("FullYear",m,h-h%g);c===d.week&&(h=n.get("Day",m),n.set("Date",m,n.get("Date",m)-h+u+(h<u?-7:0)));h=n.get("FullYear",m);u=n.get("Month",m);var r=n.get("Date",m),A=n.get("Hours",m);
l=m.getTime();!n.variableTimezone&&n.useUTC||!z(q)||(a=q-l>4*d.month||n.getTimezoneOffset(l)!==n.getTimezoneOffset(q));l=m.getTime();for(m=1;l<q;)k.push(l),l=c===d.year?n.makeTime(h+m*g,0):c===d.month?n.makeTime(h,u+m*g):!a||c!==d.day&&c!==d.week?a&&c===d.hour&&1<g?n.makeTime(h,u,r,A+m*g):l+c*g:n.makeTime(h,u,r+m*g*(c===d.day?1:7)),m++;k.push(l);c<=d.hour&&1E4>k.length&&k.forEach(function(a){0===a%18E5&&"000000000"===n.dateFormat("%H%M%S%L",a)&&(N[a]="day")})}k.info=G(f,{higherRanks:N,totalRange:c*
g});return k};return q}();e.Time=b;return e.Time});O(e,"Core/Options.js",[e["Core/Globals.js"],e["Core/Color/Color.js"],e["Core/Color/Palette.js"],e["Core/Time.js"],e["Core/Utilities.js"]],function(e,b,I,z,H){var D=e.isTouchDevice,C=e.svg;b=b.parse;var B=H.merge;"";var x={colors:I.colors,symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January February March April May June July August September October November December".split(" "),shortMonths:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),
weekdays:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),decimalPoint:".",numericSymbols:"kMGTPE".split(""),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{},time:{Date:void 0,getTimezoneOffset:void 0,timezone:void 0,timezoneOffset:0,useUTC:!0},chart:{panning:{enabled:!1,type:"x"},styledMode:!1,borderRadius:0,colorCount:10,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],resetZoomButton:{theme:{zIndex:6},position:{align:"right",
x:-10,y:10}},zoomBySingleTouch:!1,width:null,height:null,borderColor:I.highlightColor80,backgroundColor:I.backgroundColor,plotBorderColor:I.neutralColor20},title:{text:"Chart title",align:"center",margin:15,widthAdjust:-44},subtitle:{text:"",align:"center",widthAdjust:-44},caption:{margin:15,text:"",align:"left",verticalAlign:"bottom"},plotOptions:{},labels:{style:{position:"absolute",color:I.neutralColor80}},legend:{enabled:!0,align:"center",alignColumns:!0,layout:"horizontal",labelFormatter:function(){return this.name},
borderColor:I.neutralColor40,borderRadius:0,navigation:{activeColor:I.highlightColor100,inactiveColor:I.neutralColor20},itemStyle:{color:I.neutralColor80,cursor:"pointer",fontSize:"12px",fontWeight:"bold",textOverflow:"ellipsis"},itemHoverStyle:{color:I.neutralColor100},itemHiddenStyle:{color:I.neutralColor20},shadow:!1,itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},squareSymbol:!0,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",
position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:I.backgroundColor,opacity:.5,textAlign:"center"}},tooltip:{enabled:!0,animation:C,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},footerFormat:"",padding:8,snap:D?25:10,headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{point.color}">\u25cf</span> {series.name}: <b>{point.y}</b><br/>',
backgroundColor:b(I.neutralColor3).setOpacity(.85).get(),borderWidth:1,shadow:!0,style:{color:I.neutralColor80,cursor:"default",fontSize:"12px",whiteSpace:"nowrap"}},credits:{enabled:!0,href:"https://www.highcharts.com?credits",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:I.neutralColor40,fontSize:"9px"},text:"Highcharts.com"}};x.chart.styledMode=!1;"";var w=new z(B(x.global,x.time));return{defaultOptions:x,defaultTime:w,getOptions:function(){return x},
setOptions:function(v){B(!0,x,v);if(v.time||v.global)e.time?e.time.update(B(x.global,x.time,v.global,v.time)):e.time=w;return x}}});O(e,"Core/Animation/Fx.js",[e["Core/Color/Color.js"],e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b,I){var D=e.parse,H=b.win,G=I.isNumber,C=I.objectEach;return function(){function b(b,w,v){this.pos=NaN;this.options=w;this.elem=b;this.prop=v}b.prototype.dSetter=function(){var b=this.paths,w=b&&b[0];b=b&&b[1];var v=this.now||0,f=[];if(1!==v&&w&&b)if(w.length===
b.length&&1>v)for(var d=0;d<b.length;d++){for(var q=w[d],k=b[d],l=[],N=0;N<k.length;N++){var u=q[N],n=k[N];G(u)&&G(n)&&("A"!==k[0]||4!==N&&5!==N)?l[N]=u+v*(n-u):l[N]=n}f.push(l)}else f=b;else f=this.toD||[];this.elem.attr("d",f,void 0,!0)};b.prototype.update=function(){var b=this.elem,w=this.prop,v=this.now,f=this.options.step;if(this[w+"Setter"])this[w+"Setter"]();else b.attr?b.element&&b.attr(w,v,null,!0):b.style[w]=v+this.unit;f&&f.call(b,v,this)};b.prototype.run=function(e,w,v){var f=this,d=f.options,
q=function(d){return q.stopped?!1:f.step(d)},k=H.requestAnimationFrame||function(d){setTimeout(d,13)},l=function(){for(var d=0;d<b.timers.length;d++)b.timers[d]()||b.timers.splice(d--,1);b.timers.length&&k(l)};e!==w||this.elem["forceAnimate:"+this.prop]?(this.startTime=+new Date,this.start=e,this.end=w,this.unit=v,this.now=this.start,this.pos=0,q.elem=this.elem,q.prop=this.prop,q()&&1===b.timers.push(q)&&k(l)):(delete d.curAnim[this.prop],d.complete&&0===Object.keys(d.curAnim).length&&d.complete.call(this.elem))};
b.prototype.step=function(b){var w=+new Date,v=this.options,f=this.elem,d=v.complete,q=v.duration,k=v.curAnim;if(f.attr&&!f.element)b=!1;else if(b||w>=q+this.startTime){this.now=this.end;this.pos=1;this.update();var l=k[this.prop]=!0;C(k,function(d){!0!==d&&(l=!1)});l&&d&&d.call(f);b=!1}else this.pos=v.easing((w-this.startTime)/q),this.now=this.start+(this.end-this.start)*this.pos,this.update(),b=!0;return b};b.prototype.initPath=function(b,w,v){function f(d,m){for(;d.length<J;){var c=d[0],g=m[J-
d.length];g&&"M"===c[0]&&(d[0]="C"===g[0]?["C",c[1],c[2],c[1],c[2],c[1],c[2]]:["L",c[1],c[2]]);d.unshift(c);l&&(c=d.pop(),d.push(d[d.length-1],c))}}function d(d,m){for(;d.length<J;)if(m=d[Math.floor(d.length/N)-1].slice(),"C"===m[0]&&(m[1]=m[5],m[2]=m[6]),l){var c=d[Math.floor(d.length/N)].slice();d.splice(d.length/2,0,m,c)}else d.push(m)}var q=b.startX,k=b.endX;v=v.slice();var l=b.isArea,N=l?2:1;w=w&&w.slice();if(!w)return[v,v];if(q&&k&&k.length){for(b=0;b<q.length;b++)if(q[b]===k[0]){var u=b;break}else if(q[0]===
k[k.length-q.length+b]){u=b;var n=!0;break}else if(q[q.length-1]===k[k.length-q.length+b]){u=q.length-b;break}"undefined"===typeof u&&(w=[])}if(w.length&&G(u)){var J=v.length+u*N;n?(f(w,v),d(v,w)):(f(v,w),d(w,v))}return[w,v]};b.prototype.fillSetter=function(){b.prototype.strokeSetter.apply(this,arguments)};b.prototype.strokeSetter=function(){this.elem.attr(this.prop,D(this.start).tweenTo(D(this.end),this.pos),null,!0)};b.timers=[];return b}()});O(e,"Core/Animation/AnimationUtilities.js",[e["Core/Animation/Fx.js"],
e["Core/Utilities.js"]],function(e,b){function D(d){return x(d)?w({duration:500,defer:0},d):{duration:d?500:0,defer:0}}function z(d,f){for(var q=e.timers.length;q--;)e.timers[q].elem!==d||f&&f!==e.timers[q].prop||(e.timers[q].stopped=!0)}var H=b.defined,G=b.getStyle,C=b.isArray,B=b.isNumber,x=b.isObject,w=b.merge,v=b.objectEach,f=b.pick;return{animate:function(d,f,k){var l,q="",u,n;if(!x(k)){var b=arguments;k={duration:b[2],easing:b[3],complete:b[4]}}B(k.duration)||(k.duration=400);k.easing="function"===
typeof k.easing?k.easing:Math[k.easing]||Math.easeInOutSine;k.curAnim=w(f);v(f,function(b,m){z(d,m);n=new e(d,k,m);u=void 0;"d"===m&&C(f.d)?(n.paths=n.initPath(d,d.pathArray,f.d),n.toD=f.d,l=0,u=1):d.attr?l=d.attr(m):(l=parseFloat(G(d,m))||0,"opacity"!==m&&(q="px"));u||(u=b);"string"===typeof u&&u.match("px")&&(u=u.replace(/px/g,""));n.run(l,u,q)})},animObject:D,getDeferredAnimation:function(d,f,b){var l=D(f),q=0,u=0;(b?[b]:d.series).forEach(function(d){d=D(d.options.animation);q=f&&H(f.defer)?l.defer:
Math.max(q,d.duration+d.defer);u=Math.min(l.duration,d.duration)});d.renderer.forExport&&(q=0);return{defer:Math.max(0,q-u),duration:Math.min(q,u)}},setAnimation:function(d,q){q.renderer.globalAnimation=f(d,q.options.chart.animation,!0)},stop:z}});O(e,"Core/Renderer/HTML/AST.js",[e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b){var D=e.SVG_NS,z=b.attr,H=b.createElement,G=b.discardElement,C=b.error,B=b.isString,x=b.objectEach,w=b.splat;"";var v=!1;try{v=!!(new DOMParser).parseFromString("",
"text/html")}catch(f){}return function(){function f(d){this.nodes="string"===typeof d?this.parseMarkup(d):d}f.filterUserAttributes=function(d){x(d,function(q,b){var l=!0;-1===f.allowedAttributes.indexOf(b)&&(l=!1);-1!==["background","dynsrc","href","lowsrc","src"].indexOf(b)&&(l=B(q)&&f.allowedReferences.some(function(d){return 0===q.indexOf(d)}));l||(C("Highcharts warning: Invalid attribute '"+b+"' in config"),delete d[b])});return d};f.setElementHTML=function(d,q){d.innerHTML="";q&&(new f(q)).addToDOM(d)};
f.prototype.addToDOM=function(d){function q(d,l){var b;w(d).forEach(function(d){var n=d.tagName,u=d.textContent?e.doc.createTextNode(d.textContent):void 0;if(n)if("#text"===n)var k=u;else if(-1!==f.allowedTags.indexOf(n)){n=e.doc.createElementNS("svg"===n?D:l.namespaceURI||D,n);var m=d.attributes||{};x(d,function(c,g){"tagName"!==g&&"attributes"!==g&&"children"!==g&&"textContent"!==g&&(m[g]=c)});z(n,f.filterUserAttributes(m));u&&n.appendChild(u);q(d.children||[],n);k=n}else C("Highcharts warning: Invalid tagName '"+
n+"' in config");k&&l.appendChild(k);b=k});return b}return q(this.nodes,d)};f.prototype.parseMarkup=function(d){var f=[];if(v)d=(new DOMParser).parseFromString(d,"text/html");else{var b=H("div");b.innerHTML=d;d={body:b}}var l=function(d,f){var n=d.nodeName.toLowerCase(),b={tagName:n};if("#text"===n){n=d.textContent||"";if(/^[\s]*$/.test(n))return;b.textContent=n}if(n=d.attributes){var u={};[].forEach.call(n,function(c){u[c.name]=c.value});b.attributes=u}if(d.childNodes.length){var m=[];[].forEach.call(d.childNodes,
function(c){l(c,m)});m.length&&(b.children=m)}f.push(b)};[].forEach.call(d.body.childNodes,function(d){return l(d,f)});b&&G(b);return f};f.allowedTags="a b br button caption circle clipPath code dd defs div dl dt em feComponentTransfer feFuncA feFuncB feFuncG feFuncR feGaussianBlur feOffset feMerge feMergeNode filter h1 h2 h3 h4 h5 h6 hr i img li linearGradient marker ol p path pattern pre rect small span stop strong style sub sup svg table text thead tbody tspan td th tr u ul #text".split(" ");f.allowedAttributes=
"aria-controls aria-describedby aria-expanded aria-haspopup aria-hidden aria-label aria-labelledby aria-live aria-pressed aria-readonly aria-roledescription aria-selected class clip-path color colspan cx cy d dx dy disabled fill height href id in markerHeight markerWidth offset opacity orient padding paddingLeft patternUnits r refX refY role scope slope src startOffset stdDeviation stroke stroke-linecap stroke-width style result rowspan summary target tabindex text-align textAnchor textLength type valign width x x1 x2 y y1 y2 zIndex".split(" ");
f.allowedReferences="https:// http:// mailto: / ../ ./ #".split(" ");return f}()});O(e,"Core/FormatUtilities.js",[e["Core/Options.js"],e["Core/Utilities.js"]],function(e,b){function D(b,v,f,d){b=+b||0;v=+v;var q=z.lang,k=(b.toString().split(".")[1]||"").split("e")[0].length,l=b.toString().split("e"),N=v;if(-1===v)v=Math.min(k,20);else if(!C(v))v=2;else if(v&&l[1]&&0>l[1]){var u=v+ +l[1];0<=u?(l[0]=(+l[0]).toExponential(u).split("e")[0],v=u):(l[0]=l[0].split(".")[0]||0,b=20>v?(l[0]*Math.pow(10,l[1])).toFixed(v):
0,l[1]=0)}u=(Math.abs(l[1]?l[0]:b)+Math.pow(10,-Math.max(v,k)-1)).toFixed(v);k=String(x(u));var n=3<k.length?k.length%3:0;f=B(f,q.decimalPoint);d=B(d,q.thousandsSep);b=(0>b?"-":"")+(n?k.substr(0,n)+d:"");b=0>+l[1]&&!N?"0":b+k.substr(n).replace(/(\d{3})(?=\d)/g,"$1"+d);v&&(b+=f+u.slice(-v));l[1]&&0!==+b&&(b+="e"+l[1]);return b}var z=e.defaultOptions,H=e.defaultTime,G=b.getNestedProperty,C=b.isNumber,B=b.pick,x=b.pInt;return{dateFormat:function(b,v,f){return H.dateFormat(b,v,f)},format:function(b,v,
f){var d="{",q=!1,k=/f$/,l=/\.([0-9])/,N=z.lang,u=f&&f.time||H;f=f&&f.numberFormatter||D;for(var n=[];b;){var J=b.indexOf(d);if(-1===J)break;var E=b.slice(0,J);if(q){E=E.split(":");d=G(E.shift()||"",v);if(E.length&&"number"===typeof d)if(E=E.join(":"),k.test(E)){var m=parseInt((E.match(l)||["","-1"])[1],10);null!==d&&(d=f(d,m,N.decimalPoint,-1<E.indexOf(",")?N.thousandsSep:""))}else d=u.dateFormat(E,d);n.push(d)}else n.push(E);b=b.slice(J+1);d=(q=!q)?"}":"{"}n.push(b);return n.join("")},numberFormat:D}});
O(e,"Core/Renderer/SVG/SVGElement.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Renderer/HTML/AST.js"],e["Core/Color/Color.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G){var D=e.animate,B=e.animObject,x=e.stop,w=z.deg2rad,v=z.doc,f=z.noop,d=z.svg,q=z.SVG_NS,k=z.win,l=G.addEvent,N=G.attr,u=G.createElement,n=G.css,J=G.defined,E=G.erase,m=G.extend,c=G.fireEvent,g=G.isArray,a=G.isFunction,h=G.isNumber,r=G.isString,A=G.merge,y=G.objectEach,L=
G.pick,P=G.pInt,R=G.syncTimeout,V=G.uniqueKey;e=function(){function e(){this.element=void 0;this.onEvents={};this.opacity=1;this.renderer=void 0;this.SVG_NS=q;this.symbolCustomAttribs="x y width height r start end innerR anchorX anchorY rounded".split(" ")}e.prototype._defaultGetter=function(a){a=L(this[a+"Value"],this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a};e.prototype._defaultSetter=function(a,t,p){p.setAttribute(t,a)};e.prototype.add=
function(a){var t=this.renderer,p=this.element;a&&(this.parentGroup=a);this.parentInverted=a&&a.inverted;"undefined"!==typeof this.textStr&&"text"===this.element.nodeName&&t.buildText(this);this.added=!0;if(!a||a.handleZ||this.zIndex)var c=this.zIndexSetter();c||(a?a.element:t.box).appendChild(p);if(this.onAdd)this.onAdd();return this};e.prototype.addClass=function(a,t){var p=t?"":this.attr("class")||"";a=(a||"").split(/ /g).reduce(function(a,t){-1===p.indexOf(t)&&a.push(t);return a},p?[p]:[]).join(" ");
a!==p&&this.attr("class",a);return this};e.prototype.afterSetters=function(){this.doTransform&&(this.updateTransform(),this.doTransform=!1)};e.prototype.align=function(a,t,p){var c={},g=this.renderer,d=g.alignedObjects,F,h,K;if(a){if(this.alignOptions=a,this.alignByTranslate=t,!p||r(p))this.alignTo=F=p||"renderer",E(d,this),d.push(this),p=void 0}else a=this.alignOptions,t=this.alignByTranslate,F=this.alignTo;p=L(p,g[F],"scrollablePlotBox"===F?g.plotBox:void 0,g);F=a.align;var M=a.verticalAlign;g=
(p.x||0)+(a.x||0);d=(p.y||0)+(a.y||0);"right"===F?h=1:"center"===F&&(h=2);h&&(g+=(p.width-(a.width||0))/h);c[t?"translateX":"x"]=Math.round(g);"bottom"===M?K=1:"middle"===M&&(K=2);K&&(d+=(p.height-(a.height||0))/K);c[t?"translateY":"y"]=Math.round(d);this[this.placed?"animate":"attr"](c);this.placed=!0;this.alignAttr=c;return this};e.prototype.alignSetter=function(a){var t={left:"start",center:"middle",right:"end"};t[a]&&(this.alignValue=a,this.element.setAttribute("text-anchor",t[a]))};e.prototype.animate=
function(a,t,p){var c=this,g=B(L(t,this.renderer.globalAnimation,!0));t=g.defer;L(v.hidden,v.msHidden,v.webkitHidden,!1)&&(g.duration=0);0!==g.duration?(p&&(g.complete=p),R(function(){c.element&&D(c,a,g)},t)):(this.attr(a,void 0,p),y(a,function(a,p){g.step&&g.step.call(this,a,{prop:p,pos:1,elem:this})},this));return this};e.prototype.applyTextOutline=function(a){var t=this.element;-1!==a.indexOf("contrast")&&(a=a.replace(/contrast/g,this.renderer.getContrast(t.style.fill)));var p=a.split(" ");a=p[p.length-
1];if((p=p[0])&&"none"!==p&&z.svg){this.fakeTS=!0;this.ySetter=this.xSetter;p=p.replace(/(^[\d\.]+)(.*?)$/g,function(a,p,t){return 2*Number(p)+t});this.removeTextOutline();var c=v.createElementNS(q,"tspan");N(c,{"class":"highcharts-text-outline",fill:a,stroke:a,"stroke-width":p,"stroke-linejoin":"round"});[].forEach.call(t.childNodes,function(a){var p=a.cloneNode(!0);p.removeAttribute&&["fill","stroke","stroke-width","stroke"].forEach(function(a){return p.removeAttribute(a)});c.appendChild(p)});var g=
v.createElementNS(q,"tspan");g.textContent="\u200b";["x","y"].forEach(function(a){var p=t.getAttribute(a);p&&g.setAttribute(a,p)});c.appendChild(g);t.insertBefore(c,t.firstChild)}};e.prototype.attr=function(a,t,p,c){var g=this.element,d=this.symbolCustomAttribs,h,r=this,K,m;if("string"===typeof a&&"undefined"!==typeof t){var M=a;a={};a[M]=t}"string"===typeof a?r=(this[a+"Getter"]||this._defaultGetter).call(this,a,g):(y(a,function(p,t){K=!1;c||x(this,t);this.symbolName&&-1!==d.indexOf(t)&&(h||(this.symbolAttr(a),
h=!0),K=!0);!this.rotation||"x"!==t&&"y"!==t||(this.doTransform=!0);K||(m=this[t+"Setter"]||this._defaultSetter,m.call(this,p,t,g),!this.styledMode&&this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(t)&&this.updateShadows(t,p,m))},this),this.afterSetters());p&&p.call(this);return r};e.prototype.clip=function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":"none")};e.prototype.crisp=function(a,t){t=t||a.strokeWidth||0;var p=Math.round(t)%2/2;a.x=Math.floor(a.x||
this.x||0)+p;a.y=Math.floor(a.y||this.y||0)+p;a.width=Math.floor((a.width||this.width||0)-2*p);a.height=Math.floor((a.height||this.height||0)-2*p);J(a.strokeWidth)&&(a.strokeWidth=t);return a};e.prototype.complexColor=function(a,t,p){var d=this.renderer,h,r,F,m,K,M,f,b,l,n,u=[],q;c(this.renderer,"complexColor",{args:arguments},function(){a.radialGradient?r="radialGradient":a.linearGradient&&(r="linearGradient");if(r){F=a[r];K=d.gradients;M=a.stops;l=p.radialReference;g(F)&&(a[r]=F={x1:F[0],y1:F[1],
x2:F[2],y2:F[3],gradientUnits:"userSpaceOnUse"});"radialGradient"===r&&l&&!J(F.gradientUnits)&&(m=F,F=A(F,d.getRadialAttr(l,m),{gradientUnits:"userSpaceOnUse"}));y(F,function(a,p){"id"!==p&&u.push(p,a)});y(M,function(a){u.push(a)});u=u.join(",");if(K[u])n=K[u].attr("id");else{F.id=n=V();var c=K[u]=d.createElement(r).attr(F).add(d.defs);c.radAttr=m;c.stops=[];M.forEach(function(a){0===a[1].indexOf("rgba")?(h=I.parse(a[1]),f=h.get("rgb"),b=h.get("a")):(f=a[1],b=1);a=d.createElement("stop").attr({offset:a[0],
"stop-color":f,"stop-opacity":b}).add(c);c.stops.push(a)})}q="url("+d.url+"#"+n+")";p.setAttribute(t,q);p.gradient=u;a.toString=function(){return q}}})};e.prototype.css=function(a){var t=this.styles,p={},c=this.element,g=["textOutline","textOverflow","width"],h="",F=!t;a&&a.color&&(a.fill=a.color);t&&y(a,function(a,c){t&&t[c]!==a&&(p[c]=a,F=!0)});if(F){t&&(a=m(t,p));if(a)if(null===a.width||"auto"===a.width)delete this.textWidth;else if("text"===c.nodeName.toLowerCase()&&a.width)var r=this.textWidth=
P(a.width);this.styles=a;r&&!d&&this.renderer.forExport&&delete a.width;if(c.namespaceURI===this.SVG_NS){var K=function(a,p){return"-"+p.toLowerCase()};y(a,function(a,p){-1===g.indexOf(p)&&(h+=p.replace(/([A-Z])/g,K)+":"+a+";")});h&&N(c,"style",h)}else n(c,a);this.added&&("text"===this.element.nodeName&&this.renderer.buildText(this),a&&a.textOutline&&this.applyTextOutline(a.textOutline))}return this};e.prototype.dashstyleSetter=function(a){var t=this["stroke-width"];"inherit"===t&&(t=1);if(a=a&&a.toLowerCase()){var p=
a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(a=p.length;a--;)p[a]=""+P(p[a])*L(t,NaN);a=p.join(",").replace(/NaN/g,"none");this.element.setAttribute("stroke-dasharray",a)}};e.prototype.destroy=function(){var a=this,t=a.element||{},p=a.renderer,c=t.ownerSVGElement,g=p.isSVG&&"SPAN"===t.nodeName&&a.parentGroup||
void 0;t.onclick=t.onmouseout=t.onmouseover=t.onmousemove=t.point=null;x(a);if(a.clipPath&&c){var d=a.clipPath;[].forEach.call(c.querySelectorAll("[clip-path],[CLIP-PATH]"),function(a){-1<a.getAttribute("clip-path").indexOf(d.element.id)&&a.removeAttribute("clip-path")});a.clipPath=d.destroy()}if(a.stops){for(c=0;c<a.stops.length;c++)a.stops[c].destroy();a.stops.length=0;a.stops=void 0}a.safeRemoveChild(t);for(p.styledMode||a.destroyShadows();g&&g.div&&0===g.div.childNodes.length;)t=g.parentGroup,
a.safeRemoveChild(g.div),delete g.div,g=t;a.alignTo&&E(p.alignedObjects,a);y(a,function(p,c){a[c]&&a[c].parentGroup===a&&a[c].destroy&&a[c].destroy();delete a[c]})};e.prototype.destroyShadows=function(){(this.shadows||[]).forEach(function(a){this.safeRemoveChild(a)},this);this.shadows=void 0};e.prototype.destroyTextPath=function(a,c){var p=a.getElementsByTagName("text")[0];if(p){if(p.removeAttribute("dx"),p.removeAttribute("dy"),c.element.setAttribute("id",""),this.textPathWrapper&&p.getElementsByTagName("textPath").length){for(a=
this.textPathWrapper.element.childNodes;a.length;)p.appendChild(a[0]);p.removeChild(this.textPathWrapper.element)}}else if(a.getAttribute("dx")||a.getAttribute("dy"))a.removeAttribute("dx"),a.removeAttribute("dy");this.textPathWrapper&&(this.textPathWrapper=this.textPathWrapper.destroy())};e.prototype.dSetter=function(a,c,p){g(a)&&("string"===typeof a[0]&&(a=this.renderer.pathToSegments(a)),this.pathArray=a,a=a.reduce(function(a,p,c){return p&&p.join?(c?a+" ":"")+p.join(" "):(p||"").toString()},""));
/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");this[c]!==a&&(p.setAttribute(c,a),this[c]=a)};e.prototype.fadeOut=function(a){var c=this;c.animate({opacity:0},{duration:L(a,150),complete:function(){c.attr({y:-9999}).hide()}})};e.prototype.fillSetter=function(a,c,p){"string"===typeof a?p.setAttribute(c,a):a&&this.complexColor(a,c,p)};e.prototype.getBBox=function(c,t){var p=this.renderer,g=this.element,d=this.styles,h=this.textStr,F=p.cache,r=p.cacheKeys,K=g.namespaceURI===this.SVG_NS;t=L(t,this.rotation,0);var A=
p.styledMode?g&&e.prototype.getStyle.call(g,"font-size"):d&&d.fontSize,f;if(J(h)){var b=h.toString();-1===b.indexOf("<")&&(b=b.replace(/[0-9]/g,"0"));b+=["",t,A,this.textWidth,d&&d.textOverflow,d&&d.fontWeight].join()}b&&!c&&(f=F[b]);if(!f){if(K||p.forExport){try{var y=this.fakeTS&&function(a){var p=g.querySelector(".highcharts-text-outline");p&&n(p,{display:a})};a(y)&&y("none");f=g.getBBox?m({},g.getBBox()):{width:g.offsetWidth,height:g.offsetHeight};a(y)&&y("")}catch(Y){""}if(!f||0>f.width)f={width:0,
height:0}}else f=this.htmlGetBBox();p.isSVG&&(c=f.width,p=f.height,K&&(f.height=p={"11px,17":14,"13px,20":16}[d&&d.fontSize+","+Math.round(p)]||p),t&&(d=t*w,f.width=Math.abs(p*Math.sin(d))+Math.abs(c*Math.cos(d)),f.height=Math.abs(p*Math.cos(d))+Math.abs(c*Math.sin(d))));if(b&&0<f.height){for(;250<r.length;)delete F[r.shift()];F[b]||r.push(b);F[b]=f}}return f};e.prototype.getStyle=function(a){return k.getComputedStyle(this.element||this,"").getPropertyValue(a)};e.prototype.hasClass=function(a){return-1!==
(""+this.attr("class")).split(" ").indexOf(a)};e.prototype.hide=function(a){a?this.attr({y:-9999}):this.attr({visibility:"hidden"});return this};e.prototype.htmlGetBBox=function(){return{height:0,width:0,x:0,y:0}};e.prototype.init=function(a,t){this.element="span"===t?u(t):v.createElementNS(this.SVG_NS,t);this.renderer=a;c(this,"afterInit")};e.prototype.invert=function(a){this.inverted=a;this.updateTransform();return this};e.prototype.on=function(a,c){var p=this.onEvents;if(p[a])p[a]();p[a]=l(this.element,
a,c);return this};e.prototype.opacitySetter=function(a,c,p){this.opacity=a=Number(Number(a).toFixed(3));p.setAttribute(c,a)};e.prototype.removeClass=function(a){return this.attr("class",(""+this.attr("class")).replace(r(a)?new RegExp("(^| )"+a+"( |$)"):a," ").replace(/ +/g," ").trim())};e.prototype.removeTextOutline=function(){var a=this.element.querySelector("tspan.highcharts-text-outline");a&&this.safeRemoveChild(a)};e.prototype.safeRemoveChild=function(a){var c=a.parentNode;c&&c.removeChild(a)};
e.prototype.setRadialReference=function(a){var c=this.element.gradient&&this.renderer.gradients[this.element.gradient];this.element.radialReference=a;c&&c.radAttr&&c.animate(this.renderer.getRadialAttr(a,c.radAttr));return this};e.prototype.setTextPath=function(a,c){var p=this.element,t=this.text?this.text.element:p,g={textAnchor:"text-anchor"},d=!1,F=this.textPathWrapper,r=!F;c=A(!0,{enabled:!0,attributes:{dy:-5,startOffset:"50%",textAnchor:"middle"}},c);var K=b.filterUserAttributes(c.attributes);
if(a&&c&&c.enabled){F&&null===F.element.parentNode?(r=!0,F=F.destroy()):F&&this.removeTextOutline.call(F.parentGroup);this.options&&this.options.padding&&(K.dx=-this.options.padding);F||(this.textPathWrapper=F=this.renderer.createElement("textPath"),d=!0);var m=F.element;(c=a.element.getAttribute("id"))||a.element.setAttribute("id",c=V());if(r)for(t.setAttribute("y",0),h(K.dx)&&t.setAttribute("x",-K.dx),a=[].slice.call(t.childNodes),r=0;r<a.length;r++){var l=a[r];l.nodeType!==Node.TEXT_NODE&&"tspan"!==
l.nodeName||m.appendChild(l)}d&&F&&F.add({element:t});m.setAttributeNS("http://www.w3.org/1999/xlink","href",this.renderer.url+"#"+c);J(K.dy)&&(m.parentNode.setAttribute("dy",K.dy),delete K.dy);J(K.dx)&&(m.parentNode.setAttribute("dx",K.dx),delete K.dx);y(K,function(a,p){m.setAttribute(g[p]||p,a)});p.removeAttribute("transform");this.removeTextOutline.call(F);this.text&&!this.renderer.styledMode&&this.attr({fill:"none","stroke-width":0});this.applyTextOutline=this.updateTransform=f}else F&&(delete this.updateTransform,
delete this.applyTextOutline,this.destroyTextPath(p,a),this.updateTransform(),this.options&&this.options.rotation&&this.applyTextOutline(this.options.style.textOutline));return this};e.prototype.shadow=function(a,c,p){var t=[],g=this.element,d=this.oldShadowOptions,h={color:H.neutralColor100,offsetX:1,offsetY:1,opacity:.15,width:3},r=!1,K;!0===a?K=h:"object"===typeof a&&(K=m(h,a));K&&(K&&d&&y(K,function(a,p){a!==d[p]&&(r=!0)}),r&&this.destroyShadows(),this.oldShadowOptions=K);if(!K)this.destroyShadows();
else if(!this.shadows){var A=K.opacity/K.width;var f=this.parentInverted?"translate(-1,-1)":"translate("+K.offsetX+", "+K.offsetY+")";for(h=1;h<=K.width;h++){var b=g.cloneNode(!1);var l=2*K.width+1-2*h;N(b,{stroke:a.color||H.neutralColor100,"stroke-opacity":A*h,"stroke-width":l,transform:f,fill:"none"});b.setAttribute("class",(b.getAttribute("class")||"")+" highcharts-shadow");p&&(N(b,"height",Math.max(N(b,"height")-l,0)),b.cutHeight=l);c?c.element.appendChild(b):g.parentNode&&g.parentNode.insertBefore(b,
g);t.push(b)}this.shadows=t}return this};e.prototype.show=function(a){return this.attr({visibility:a?"inherit":"visible"})};e.prototype.strokeSetter=function(a,c,p){this[c]=a;this.stroke&&this["stroke-width"]?(e.prototype.fillSetter.call(this,this.stroke,"stroke",p),p.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0):"stroke-width"===c&&0===a&&this.hasStroke?(p.removeAttribute("stroke"),this.hasStroke=!1):this.renderer.styledMode&&this["stroke-width"]&&(p.setAttribute("stroke-width",
this["stroke-width"]),this.hasStroke=!0)};e.prototype.strokeWidth=function(){if(!this.renderer.styledMode)return this["stroke-width"]||0;var a=this.getStyle("stroke-width"),c=0;if(a.indexOf("px")===a.length-2)c=P(a);else if(""!==a){var p=v.createElementNS(q,"rect");N(p,{width:a,"stroke-width":0});this.element.parentNode.appendChild(p);c=p.getBBox().width;p.parentNode.removeChild(p)}return c};e.prototype.symbolAttr=function(a){var c=this;"x y r start end width height innerR anchorX anchorY clockwise".split(" ").forEach(function(p){c[p]=
L(a[p],c[p])});c.attr({d:c.renderer.symbols[c.symbolName](c.x,c.y,c.width,c.height,c)})};e.prototype.textSetter=function(a){a!==this.textStr&&(delete this.textPxLength,this.textStr=a,this.added&&this.renderer.buildText(this))};e.prototype.titleSetter=function(a){var c=this.element,p=c.getElementsByTagName("title")[0]||v.createElementNS(this.SVG_NS,"title");c.insertBefore?c.insertBefore(p,c.firstChild):c.appendChild(p);p.textContent=String(L(a,"")).replace(/<[^>]*>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,
">")};e.prototype.toFront=function(){var a=this.element;a.parentNode.appendChild(a);return this};e.prototype.translate=function(a,c){return this.attr({translateX:a,translateY:c})};e.prototype.updateShadows=function(a,c,p){var t=this.shadows;if(t)for(var g=t.length;g--;)p.call(t[g],"height"===a?Math.max(c-(t[g].cutHeight||0),0):"d"===a?this.d:c,a,t[g])};e.prototype.updateTransform=function(){var a=this.scaleX,c=this.scaleY,p=this.inverted,g=this.rotation,d=this.matrix,h=this.element,F=this.translateX||
0,r=this.translateY||0;p&&(F+=this.width,r+=this.height);F=["translate("+F+","+r+")"];J(d)&&F.push("matrix("+d.join(",")+")");p?F.push("rotate(90) scale(-1,1)"):g&&F.push("rotate("+g+" "+L(this.rotationOriginX,h.getAttribute("x"),0)+" "+L(this.rotationOriginY,h.getAttribute("y")||0)+")");(J(a)||J(c))&&F.push("scale("+L(a,1)+" "+L(c,1)+")");F.length&&h.setAttribute("transform",F.join(" "))};e.prototype.visibilitySetter=function(a,c,p){"inherit"===a?p.removeAttribute(c):this[c]!==a&&p.setAttribute(c,
a);this[c]=a};e.prototype.xGetter=function(a){"circle"===this.element.nodeName&&("x"===a?a="cx":"y"===a&&(a="cy"));return this._defaultGetter(a)};e.prototype.zIndexSetter=function(a,c){var p=this.renderer,g=this.parentGroup,t=(g||p).element||p.box,d=this.element;p=t===p.box;var h=!1;var r=this.added;var K;J(a)?(d.setAttribute("data-z-index",a),a=+a,this[c]===a&&(r=!1)):J(this[c])&&d.removeAttribute("data-z-index");this[c]=a;if(r){(a=this.zIndex)&&g&&(g.handleZ=!0);c=t.childNodes;for(K=c.length-1;0<=
K&&!h;K--){g=c[K];r=g.getAttribute("data-z-index");var m=!J(r);if(g!==d)if(0>a&&m&&!p&&!K)t.insertBefore(d,c[K]),h=!0;else if(P(r)<=a||m&&(!J(a)||0<=a))t.insertBefore(d,c[K+1]||null),h=!0}h||(t.insertBefore(d,c[p?3:0]||null),h=!0)}return h};return e}();e.prototype["stroke-widthSetter"]=e.prototype.strokeSetter;e.prototype.yGetter=e.prototype.xGetter;e.prototype.matrixSetter=e.prototype.rotationOriginXSetter=e.prototype.rotationOriginYSetter=e.prototype.rotationSetter=e.prototype.scaleXSetter=e.prototype.scaleYSetter=
e.prototype.translateXSetter=e.prototype.translateYSetter=e.prototype.verticalAlignSetter=function(a,c){this[c]=a;this.doTransform=!0};"";return e});O(e,"Core/Renderer/SVG/SVGLabel.js",[e["Core/Renderer/SVG/SVGElement.js"],e["Core/Utilities.js"]],function(e,b){function D(b,f){C(b)?b!==this[f]&&(this[f]=b,this.updateTextPadding()):this[f]=void 0}var z=this&&this.__extends||function(){var b=function(f,d){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,
b){for(var f in b)b.hasOwnProperty(f)&&(d[f]=b[f])};return b(f,d)};return function(f,d){function q(){this.constructor=f}b(f,d);f.prototype=null===d?Object.create(d):(q.prototype=d.prototype,new q)}}(),H=b.defined,G=b.extend,C=b.isNumber,B=b.merge,x=b.pick,w=b.removeEvent;return function(b){function f(d,q,k,l,e,u,n,v,E,m){var c=b.call(this)||this;c.paddingSetter=D;c.paddingLeftSetter=D;c.paddingRightSetter=D;c.init(d,"g");c.textStr=q;c.x=k;c.y=l;c.anchorX=u;c.anchorY=n;c.baseline=E;c.className=m;"button"!==
m&&c.addClass("highcharts-label");m&&c.addClass("highcharts-"+m);c.text=d.text("",0,0,v).attr({zIndex:1});if("string"===typeof e){var g=/^url\((.*?)\)$/.test(e);if(c.renderer.symbols[e]||g)c.symbolKey=e}c.bBox=f.emptyBBox;c.padding=3;c.baselineOffset=0;c.needsBox=d.styledMode||g;c.deferredAttr={};c.alignFactor=0;return c}z(f,b);f.prototype.alignSetter=function(d){d={left:0,center:.5,right:1}[d];d!==this.alignFactor&&(this.alignFactor=d,this.bBox&&C(this.xSetting)&&this.attr({x:this.xSetting}))};f.prototype.anchorXSetter=
function(d,b){this.anchorX=d;this.boxAttr(b,Math.round(d)-this.getCrispAdjust()-this.xSetting)};f.prototype.anchorYSetter=function(d,b){this.anchorY=d;this.boxAttr(b,d-this.ySetting)};f.prototype.boxAttr=function(d,b){this.box?this.box.attr(d,b):this.deferredAttr[d]=b};f.prototype.css=function(d){if(d){var b={},k=void 0;d=B(d);f.textProps.forEach(function(f){"undefined"!==typeof d[f]&&(b[f]=d[f],delete d[f])});this.text.css(b);k="width"in b;"fontSize"in b||"fontWeight"in b?this.updateTextPadding():
k&&this.updateBoxSize()}return e.prototype.css.call(this,d)};f.prototype.destroy=function(){w(this.element,"mouseenter");w(this.element,"mouseleave");this.text&&this.text.destroy();this.box&&(this.box=this.box.destroy());e.prototype.destroy.call(this)};f.prototype.fillSetter=function(d,b){d&&(this.needsBox=!0);this.fill=d;this.boxAttr(b,d)};f.prototype.getBBox=function(){this.textStr&&0===this.bBox.width&&0===this.bBox.height&&this.updateBoxSize();var d=this.padding,b=x(this.paddingLeft,d);return{width:this.width,
height:this.height,x:this.bBox.x-b,y:this.bBox.y-d}};f.prototype.getCrispAdjust=function(){return this.renderer.styledMode&&this.box?this.box.strokeWidth()%2/2:(this["stroke-width"]?parseInt(this["stroke-width"],10):0)%2/2};f.prototype.heightSetter=function(d){this.heightSetting=d};f.prototype.on=function(d,b){var f=this,l=f.text,q=l&&"SPAN"===l.element.tagName?l:void 0;if(q){var u=function(l){("mouseenter"===d||"mouseleave"===d)&&l.relatedTarget instanceof Element&&(f.element.compareDocumentPosition(l.relatedTarget)&
Node.DOCUMENT_POSITION_CONTAINED_BY||q.element.compareDocumentPosition(l.relatedTarget)&Node.DOCUMENT_POSITION_CONTAINED_BY)||b.call(f.element,l)};q.on(d,u)}e.prototype.on.call(f,d,u||b);return f};f.prototype.onAdd=function(){var d=this.textStr;this.text.add(this);this.attr({text:H(d)?d:"",x:this.x,y:this.y});this.box&&H(this.anchorX)&&this.attr({anchorX:this.anchorX,anchorY:this.anchorY})};f.prototype.rSetter=function(d,b){this.boxAttr(b,d)};f.prototype.shadow=function(d){d&&!this.renderer.styledMode&&
(this.updateBoxSize(),this.box&&this.box.shadow(d));return this};f.prototype.strokeSetter=function(d,b){this.stroke=d;this.boxAttr(b,d)};f.prototype["stroke-widthSetter"]=function(d,b){d&&(this.needsBox=!0);this["stroke-width"]=d;this.boxAttr(b,d)};f.prototype["text-alignSetter"]=function(d){this.textAlign=d};f.prototype.textSetter=function(d){"undefined"!==typeof d&&this.text.attr({text:d});this.updateTextPadding()};f.prototype.updateBoxSize=function(){var d=this.text.element.style,b={},e=this.padding,
l=this.bBox=C(this.widthSetting)&&C(this.heightSetting)&&!this.textAlign||!H(this.text.textStr)?f.emptyBBox:this.text.getBBox();this.width=this.getPaddedWidth();this.height=(this.heightSetting||l.height||0)+2*e;this.baselineOffset=e+Math.min(this.renderer.fontMetrics(d&&d.fontSize,this.text).b,l.height||Infinity);this.needsBox&&(this.box||(d=this.box=this.symbolKey?this.renderer.symbol(this.symbolKey):this.renderer.rect(),d.addClass(("button"===this.className?"":"highcharts-label-box")+(this.className?
" highcharts-"+this.className+"-box":"")),d.add(this)),d=this.getCrispAdjust(),b.x=d,b.y=(this.baseline?-this.baselineOffset:0)+d,b.width=Math.round(this.width),b.height=Math.round(this.height),this.box.attr(G(b,this.deferredAttr)),this.deferredAttr={})};f.prototype.updateTextPadding=function(){var d=this.text;this.updateBoxSize();var b=this.baseline?0:this.baselineOffset,f=x(this.paddingLeft,this.padding);H(this.widthSetting)&&this.bBox&&("center"===this.textAlign||"right"===this.textAlign)&&(f+=
{center:.5,right:1}[this.textAlign]*(this.widthSetting-this.bBox.width));if(f!==d.x||b!==d.y)d.attr("x",f),d.hasBoxWidthChanged&&(this.bBox=d.getBBox(!0)),"undefined"!==typeof b&&d.attr("y",b);d.x=f;d.y=b};f.prototype.widthSetter=function(d){this.widthSetting=C(d)?d:void 0};f.prototype.getPaddedWidth=function(){var d=this.padding,b=x(this.paddingLeft,d);d=x(this.paddingRight,d);return(this.widthSetting||this.bBox.width||0)+b+d};f.prototype.xSetter=function(d){this.x=d;this.alignFactor&&(d-=this.alignFactor*
this.getPaddedWidth(),this["forceAnimate:x"]=!0);this.xSetting=Math.round(d);this.attr("translateX",this.xSetting)};f.prototype.ySetter=function(d){this.ySetting=this.y=Math.round(d);this.attr("translateY",this.ySetting)};f.emptyBBox={width:0,height:0,x:0,y:0};f.textProps="color direction fontFamily fontSize fontStyle fontWeight lineHeight textAlign textDecoration textOutline textOverflow width".split(" ");return f}(e)});O(e,"Core/Renderer/SVG/TextBuilder.js",[e["Core/Globals.js"],e["Core/Utilities.js"],
e["Core/Renderer/HTML/AST.js"]],function(e,b,I){var D=e.doc,H=e.SVG_NS,G=b.attr,C=b.isString,B=b.objectEach,x=b.pick;return function(){function b(b){var f=b.styles;this.renderer=b.renderer;this.svgElement=b;this.width=b.textWidth;this.textLineHeight=f&&f.lineHeight;this.textOutline=f&&f.textOutline;this.ellipsis=!(!f||"ellipsis"!==f.textOverflow);this.noWrap=!(!f||"nowrap"!==f.whiteSpace);this.fontSize=f&&f.fontSize}b.prototype.buildSVG=function(){var b=this.svgElement,f=b.element,d=b.renderer,e=
x(b.textStr,"").toString(),k=-1!==e.indexOf("<"),l=f.childNodes,N=l.length;d=this.width&&!b.added&&d.box;var u=/<br.*?>/g;var n=[e,this.ellipsis,this.noWrap,this.textLineHeight,this.textOutline,this.fontSize,this.width].join();if(n!==b.textCache){b.textCache=n;for(delete b.actualWidth;N--;)f.removeChild(l[N]);k||this.ellipsis||this.width||-1!==e.indexOf(" ")&&(!this.noWrap||u.test(e))?""!==e&&(d&&d.appendChild(f),e=new I(e),this.modifyTree(e.nodes),e.addToDOM(b.element),this.modifyDOM(),this.ellipsis&&
-1!==(f.textContent||"").indexOf("\u2026")&&b.attr("title",this.unescapeEntities(b.textStr||"",["&lt;","&gt;"])),d&&d.removeChild(f)):f.appendChild(D.createTextNode(this.unescapeEntities(e)));C(this.textOutline)&&b.applyTextOutline&&b.applyTextOutline(this.textOutline)}};b.prototype.modifyDOM=function(){var b=this,f=this.svgElement,d=G(f.element,"x");[].forEach.call(f.element.querySelectorAll("tspan.highcharts-br"),function(f){f.nextSibling&&f.previousSibling&&G(f,{dy:b.getLineHeight(f.nextSibling),
x:d})});var e=this.width||0;if(e){var k=function(l,u){var n=l.textContent||"",k=n.replace(/([^\^])-/g,"$1- ").split(" "),q=!b.noWrap&&(1<k.length||1<f.element.childNodes.length),m=b.getLineHeight(u),c=0,g=f.actualWidth;if(b.ellipsis)n&&b.truncate(l,n,void 0,0,Math.max(0,e-parseInt(b.fontSize||12,10)),function(a,c){return a.substring(0,c)+"\u2026"});else if(q){n=[];for(q=[];u.firstChild&&u.firstChild!==l;)q.push(u.firstChild),u.removeChild(u.firstChild);for(;k.length;)k.length&&!b.noWrap&&0<c&&(n.push(l.textContent||
""),l.textContent=k.join(" ").replace(/- /g,"-")),b.truncate(l,void 0,k,0===c?g||0:0,e,function(a,c){return k.slice(0,c).join(" ").replace(/- /g,"-")}),g=f.actualWidth,c++;q.forEach(function(a){u.insertBefore(a,l)});n.forEach(function(a){u.insertBefore(D.createTextNode(a),l);a=D.createElementNS(H,"tspan");a.textContent="\u200b";G(a,{dy:m,x:d});u.insertBefore(a,l)})}},l=function(d){[].slice.call(d.childNodes).forEach(function(b){b.nodeType===Node.TEXT_NODE?k(b,d):(-1!==b.className.baseVal.indexOf("highcharts-br")&&
(f.actualWidth=0),l(b))})};l(f.element)}};b.prototype.getLineHeight=function(b){var f;b=b.nodeType===Node.TEXT_NODE?b.parentElement:b;this.renderer.styledMode||(f=b&&/(px|em)$/.test(b.style.fontSize)?b.style.fontSize:this.fontSize||this.renderer.style.fontSize||12);return this.textLineHeight?parseInt(this.textLineHeight.toString(),10):this.renderer.fontMetrics(f,b||this.svgElement.element).h};b.prototype.modifyTree=function(b){var f=this,d=function(e,k){var l=e.tagName,q=f.renderer.styledMode,u=e.attributes||
{};if("b"===l||"strong"===l)q?u["class"]="highcharts-strong":u.style="font-weight:bold;"+(u.style||"");else if("i"===l||"em"===l)q?u["class"]="highcharts-emphasized":u.style="font-style:italic;"+(u.style||"");C(u.style)&&(u.style=u.style.replace(/(;| |^)color([ :])/,"$1fill$2"));"br"===l&&(u["class"]="highcharts-br",e.textContent="\u200b",(k=b[k+1])&&k.textContent&&(k.textContent=k.textContent.replace(/^ +/gm,"")));"#text"!==l&&"a"!==l&&(e.tagName="tspan");e.attributes=u;e.children&&e.children.filter(function(d){return"#text"!==
d.tagName}).forEach(d)};for(b.forEach(d);b[0]&&"tspan"===b[0].tagName&&!b[0].children;)b.splice(0,1)};b.prototype.truncate=function(b,f,d,e,k,l){var q=this.svgElement,u=q.renderer,n=q.rotation,J=[],E=d?1:0,m=(f||d||"").length,c=m,g,a=function(a,c){c=c||a;var g=b.parentNode;if(g&&"undefined"===typeof J[c])if(g.getSubStringLength)try{J[c]=e+g.getSubStringLength(0,d?c+1:c)}catch(L){""}else u.getSpanWidth&&(b.textContent=l(f||d,a),J[c]=e+u.getSpanWidth(q,b));return J[c]};q.rotation=0;var h=a(b.textContent.length);
if(e+h>k){for(;E<=m;)c=Math.ceil((E+m)/2),d&&(g=l(d,c)),h=a(c,g&&g.length-1),E===m?E=m+1:h>k?m=c-1:E=c;0===m?b.textContent="":f&&m===f.length-1||(b.textContent=g||l(f||d,c))}d&&d.splice(0,c);q.actualWidth=h;q.rotation=n};b.prototype.unescapeEntities=function(b,f){B(this.renderer.escapes,function(d,e){f&&-1!==f.indexOf(d)||(b=b.toString().replace(new RegExp(d,"g"),e))});return b};return b}()});O(e,"Core/Renderer/SVG/SVGRenderer.js",[e["Core/Color/Color.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],
e["Core/Renderer/SVG/SVGElement.js"],e["Core/Renderer/SVG/SVGLabel.js"],e["Core/Renderer/HTML/AST.js"],e["Core/Renderer/SVG/TextBuilder.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C,B){var x=B.addEvent,w=B.attr,v=B.createElement,f=B.css,d=B.defined,q=B.destroyObjectProperties,k=B.extend,l=B.isArray,N=B.isNumber,u=B.isObject,n=B.isString,J=B.merge,E=B.pick,m=B.pInt,c=B.uniqueKey,g=b.charts,a=b.deg2rad,h=b.doc,r=b.isFirefox,A=b.isMS,y=b.isWebKit,L=b.noop,P=b.SVG_NS,R=b.symbolSizes,V=b.win,Q;B=
function(){function t(a,c,g,t,d,h,r){this.width=this.url=this.style=this.isSVG=this.imgCount=this.height=this.gradients=this.globalAnimation=this.defs=this.chartIndex=this.cacheKeys=this.cache=this.boxWrapper=this.box=this.alignedObjects=void 0;this.init(a,c,g,t,d,h,r)}t.prototype.init=function(a,c,g,t,d,b,K){var p=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"});K||p.css(this.getStyle(t));t=p.element;a.appendChild(t);w(a,"dir","ltr");-1===a.innerHTML.indexOf("xmlns")&&w(t,
"xmlns",this.SVG_NS);this.isSVG=!0;this.box=t;this.boxWrapper=p;this.alignedObjects=[];this.url=this.getReferenceURL();this.createElement("desc").add().element.appendChild(h.createTextNode("Created with Highcharts 9.1.0"));this.defs=this.createElement("defs").add();this.allowHTML=b;this.forExport=d;this.styledMode=K;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(c,g,!1);var F;r&&a.getBoundingClientRect&&(c=function(){f(a,{left:0,top:0});F=a.getBoundingClientRect();
f(a,{left:Math.ceil(F.left)-F.left+"px",top:Math.ceil(F.top)-F.top+"px"})},c(),this.unSubPixelFix=x(V,"resize",c))};t.prototype.definition=function(a){return(new G([a])).addToDOM(this.defs.element)};t.prototype.getReferenceURL=function(){if((r||y)&&h.getElementsByTagName("base").length){if(!d(Q)){var a=c();a=(new G([{tagName:"svg",attributes:{width:8,height:8},children:[{tagName:"defs",children:[{tagName:"clipPath",attributes:{id:a},children:[{tagName:"rect",attributes:{width:4,height:4}}]}]},{tagName:"rect",
attributes:{id:"hitme",width:8,height:8,"clip-path":"url(#"+a+")",fill:"rgba(0,0,0,0.001)"}}]}])).addToDOM(h.body);f(a,{position:"fixed",top:0,left:0,zIndex:9E5});var g=h.elementFromPoint(6,6);Q="hitme"===(g&&g.id);h.body.removeChild(a)}if(Q)return V.location.href.split("#")[0].replace(/<[^>]*>/g,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20")}return""};t.prototype.getStyle=function(a){return this.style=k({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},
a)};t.prototype.setStyle=function(a){this.boxWrapper.css(this.getStyle(a))};t.prototype.isHidden=function(){return!this.boxWrapper.getBBox().width};t.prototype.destroy=function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();q(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy());this.unSubPixelFix&&this.unSubPixelFix();return this.alignedObjects=null};t.prototype.createElement=function(a){var c=new this.Element;c.init(this,a);return c};t.prototype.getRadialAttr=
function(a,c){return{cx:a[0]-a[2]/2+(c.cx||0)*a[2],cy:a[1]-a[2]/2+(c.cy||0)*a[2],r:(c.r||0)*a[2]}};t.prototype.buildText=function(a){(new C(a)).buildSVG()};t.prototype.getContrast=function(a){a=e.parse(a).rgba;a[0]*=1;a[1]*=1.2;a[2]*=.5;return 459<a[0]+a[1]+a[2]?"#000000":"#FFFFFF"};t.prototype.button=function(a,c,g,t,d,h,r,b,m,f){var p=this.label(a,c,g,m,void 0,void 0,f,void 0,"button"),F=0,K=this.styledMode,y=d?J(d):{};a=y&&y.style||{};y=G.filterUserAttributes(y);p.attr(J({padding:8,r:2},y));if(!K){y=
J({fill:I.neutralColor3,stroke:I.neutralColor20,"stroke-width":1,style:{color:I.neutralColor80,cursor:"pointer",fontWeight:"normal"}},{style:a},y);var l=y.style;delete y.style;h=J(y,{fill:I.neutralColor10},G.filterUserAttributes(h||{}));var S=h.style;delete h.style;r=J(y,{fill:I.highlightColor10,style:{color:I.neutralColor100,fontWeight:"bold"}},G.filterUserAttributes(r||{}));var u=r.style;delete r.style;b=J(y,{style:{color:I.neutralColor20}},G.filterUserAttributes(b||{}));var n=b.style;delete b.style}x(p.element,
A?"mouseover":"mouseenter",function(){3!==F&&p.setState(1)});x(p.element,A?"mouseout":"mouseleave",function(){3!==F&&p.setState(F)});p.setState=function(a){1!==a&&(p.state=F=a);p.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/).addClass("highcharts-button-"+["normal","hover","pressed","disabled"][a||0]);K||p.attr([y,h,r,b][a||0]).css([l,S,u,n][a||0])};K||p.attr(y).css(k({cursor:"default"},l));return p.on("touchstart",function(a){return a.stopPropagation()}).on("click",function(a){3!==
F&&t.call(p,a)})};t.prototype.crispLine=function(a,c,g){void 0===g&&(g="round");var p=a[0],t=a[1];p[1]===t[1]&&(p[1]=t[1]=Math[g](p[1])-c%2/2);p[2]===t[2]&&(p[2]=t[2]=Math[g](p[2])+c%2/2);return a};t.prototype.path=function(a){var c=this.styledMode?{}:{fill:"none"};l(a)?c.d=a:u(a)&&k(c,a);return this.createElement("path").attr(c)};t.prototype.circle=function(a,c,g){a=u(a)?a:"undefined"===typeof a?{}:{x:a,y:c,r:g};c=this.createElement("circle");c.xSetter=c.ySetter=function(a,c,p){p.setAttribute("c"+
c,a)};return c.attr(a)};t.prototype.arc=function(a,c,g,t,d,h){u(a)?(t=a,c=t.y,g=t.r,a=t.x):t={innerR:t,start:d,end:h};a=this.symbol("arc",a,c,g,g,t);a.r=g;return a};t.prototype.rect=function(a,c,g,t,d,h){d=u(a)?a.r:d;var p=this.createElement("rect");a=u(a)?a:"undefined"===typeof a?{}:{x:a,y:c,width:Math.max(g,0),height:Math.max(t,0)};this.styledMode||("undefined"!==typeof h&&(a["stroke-width"]=h,a=p.crisp(a)),a.fill="none");d&&(a.r=d);p.rSetter=function(a,c,g){p.r=a;w(g,{rx:a,ry:a})};p.rGetter=function(){return p.r||
0};return p.attr(a)};t.prototype.setSize=function(a,c,g){this.width=a;this.height=c;this.boxWrapper.animate({width:a,height:c},{step:function(){this.attr({viewBox:"0 0 "+this.attr("width")+" "+this.attr("height")})},duration:E(g,!0)?void 0:0});this.alignElements()};t.prototype.g=function(a){var c=this.createElement("g");return a?c.attr({"class":"highcharts-"+a}):c};t.prototype.image=function(a,c,g,t,d,h){var p={preserveAspectRatio:"none"},r=function(a,c){a.setAttributeNS?a.setAttributeNS("http://www.w3.org/1999/xlink",
"href",c):a.setAttribute("hc-svg-href",c)},F=function(c){r(b.element,a);h.call(b,c)};1<arguments.length&&k(p,{x:c,y:g,width:t,height:d});var b=this.createElement("image").attr(p);h?(r(b.element,"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),p=new V.Image,x(p,"load",F),p.src=a,p.complete&&F({})):r(b.element,a);return b};t.prototype.symbol=function(a,c,t,r,F,b){var p=this,m=/^url\((.*?)\)$/,A=m.test(a),y=!A&&(this.symbols[a]?a:"circle"),l=y&&this.symbols[y],u;if(l){"number"===
typeof c&&(u=l.call(this.symbols,Math.round(c||0),Math.round(t||0),r||0,F||0,b));var n=this.path(u);p.styledMode||n.attr("fill","none");k(n,{symbolName:y,x:c,y:t,width:r,height:F});b&&k(n,b)}else if(A){var e=a.match(m)[1];n=this.image(e);n.imgwidth=E(R[e]&&R[e].width,b&&b.width);n.imgheight=E(R[e]&&R[e].height,b&&b.height);var S=function(){n.attr({width:n.width,height:n.height})};["width","height"].forEach(function(a){n[a+"Setter"]=function(a,c){var p=this["img"+c];this[c]=a;d(p)&&(b&&"within"===
b.backgroundSize&&this.width&&this.height&&(p=Math.round(p*Math.min(this.width/this.imgwidth,this.height/this.imgheight))),this.element&&this.element.setAttribute(c,p),this.alignByTranslate||(a=((this[c]||0)-p)/2,this.attr("width"===c?{translateX:a}:{translateY:a})))}});d(c)&&n.attr({x:c,y:t});n.isImg=!0;d(n.imgwidth)&&d(n.imgheight)?S():(n.attr({width:0,height:0}),v("img",{onload:function(){var a=g[p.chartIndex];0===this.width&&(f(this,{position:"absolute",top:"-999em"}),h.body.appendChild(this));
R[e]={width:this.width,height:this.height};n.imgwidth=this.width;n.imgheight=this.height;n.element&&S();this.parentNode&&this.parentNode.removeChild(this);p.imgCount--;if(!p.imgCount&&a&&!a.hasLoaded)a.onload()},src:e}),this.imgCount++)}return n};t.prototype.clipRect=function(a,g,t,d){var p=c()+"-",h=this.createElement("clipPath").attr({id:p}).add(this.defs);a=this.rect(a,g,t,d,0).add(h);a.id=p;a.clipPath=h;a.count=0;return a};t.prototype.text=function(a,c,g,t){var p={};if(t&&(this.allowHTML||!this.forExport))return this.html(a,
c,g);p.x=Math.round(c||0);g&&(p.y=Math.round(g));d(a)&&(p.text=a);a=this.createElement("text").attr(p);t||(a.xSetter=function(a,c,p){var g=p.getElementsByTagName("tspan"),t=p.getAttribute(c),d;for(d=0;d<g.length;d++){var h=g[d];h.getAttribute(c)===t&&h.setAttribute(c,a)}p.setAttribute(c,a)});return a};t.prototype.fontMetrics=function(a,c){a=!this.styledMode&&/px/.test(a)||!V.getComputedStyle?a||c&&c.style&&c.style.fontSize||this.style&&this.style.fontSize:c&&z.prototype.getStyle.call(c,"font-size");
a=/px/.test(a)?m(a):12;c=24>a?a+3:Math.round(1.2*a);return{h:c,b:Math.round(.8*c),f:a}};t.prototype.rotCorr=function(c,g,t){var p=c;g&&t&&(p=Math.max(p*Math.cos(g*a),4));return{x:-c/3*Math.sin(g*a),y:p}};t.prototype.pathToSegments=function(a){for(var c=[],g=[],p={A:8,C:7,H:2,L:3,M:3,Q:5,S:5,T:3,V:2},t=0;t<a.length;t++)n(g[0])&&N(a[t])&&g.length===p[g[0].toUpperCase()]&&a.splice(t,0,g[0].replace("M","L").replace("m","l")),"string"===typeof a[t]&&(g.length&&c.push(g.slice(0)),g.length=0),g.push(a[t]);
c.push(g.slice(0));return c};t.prototype.label=function(a,c,g,t,d,h,r,b,m){return new H(this,a,c,g,t,d,h,r,b,m)};t.prototype.alignElements=function(){this.alignedObjects.forEach(function(a){return a.align()})};return t}();B.prototype.Element=z;B.prototype.SVG_NS=P;B.prototype.draw=L;B.prototype.escapes={"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"};var M=function(a,c,g,d,h){h=h&&h.r||0;return[["M",a+h,c],["L",a+g-h,c],["C",a+g,c,a+g,c,a+g,c+h],["L",a+g,c+d-h],["C",a+g,c+d,a+g,c+d,a+
g-h,c+d],["L",a+h,c+d],["C",a,c+d,a,c+d,a,c+d-h],["L",a,c+h],["C",a,c,a,c,a+h,c]]};L=function(a,c,g,d,h){return h&&h.r?M(a,c,g,d,h):[["M",a,c],["L",a+g,c],["L",a+g,c+d],["L",a,c+d],["Z"]]};B.prototype.symbols={circle:function(a,c,g,d){return this.arc(a+g/2,c+d/2,g/2,d/2,{start:.5*Math.PI,end:2.5*Math.PI,open:!1})},rect:L,square:L,triangle:function(a,c,g,d){return[["M",a+g/2,c],["L",a+g,c+d],["L",a,c+d],["Z"]]},"triangle-down":function(a,c,g,d){return[["M",a,c],["L",a+g,c],["L",a+g/2,c+d],["Z"]]},
diamond:function(a,c,g,d){return[["M",a+g/2,c],["L",a+g,c+d/2],["L",a+g/2,c+d],["L",a,c+d/2],["Z"]]},arc:function(a,c,g,h,r){var t=[];if(r){var p=r.start||0,b=E(r.r,g);g=E(r.r,h||g);var m=(r.end||0)-.001;h=r.innerR;var f=E(r.open,.001>Math.abs((r.end||0)-p-2*Math.PI)),A=Math.cos(p),y=Math.sin(p),l=Math.cos(m),n=Math.sin(m);p=E(r.longArc,.001>m-p-Math.PI?0:1);t.push(["M",a+b*A,c+g*y],["A",b,g,0,p,E(r.clockwise,1),a+b*l,c+g*n]);d(h)&&t.push(f?["M",a+h*l,c+h*n]:["L",a+h*l,c+h*n],["A",h,h,0,p,d(r.clockwise)?
1-r.clockwise:0,a+h*A,c+h*y]);f||t.push(["Z"])}return t},callout:function(a,c,g,d,h){var p=Math.min(h&&h.r||0,g,d),t=p+6,r=h&&h.anchorX;h=h&&h.anchorY||0;var b=M(a,c,g,d,{r:p});if(!N(r))return b;a+r>=g?h>c+t&&h<c+d-t?b.splice(3,1,["L",a+g,h-6],["L",a+g+6,h],["L",a+g,h+6],["L",a+g,c+d-p]):b.splice(3,1,["L",a+g,d/2],["L",r,h],["L",a+g,d/2],["L",a+g,c+d-p]):0>=a+r?h>c+t&&h<c+d-t?b.splice(7,1,["L",a,h+6],["L",a-6,h],["L",a,h-6],["L",a,c+p]):b.splice(7,1,["L",a,d/2],["L",r,h],["L",a,d/2],["L",a,c+p]):
h&&h>d&&r>a+t&&r<a+g-t?b.splice(5,1,["L",r+6,c+d],["L",r,c+d+6],["L",r-6,c+d],["L",a+p,c+d]):h&&0>h&&r>a+t&&r<a+g-t&&b.splice(1,1,["L",r-6,c],["L",r,c-6],["L",r+6,c],["L",g-p,c]);return b}};b.SVGRenderer=B;b.Renderer=b.SVGRenderer;return b.Renderer});O(e,"Core/Renderer/HTML/HTMLElement.js",[e["Core/Globals.js"],e["Core/Renderer/SVG/SVGElement.js"],e["Core/Utilities.js"]],function(e,b,I){var D=e.isFirefox,H=e.isMS,G=e.isWebKit,C=e.win,B=I.css,x=I.defined,w=I.extend,v=I.pick,f=I.pInt;w(b.prototype,
{htmlCss:function(d){var b="SPAN"===this.element.tagName&&d&&"width"in d,f=v(b&&d.width,void 0);if(b){delete d.width;this.textWidth=f;var l=!0}d&&"ellipsis"===d.textOverflow&&(d.whiteSpace="nowrap",d.overflow="hidden");this.styles=w(this.styles,d);B(this.element,d);l&&this.htmlUpdateTransform();return this},htmlGetBBox:function(){var d=this.element;return{x:d.offsetLeft,y:d.offsetTop,width:d.offsetWidth,height:d.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var d=this.renderer,b=this.element,
e=this.translateX||0,l=this.translateY||0,N=this.x||0,u=this.y||0,n=this.textAlign||"left",J={left:0,center:.5,right:1}[n],E=this.styles;E=E&&E.whiteSpace;B(b,{marginLeft:e,marginTop:l});!d.styledMode&&this.shadows&&this.shadows.forEach(function(a){B(a,{marginLeft:e+1,marginTop:l+1})});this.inverted&&[].forEach.call(b.childNodes,function(a){d.invertChild(a,b)});if("SPAN"===b.tagName){var m=this.rotation,c=void 0;c=this.textWidth&&f(this.textWidth);var g=[m,n,b.innerHTML,this.textWidth,this.textAlign].join(),
a;(a=c!==this.oldTextWidth)&&!(a=c>this.oldTextWidth)&&((a=this.textPxLength)||(B(b,{width:"",whiteSpace:E||"nowrap"}),a=b.offsetWidth),a=a>c);a&&(/[ \-]/.test(b.textContent||b.innerText)||"ellipsis"===b.style.textOverflow)?(B(b,{width:c+"px",display:"block",whiteSpace:E||"normal"}),this.oldTextWidth=c,this.hasBoxWidthChanged=!0):this.hasBoxWidthChanged=!1;g!==this.cTT&&(c=d.fontMetrics(b.style.fontSize,b).b,!x(m)||m===(this.oldRotation||0)&&n===this.oldAlign||this.setSpanRotation(m,J,c),this.getSpanCorrection(!x(m)&&
this.textPxLength||b.offsetWidth,c,J,m,n));B(b,{left:N+(this.xCorr||0)+"px",top:u+(this.yCorr||0)+"px"});this.cTT=g;this.oldRotation=m;this.oldAlign=n}}else this.alignOnAdd=!0},setSpanRotation:function(d,b,f){var l={},e=H&&!/Edge/.test(C.navigator.userAgent)?"-ms-transform":G?"-webkit-transform":D?"MozTransform":C.opera?"-o-transform":void 0;e&&(l[e]=l.transform="rotate("+d+"deg)",l[e+(D?"Origin":"-origin")]=l.transformOrigin=100*b+"% "+f+"px",B(this.element,l))},getSpanCorrection:function(d,b,f){this.xCorr=
-d*f;this.yCorr=-b}});return b});O(e,"Core/Renderer/HTML/HTMLRenderer.js",[e["Core/Renderer/HTML/AST.js"],e["Core/Renderer/SVG/SVGElement.js"],e["Core/Renderer/SVG/SVGRenderer.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=z.attr,G=z.createElement,C=z.extend,B=z.pick;C(I.prototype,{html:function(x,w,v){var f=this.createElement("span"),d=f.element,q=f.renderer,k=q.isSVG,l=function(d,f){["opacity","visibility"].forEach(function(l){d[l+"Setter"]=function(n,e,m){var c=d.div?d.div.style:f;b.prototype[l+
"Setter"].call(this,n,e,m);c&&(c[e]=n)}});d.addedSetters=!0};f.textSetter=function(d){d!==this.textStr&&(delete this.bBox,delete this.oldTextWidth,e.setElementHTML(this.element,B(d,"")),this.textStr=d,f.doTransform=!0)};k&&l(f,f.element.style);f.xSetter=f.ySetter=f.alignSetter=f.rotationSetter=function(d,b){"align"===b?f.alignValue=f.textAlign=d:f[b]=d;f.doTransform=!0};f.afterSetters=function(){this.doTransform&&(this.htmlUpdateTransform(),this.doTransform=!1)};f.attr({text:x,x:Math.round(w),y:Math.round(v)}).css({position:"absolute"});
q.styledMode||f.css({fontFamily:this.style.fontFamily,fontSize:this.style.fontSize});d.style.whiteSpace="nowrap";f.css=f.htmlCss;k&&(f.add=function(b){var e=q.box.parentNode,n=[];if(this.parentGroup=b){var k=b.div;if(!k){for(;b;)n.push(b),b=b.parentGroup;n.reverse().forEach(function(d){function b(c,g){d[g]=c;"translateX"===g?a.left=c+"px":a.top=c+"px";d.doTransform=!0}var c=D(d.element,"class"),g=d.styles||{};k=d.div=d.div||G("div",c?{className:c}:void 0,{position:"absolute",left:(d.translateX||0)+
"px",top:(d.translateY||0)+"px",display:d.display,opacity:d.opacity,cursor:g.cursor,pointerEvents:g.pointerEvents},k||e);var a=k.style;C(d,{classSetter:function(a){return function(c){this.element.setAttribute("class",c);a.className=c}}(k),on:function(){n[0].div&&f.on.apply({element:n[0].div,onEvents:f.onEvents},arguments);return d},translateXSetter:b,translateYSetter:b});d.addedSetters||l(d)})}}else k=e;k.appendChild(d);f.added=!0;f.alignOnAdd&&f.htmlUpdateTransform();return f});return f}});return I});
O(e,"Core/Axis/Tick.js",[e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b,I){var D=b.deg2rad,H=I.clamp,G=I.correctFloat,C=I.defined,B=I.destroyObjectProperties,x=I.extend,w=I.fireEvent,v=I.isNumber,f=I.merge,d=I.objectEach,q=I.pick;"";I=function(){function b(d,b,f,e,k){this.isNewLabel=this.isNew=!0;this.axis=d;this.pos=b;this.type=f||"";this.parameters=k||{};this.tickmarkOffset=this.parameters.tickmarkOffset;this.options=this.parameters.options;w(this,"init");
f||e||this.addLabel()}b.prototype.addLabel=function(){var d=this,b=d.axis,f=b.options,n=b.chart,k=b.categories,E=b.logarithmic,m=b.names,c=d.pos,g=q(d.options&&d.options.labels,f.labels),a=b.tickPositions,h=c===a[0],r=c===a[a.length-1],A=d.label,y=(!g.step||1===g.step)&&1===b.tickInterval;a=a.info;var L,P;k=this.parameters.category||(k?q(k[c],m[c],c):c);E&&v(k)&&(k=G(E.lin2log(k)));if(b.dateTime&&a){var R=n.time.resolveDTLFormat(f.dateTimeLabelFormats[!f.grid&&a.higherRanks[c]||a.unitName]);var V=
R.main}d.isFirst=h;d.isLast=r;var Q={axis:b,chart:n,dateTimeLabelFormat:V,isFirst:h,isLast:r,pos:c,tick:d,tickPositionInfo:a,value:k};w(this,"labelFormat",Q);var M=function(a){return g.formatter?g.formatter.call(a,a):g.format?(a.text=b.defaultLabelFormatter.call(a),e.format(g.format,a,n)):b.defaultLabelFormatter.call(a,a)};f=M.call(Q,Q);if(P=R&&R.list)d.shortenLabel=function(){for(L=0;L<P.length;L++)if(x(Q,{dateTimeLabelFormat:P[L]}),A.attr({text:M.call(Q,Q)}),A.getBBox().width<b.getSlotWidth(d)-
2*g.padding)return;A.attr({text:""})};y&&b._addedPlotLB&&d.moveLabel(f,g);C(A)||d.movedLabel?A&&A.textStr!==f&&!y&&(!A.textWidth||g.style.width||A.styles.width||A.css({width:null}),A.attr({text:f}),A.textPxLength=A.getBBox().width):(d.label=A=d.createLabel({x:0,y:0},f,g),d.rotation=0)};b.prototype.createLabel=function(d,b,e){var n=this.axis,l=n.chart;if(d=C(b)&&e.enabled?l.renderer.text(b,d.x,d.y,e.useHTML).add(n.labelGroup):null)l.styledMode||d.css(f(e.style)),d.textPxLength=d.getBBox().width;return d};
b.prototype.destroy=function(){B(this,this.axis)};b.prototype.getPosition=function(d,b,f,e){var n=this.axis,l=n.chart,m=e&&l.oldChartHeight||l.chartHeight;d={x:d?G(n.translate(b+f,null,null,e)+n.transB):n.left+n.offset+(n.opposite?(e&&l.oldChartWidth||l.chartWidth)-n.right-n.left:0),y:d?m-n.bottom+n.offset-(n.opposite?n.height:0):G(m-n.translate(b+f,null,null,e)-n.transB)};d.y=H(d.y,-1E5,1E5);w(this,"afterGetPosition",{pos:d});return d};b.prototype.getLabelPosition=function(d,b,f,e,k,q,m,c){var g=
this.axis,a=g.transA,h=g.isLinked&&g.linkedParent?g.linkedParent.reversed:g.reversed,r=g.staggerLines,A=g.tickRotCorr||{x:0,y:0},y=k.y,n=e||g.reserveSpaceDefault?0:-g.labelOffset*("center"===g.labelAlign?.5:1),l={};C(y)||(y=0===g.side?f.rotation?-8:-f.getBBox().height:2===g.side?A.y+8:Math.cos(f.rotation*D)*(A.y-f.getBBox(!1,0).height/2));d=d+k.x+n+A.x-(q&&e?q*a*(h?-1:1):0);b=b+y-(q&&!e?q*a*(h?1:-1):0);r&&(f=m/(c||1)%r,g.opposite&&(f=r-f-1),b+=g.labelOffset/r*f);l.x=d;l.y=Math.round(b);w(this,"afterGetLabelPosition",
{pos:l,tickmarkOffset:q,index:m});return l};b.prototype.getLabelSize=function(){return this.label?this.label.getBBox()[this.axis.horiz?"height":"width"]:0};b.prototype.getMarkPath=function(d,b,f,e,k,q){return q.crispLine([["M",d,b],["L",d+(k?0:-f),b+(k?f:0)]],e)};b.prototype.handleOverflow=function(d){var b=this.axis,f=b.options.labels,e=d.x,l=b.chart.chartWidth,k=b.chart.spacing,m=q(b.labelLeft,Math.min(b.pos,k[3]));k=q(b.labelRight,Math.max(b.isRadial?0:b.pos+b.len,l-k[1]));var c=this.label,g=this.rotation,
a={left:0,center:.5,right:1}[b.labelAlign||c.attr("align")],h=c.getBBox().width,r=b.getSlotWidth(this),A=r,y=1,L,P={};if(g||"justify"!==f.overflow)0>g&&e-a*h<m?L=Math.round(e/Math.cos(g*D)-m):0<g&&e+a*h>k&&(L=Math.round((l-e)/Math.cos(g*D)));else if(l=e+(1-a)*h,e-a*h<m?A=d.x+A*(1-a)-m:l>k&&(A=k-d.x+A*a,y=-1),A=Math.min(r,A),A<r&&"center"===b.labelAlign&&(d.x+=y*(r-A-a*(r-Math.min(h,A)))),h>A||b.autoRotation&&(c.styles||{}).width)L=A;L&&(this.shortenLabel?this.shortenLabel():(P.width=Math.floor(L)+
"px",(f.style||{}).textOverflow||(P.textOverflow="ellipsis"),c.css(P)))};b.prototype.moveLabel=function(b,f){var e=this,n=e.label,l=!1,k=e.axis,m=k.reversed;n&&n.textStr===b?(e.movedLabel=n,l=!0,delete e.label):d(k.ticks,function(c){l||c.isNew||c===e||!c.label||c.label.textStr!==b||(e.movedLabel=c.label,l=!0,c.labelPos=e.movedLabel.xy,delete c.label)});if(!l&&(e.labelPos||n)){var c=e.labelPos||n.xy;n=k.horiz?m?0:k.width+k.left:c.x;k=k.horiz?c.y:m?k.width+k.left:0;e.movedLabel=e.createLabel({x:n,y:k},
b,f);e.movedLabel&&e.movedLabel.attr({opacity:0})}};b.prototype.render=function(d,b,f){var e=this.axis,l=e.horiz,k=this.pos,m=q(this.tickmarkOffset,e.tickmarkOffset);k=this.getPosition(l,k,m,b);m=k.x;var c=k.y;e=l&&m===e.pos+e.len||!l&&c===e.pos?-1:1;l=q(f,this.label&&this.label.newOpacity,1);f=q(f,1);this.isActive=!0;this.renderGridLine(b,f,e);this.renderMark(k,f,e);this.renderLabel(k,b,l,d);this.isNew=!1;w(this,"afterRender")};b.prototype.renderGridLine=function(d,b,f){var e=this.axis,l=e.options,
k=this.gridLine,m={},c=this.pos,g=this.type,a=q(this.tickmarkOffset,e.tickmarkOffset),h=e.chart.renderer,r=l.gridLineWidth,A=l.gridLineColor,y=l.gridLineDashStyle;"minor"===this.type&&(r=l.minorGridLineWidth,A=l.minorGridLineColor,y=l.minorGridLineDashStyle);k||(e.chart.styledMode||(m.stroke=A,m["stroke-width"]=r||0,m.dashstyle=y),g||(m.zIndex=1),d&&(b=0),this.gridLine=k=h.path().attr(m).addClass("highcharts-"+(g?g+"-":"")+"grid-line").add(e.gridGroup));if(k&&(f=e.getPlotLinePath({value:c+a,lineWidth:k.strokeWidth()*
f,force:"pass",old:d})))k[d||this.isNew?"attr":"animate"]({d:f,opacity:b})};b.prototype.renderMark=function(d,b,f){var e=this.axis,l=e.options,k=e.chart.renderer,m=this.type,c=e.tickSize(m?m+"Tick":"tick"),g=this.mark,a=!g,h=d.x;d=d.y;var r=q(l["minor"!==m?"tickWidth":"minorTickWidth"],!m&&e.isXAxis?1:0);l=l["minor"!==m?"tickColor":"minorTickColor"];c&&(e.opposite&&(c[0]=-c[0]),a&&(this.mark=g=k.path().addClass("highcharts-"+(m?m+"-":"")+"tick").add(e.axisGroup),e.chart.styledMode||g.attr({stroke:l,
"stroke-width":r})),g[a?"attr":"animate"]({d:this.getMarkPath(h,d,c[0],g.strokeWidth()*f,e.horiz,k),opacity:b}))};b.prototype.renderLabel=function(d,b,f,e){var l=this.axis,n=l.horiz,m=l.options,c=this.label,g=m.labels,a=g.step;l=q(this.tickmarkOffset,l.tickmarkOffset);var h=!0,r=d.x;d=d.y;c&&v(r)&&(c.xy=d=this.getLabelPosition(r,d,c,n,g,l,e,a),this.isFirst&&!this.isLast&&!m.showFirstLabel||this.isLast&&!this.isFirst&&!m.showLastLabel?h=!1:!n||g.step||g.rotation||b||0===f||this.handleOverflow(d),a&&
e%a&&(h=!1),h&&v(d.y)?(d.opacity=f,c[this.isNewLabel?"attr":"animate"](d),this.isNewLabel=!1):(c.attr("y",-9999),this.isNewLabel=!0))};b.prototype.replaceMovedLabel=function(){var d=this.label,b=this.axis,f=b.reversed;if(d&&!this.isNew){var e=b.horiz?f?b.left:b.width+b.left:d.xy.x;f=b.horiz?d.xy.y:f?b.width+b.top:b.top;d.animate({x:e,y:f,opacity:0},void 0,d.destroy);delete this.label}b.isDirty=!0;this.label=this.movedLabel;delete this.movedLabel};return b}();b.Tick=I;return b.Tick});O(e,"Core/Axis/Axis.js",
[e["Core/Animation/AnimationUtilities.js"],e["Core/Color/Color.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Options.js"],e["Core/Axis/Tick.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C){var B=e.animObject,x=H.defaultOptions,w=C.addEvent,v=C.arrayMax,f=C.arrayMin,d=C.clamp,q=C.correctFloat,k=C.defined,l=C.destroyObjectProperties,N=C.erase,u=C.error,n=C.extend,J=C.fireEvent,E=C.getMagnitude,m=C.isArray,c=C.isFunction,g=C.isNumber,a=C.isString,h=C.merge,r=C.normalizeTickInterval,
A=C.objectEach,y=C.pick,L=C.relativeLength,P=C.removeEvent,R=C.splat,V=C.syncTimeout;"";var Q=I.deg2rad;e=function(){function e(a,c){this.zoomEnabled=this.width=this.visible=this.userOptions=this.translationSlope=this.transB=this.transA=this.top=this.ticks=this.tickRotCorr=this.tickPositions=this.tickmarkOffset=this.tickInterval=this.tickAmount=this.side=this.series=this.right=this.positiveValuesOnly=this.pos=this.pointRangePadding=this.pointRange=this.plotLinesAndBandsGroups=this.plotLinesAndBands=
this.paddedTicks=this.overlap=this.options=this.offset=this.names=this.minPixelPadding=this.minorTicks=this.minorTickInterval=this.min=this.maxLabelLength=this.max=this.len=this.left=this.labelFormatter=this.labelEdge=this.isLinked=this.height=this.hasVisibleSeries=this.hasNames=this.coll=this.closestPointRange=this.chart=this.categories=this.bottom=this.alternateBands=void 0;this.init(a,c)}e.prototype.init=function(a,d){var b=d.isX,h=this;h.chart=a;h.horiz=a.inverted&&!h.isZAxis?!b:b;h.isXAxis=b;
h.coll=h.coll||(b?"xAxis":"yAxis");J(this,"init",{userOptions:d});h.opposite=y(d.opposite,h.opposite);h.side=y(d.side,h.side,h.horiz?h.opposite?0:2:h.opposite?1:3);h.setOptions(d);var p=this.options,t=p.labels,r=p.type;h.userOptions=d;h.minPixelPadding=0;h.reversed=y(p.reversed,h.reversed);h.visible=p.visible;h.zoomEnabled=p.zoomEnabled;h.hasNames="category"===r||!0===p.categories;h.categories=p.categories||h.hasNames;h.names||(h.names=[],h.names.keys={});h.plotLinesAndBandsGroups={};h.positiveValuesOnly=
!!h.logarithmic;h.isLinked=k(p.linkedTo);h.ticks={};h.labelEdge=[];h.minorTicks={};h.plotLinesAndBands=[];h.alternateBands={};h.len=0;h.minRange=h.userMinRange=p.minRange||p.maxZoom;h.range=p.range;h.offset=p.offset||0;h.max=null;h.min=null;d=y(p.crosshair,R(a.options.tooltip.crosshairs)[b?0:1]);h.crosshair=!0===d?{}:d;d=h.options.events;-1===a.axes.indexOf(h)&&(b?a.axes.splice(a.xAxis.length,0,h):a.axes.push(h),a[h.coll].push(h));h.series=h.series||[];a.inverted&&!h.isZAxis&&b&&"undefined"===typeof h.reversed&&
(h.reversed=!0);h.labelRotation=g(t.rotation)?t.rotation:void 0;A(d,function(a,d){c(a)&&w(h,d,a)});J(this,"afterInit")};e.prototype.setOptions=function(a){this.options=h(e.defaultOptions,"yAxis"===this.coll&&e.defaultYAxisOptions,[e.defaultTopAxisOptions,e.defaultRightAxisOptions,e.defaultBottomAxisOptions,e.defaultLeftAxisOptions][this.side],h(x[this.coll],a));J(this,"afterSetOptions",{userOptions:a})};e.prototype.defaultLabelFormatter=function(){var a=this.axis,c=g(this.value)?this.value:NaN,d=
a.chart.time,h=this.dateTimeLabelFormat,b=x.lang,r=b.numericSymbols;b=b.numericSymbolMagnitude||1E3;var e=r&&r.length,f=a.logarithmic?Math.abs(c):a.tickInterval,m=this.chart.numberFormatter;if(a.categories)var A=""+this.value;else if(h)A=d.dateFormat(h,c);else if(e&&1E3<=f)for(;e--&&"undefined"===typeof A;)a=Math.pow(b,e+1),f>=a&&0===10*c%a&&null!==r[e]&&0!==c&&(A=m(c/a,-1)+r[e]);"undefined"===typeof A&&(A=1E4<=Math.abs(c)?m(c,-1):m(c,-1,void 0,""));return A};e.prototype.getSeriesExtremes=function(){var a=
this,c=a.chart,d;J(this,"getSeriesExtremes",null,function(){a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.threshold=null;a.softThreshold=!a.isXAxis;a.stacking&&a.stacking.buildStacks();a.series.forEach(function(h){if(h.visible||!c.options.chart.ignoreHiddenSeries){var b=h.options,p=b.threshold;a.hasVisibleSeries=!0;a.positiveValuesOnly&&0>=p&&(p=null);if(a.isXAxis){if(b=h.xData,b.length){b=a.logarithmic?b.filter(a.validatePositiveValue):b;d=h.getXExtremes(b);var t=d.min;var r=d.max;g(t)||t instanceof
Date||(b=b.filter(g),d=h.getXExtremes(b),t=d.min,r=d.max);b.length&&(a.dataMin=Math.min(y(a.dataMin,t),t),a.dataMax=Math.max(y(a.dataMax,r),r))}}else if(h=h.applyExtremes(),g(h.dataMin)&&(t=h.dataMin,a.dataMin=Math.min(y(a.dataMin,t),t)),g(h.dataMax)&&(r=h.dataMax,a.dataMax=Math.max(y(a.dataMax,r),r)),k(p)&&(a.threshold=p),!b.softThreshold||a.positiveValuesOnly)a.softThreshold=!1}})});J(this,"afterGetSeriesExtremes")};e.prototype.translate=function(a,c,d,h,b,r){var p=this.linkedParent||this,t=1,e=
0,f=h&&p.old?p.old.transA:p.transA;h=h&&p.old?p.old.min:p.min;var F=p.minPixelPadding;b=(p.isOrdinal||p.brokenAxis&&p.brokenAxis.hasBreaks||p.logarithmic&&b)&&p.lin2val;f||(f=p.transA);d&&(t*=-1,e=p.len);p.reversed&&(t*=-1,e-=t*(p.sector||p.len));c?(a=(a*t+e-F)/f+h,b&&(a=p.lin2val(a))):(b&&(a=p.val2lin(a)),a=g(h)?t*(a-h)*f+e+t*F+(g(r)?f*r:0):void 0);return a};e.prototype.toPixels=function(a,c){return this.translate(a,!1,!this.horiz,null,!0)+(c?0:this.pos)};e.prototype.toValue=function(a,c){return this.translate(a-
(c?0:this.pos),!0,!this.horiz,null,!0)};e.prototype.getPlotLinePath=function(a){function c(a,c,g){if("pass"!==l&&a<c||a>g)l?a=d(a,c,g):v=!0;return a}var h=this,b=h.chart,t=h.left,r=h.top,e=a.old,f=a.value,m=a.translatedValue,A=a.lineWidth,l=a.force,n,k,u,L,q=e&&b.oldChartHeight||b.chartHeight,P=e&&b.oldChartWidth||b.chartWidth,v,da=h.transB;a={value:f,lineWidth:A,old:e,force:l,acrossPanes:a.acrossPanes,translatedValue:m};J(this,"getPlotLinePath",a,function(a){m=y(m,h.translate(f,null,null,e));m=d(m,
-1E5,1E5);n=u=Math.round(m+da);k=L=Math.round(q-m-da);g(m)?h.horiz?(k=r,L=q-h.bottom,n=u=c(n,t,t+h.width)):(n=t,u=P-h.right,k=L=c(k,r,r+h.height)):(v=!0,l=!1);a.path=v&&!l?null:b.renderer.crispLine([["M",n,k],["L",u,L]],A||1)});return a.path};e.prototype.getLinearTickPositions=function(a,c,d){var g=q(Math.floor(c/a)*a);d=q(Math.ceil(d/a)*a);var h=[],b;q(g+a)===g&&(b=20);if(this.single)return[c];for(c=g;c<=d;){h.push(c);c=q(c+a,b);if(c===p)break;var p=c}return h};e.prototype.getMinorTickInterval=function(){var a=
this.options;return!0===a.minorTicks?y(a.minorTickInterval,"auto"):!1===a.minorTicks?null:a.minorTickInterval};e.prototype.getMinorTickPositions=function(){var a=this.options,c=this.tickPositions,d=this.minorTickInterval,g=[],h=this.pointRangePadding||0,b=this.min-h;h=this.max+h;var r=h-b;if(r&&r/d<this.len/3){var e=this.logarithmic;if(e)this.paddedTicks.forEach(function(a,c,h){c&&g.push.apply(g,e.getLogTickPositions(d,h[c-1],h[c],!0))});else if(this.dateTime&&"auto"===this.getMinorTickInterval())g=
g.concat(this.getTimeTicks(this.dateTime.normalizeTimeTickInterval(d),b,h,a.startOfWeek));else for(a=b+(c[0]-b)%d;a<=h&&a!==g[0];a+=d)g.push(a)}0!==g.length&&this.trimTicks(g);return g};e.prototype.adjustForMinRange=function(){var a=this.options,c=this.min,d=this.max,g=this.logarithmic,h=0,b,r,e,m;this.isXAxis&&"undefined"===typeof this.minRange&&!g&&(k(a.min)||k(a.max)?this.minRange=null:(this.series.forEach(function(a){e=a.xData;m=a.xIncrement?1:e.length-1;if(1<e.length)for(b=m;0<b;b--)if(r=e[b]-
e[b-1],!h||r<h)h=r}),this.minRange=Math.min(5*h,this.dataMax-this.dataMin)));if(d-c<this.minRange){var A=this.dataMax-this.dataMin>=this.minRange;var l=this.minRange;var n=(l-d+c)/2;n=[c-n,y(a.min,c-n)];A&&(n[2]=this.logarithmic?this.logarithmic.log2lin(this.dataMin):this.dataMin);c=v(n);d=[c+l,y(a.max,c+l)];A&&(d[2]=g?g.log2lin(this.dataMax):this.dataMax);d=f(d);d-c<l&&(n[0]=d-l,n[1]=y(a.min,d-l),c=v(n))}this.min=c;this.max=d};e.prototype.getClosest=function(){var a;this.categories?a=1:this.series.forEach(function(c){var d=
c.closestPointRange,g=c.visible||!c.chart.options.chart.ignoreHiddenSeries;!c.noSharedTooltip&&k(d)&&g&&(a=k(a)?Math.min(a,d):d)});return a};e.prototype.nameToX=function(a){var c=m(this.categories),d=c?this.categories:this.names,g=a.options.x;a.series.requireSorting=!1;k(g)||(g=this.options.uniqueNames?c?d.indexOf(a.name):y(d.keys[a.name],-1):a.series.autoIncrement());if(-1===g){if(!c)var h=d.length}else h=g;"undefined"!==typeof h&&(this.names[h]=a.name,this.names.keys[a.name]=h);return h};e.prototype.updateNames=
function(){var a=this,c=this.names;0<c.length&&(Object.keys(c.keys).forEach(function(a){delete c.keys[a]}),c.length=0,this.minRange=this.userMinRange,(this.series||[]).forEach(function(c){c.xIncrement=null;if(!c.points||c.isDirtyData)a.max=Math.max(a.max,c.xData.length-1),c.processData(),c.generatePoints();c.data.forEach(function(d,g){if(d&&d.options&&"undefined"!==typeof d.name){var h=a.nameToX(d);"undefined"!==typeof h&&h!==d.x&&(d.x=h,c.xData[g]=h)}})}))};e.prototype.setAxisTranslation=function(){var c=
this,d=c.max-c.min,g=c.axisPointRange||0,h=0,b=0,r=c.linkedParent,e=!!c.categories,f=c.transA,m=c.isXAxis;if(m||e||g){var A=c.getClosest();r?(h=r.minPointOffset,b=r.pointRangePadding):c.series.forEach(function(d){var p=e?1:m?y(d.options.pointRange,A,0):c.axisPointRange||0,r=d.options.pointPlacement;g=Math.max(g,p);if(!c.single||e)d=d.is("xrange")?!m:m,h=Math.max(h,d&&a(r)?0:p/2),b=Math.max(b,d&&"on"===r?0:p)});r=c.ordinal&&c.ordinal.slope&&A?c.ordinal.slope/A:1;c.minPointOffset=h*=r;c.pointRangePadding=
b*=r;c.pointRange=Math.min(g,c.single&&e?1:d);m&&(c.closestPointRange=A)}c.translationSlope=c.transA=f=c.staticScale||c.len/(d+b||1);c.transB=c.horiz?c.left:c.bottom;c.minPixelPadding=f*h;J(this,"afterSetAxisTranslation")};e.prototype.minFromRange=function(){return this.max-this.range};e.prototype.setTickInterval=function(a){var c=this,d=c.chart,h=c.logarithmic,b=c.options,e=c.isXAxis,t=c.isLinked,f=b.maxPadding,m=b.minPadding,A=b.tickInterval,l=b.tickPixelInterval,n=c.categories,L=g(c.threshold)?
c.threshold:null,P=c.softThreshold;c.dateTime||n||t||this.getTickAmount();var v=y(c.userMin,b.min);var w=y(c.userMax,b.max);if(t){c.linkedParent=d[c.coll][b.linkedTo];var R=c.linkedParent.getExtremes();c.min=y(R.min,R.dataMin);c.max=y(R.max,R.dataMax);b.type!==c.linkedParent.options.type&&u(11,1,d)}else{if(P&&k(L))if(c.dataMin>=L)R=L,m=0;else if(c.dataMax<=L){var Q=L;f=0}c.min=y(v,R,c.dataMin);c.max=y(w,Q,c.dataMax)}h&&(c.positiveValuesOnly&&!a&&0>=Math.min(c.min,y(c.dataMin,c.min))&&u(10,1,d),c.min=
q(h.log2lin(c.min),16),c.max=q(h.log2lin(c.max),16));c.range&&k(c.max)&&(c.userMin=c.min=v=Math.max(c.dataMin,c.minFromRange()),c.userMax=w=c.max,c.range=null);J(c,"foundExtremes");c.beforePadding&&c.beforePadding();c.adjustForMinRange();!(n||c.axisPointRange||c.stacking&&c.stacking.usePercentage||t)&&k(c.min)&&k(c.max)&&(d=c.max-c.min)&&(!k(v)&&m&&(c.min-=d*m),!k(w)&&f&&(c.max+=d*f));g(c.userMin)||(g(b.softMin)&&b.softMin<c.min&&(c.min=v=b.softMin),g(b.floor)&&(c.min=Math.max(c.min,b.floor)));g(c.userMax)||
(g(b.softMax)&&b.softMax>c.max&&(c.max=w=b.softMax),g(b.ceiling)&&(c.max=Math.min(c.max,b.ceiling)));P&&k(c.dataMin)&&(L=L||0,!k(v)&&c.min<L&&c.dataMin>=L?c.min=c.options.minRange?Math.min(L,c.max-c.minRange):L:!k(w)&&c.max>L&&c.dataMax<=L&&(c.max=c.options.minRange?Math.max(L,c.min+c.minRange):L));g(c.min)&&g(c.max)&&!this.chart.polar&&c.min>c.max&&(k(c.options.min)?c.max=c.min:k(c.options.max)&&(c.min=c.max));c.tickInterval=c.min===c.max||"undefined"===typeof c.min||"undefined"===typeof c.max?1:
t&&c.linkedParent&&!A&&l===c.linkedParent.options.tickPixelInterval?A=c.linkedParent.tickInterval:y(A,this.tickAmount?(c.max-c.min)/Math.max(this.tickAmount-1,1):void 0,n?1:(c.max-c.min)*l/Math.max(c.len,l));e&&!a&&c.series.forEach(function(a){a.processData(c.min!==(c.old&&c.old.min)||c.max!==(c.old&&c.old.max))});c.setAxisTranslation();J(this,"initialAxisTranslation");c.pointRange&&!A&&(c.tickInterval=Math.max(c.pointRange,c.tickInterval));a=y(b.minTickInterval,c.dateTime&&!c.series.some(function(a){return a.noSharedTooltip})?
c.closestPointRange:0);!A&&c.tickInterval<a&&(c.tickInterval=a);c.dateTime||c.logarithmic||A||(c.tickInterval=r(c.tickInterval,void 0,E(c.tickInterval),y(b.allowDecimals,.5>c.tickInterval||void 0!==this.tickAmount),!!this.tickAmount));this.tickAmount||(c.tickInterval=c.unsquish());this.setTickPositions()};e.prototype.setTickPositions=function(){var a=this.options,c=a.tickPositions;var d=this.getMinorTickInterval();var g=a.tickPositioner,h=this.hasVerticalPanning(),b="colorAxis"===this.coll,r=(b||
!h)&&a.startOnTick;h=(b||!h)&&a.endOnTick;this.tickmarkOffset=this.categories&&"between"===a.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===d&&this.tickInterval?this.tickInterval/5:d;this.single=this.min===this.max&&k(this.min)&&!this.tickAmount&&(parseInt(this.min,10)===this.min||!1!==a.allowDecimals);this.tickPositions=d=c&&c.slice();!d&&(this.ordinal&&this.ordinal.positions||!((this.max-this.min)/this.tickInterval>Math.max(2*this.len,200))?d=this.dateTime?this.getTimeTicks(this.dateTime.normalizeTimeTickInterval(this.tickInterval,
a.units),this.min,this.max,a.startOfWeek,this.ordinal&&this.ordinal.positions,this.closestPointRange,!0):this.logarithmic?this.logarithmic.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max):(d=[this.min,this.max],u(19,!1,this.chart)),d.length>this.len&&(d=[d[0],d.pop()],d[0]===d[1]&&(d.length=1)),this.tickPositions=d,g&&(g=g.apply(this,[this.min,this.max])))&&(this.tickPositions=d=g);this.paddedTicks=d.slice(0);this.trimTicks(d,
r,h);this.isLinked||(this.single&&2>d.length&&!this.categories&&!this.series.some(function(a){return a.is("heatmap")&&"between"===a.options.pointPlacement})&&(this.min-=.5,this.max+=.5),c||g||this.adjustTickAmount());J(this,"afterSetTickPositions")};e.prototype.trimTicks=function(a,c,d){var g=a[0],h=a[a.length-1],b=!this.isOrdinal&&this.minPointOffset||0;J(this,"trimTicks");if(!this.isLinked){if(c&&-Infinity!==g)this.min=g;else for(;this.min-b>a[0];)a.shift();if(d)this.max=h;else for(;this.max+b<
a[a.length-1];)a.pop();0===a.length&&k(g)&&!this.options.tickPositions&&a.push((h+g)/2)}};e.prototype.alignToOthers=function(){var a={},c,d=this.options;!1!==this.chart.options.chart.alignTicks&&d.alignTicks&&!1!==d.startOnTick&&!1!==d.endOnTick&&!this.logarithmic&&this.chart[this.coll].forEach(function(d){var g=d.options;g=[d.horiz?g.left:g.top,g.width,g.height,g.pane].join();d.series.length&&(a[g]?c=!0:a[g]=1)});return c};e.prototype.getTickAmount=function(){var a=this.options,c=a.tickAmount,d=
a.tickPixelInterval;!k(a.tickInterval)&&!c&&this.len<d&&!this.isRadial&&!this.logarithmic&&a.startOnTick&&a.endOnTick&&(c=2);!c&&this.alignToOthers()&&(c=Math.ceil(this.len/d)+1);4>c&&(this.finalTickAmt=c,c=5);this.tickAmount=c};e.prototype.adjustTickAmount=function(){var a=this.options,c=this.tickInterval,d=this.tickPositions,h=this.tickAmount,b=this.finalTickAmt,r=d&&d.length,e=y(this.threshold,this.softThreshold?0:null);if(this.hasData()&&g(this.min)&&g(this.max)){if(r<h){for(;d.length<h;)d.length%
2||this.min===e?d.push(q(d[d.length-1]+c)):d.unshift(q(d[0]-c));this.transA*=(r-1)/(h-1);this.min=a.startOnTick?d[0]:Math.min(this.min,d[0]);this.max=a.endOnTick?d[d.length-1]:Math.max(this.max,d[d.length-1])}else r>h&&(this.tickInterval*=2,this.setTickPositions());if(k(b)){for(c=a=d.length;c--;)(3===b&&1===c%2||2>=b&&0<c&&c<a-1)&&d.splice(c,1);this.finalTickAmt=void 0}}};e.prototype.setScale=function(){var a,c=!1,d=!1;this.series.forEach(function(a){c=c||a.isDirtyData||a.isDirty;d=d||a.xAxis&&a.xAxis.isDirty||
!1});this.setAxisSize();(a=this.len!==(this.old&&this.old.len))||c||d||this.isLinked||this.forceRedraw||this.userMin!==(this.old&&this.old.userMin)||this.userMax!==(this.old&&this.old.userMax)||this.alignToOthers()?(this.stacking&&this.stacking.resetStacks(),this.forceRedraw=!1,this.getSeriesExtremes(),this.setTickInterval(),this.isDirty||(this.isDirty=a||this.min!==(this.old&&this.old.min)||this.max!==(this.old&&this.old.max))):this.stacking&&this.stacking.cleanStacks();c&&this.panningState&&(this.panningState.isDirty=
!0);J(this,"afterSetScale")};e.prototype.setExtremes=function(a,c,d,g,h){var b=this,r=b.chart;d=y(d,!0);b.series.forEach(function(a){delete a.kdTree});h=n(h,{min:a,max:c});J(b,"setExtremes",h,function(){b.userMin=a;b.userMax=c;b.eventArgs=h;d&&r.redraw(g)})};e.prototype.zoom=function(a,c){var d=this,g=this.dataMin,h=this.dataMax,b=this.options,r=Math.min(g,y(b.min,g)),e=Math.max(h,y(b.max,h));a={newMin:a,newMax:c};J(this,"zoom",a,function(a){var c=a.newMin,b=a.newMax;if(c!==d.min||b!==d.max)d.allowZoomOutside||
(k(g)&&(c<r&&(c=r),c>e&&(c=e)),k(h)&&(b<r&&(b=r),b>e&&(b=e))),d.displayBtn="undefined"!==typeof c||"undefined"!==typeof b,d.setExtremes(c,b,!1,void 0,{trigger:"zoom"});a.zoomed=!0});return a.zoomed};e.prototype.setAxisSize=function(){var a=this.chart,c=this.options,d=c.offsets||[0,0,0,0],g=this.horiz,h=this.width=Math.round(L(y(c.width,a.plotWidth-d[3]+d[1]),a.plotWidth)),b=this.height=Math.round(L(y(c.height,a.plotHeight-d[0]+d[2]),a.plotHeight)),r=this.top=Math.round(L(y(c.top,a.plotTop+d[0]),a.plotHeight,
a.plotTop));c=this.left=Math.round(L(y(c.left,a.plotLeft+d[3]),a.plotWidth,a.plotLeft));this.bottom=a.chartHeight-b-r;this.right=a.chartWidth-h-c;this.len=Math.max(g?h:b,0);this.pos=g?c:r};e.prototype.getExtremes=function(){var a=this.logarithmic;return{min:a?q(a.lin2log(this.min)):this.min,max:a?q(a.lin2log(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}};e.prototype.getThreshold=function(a){var c=this.logarithmic,d=c?c.lin2log(this.min):this.min;
c=c?c.lin2log(this.max):this.max;null===a||-Infinity===a?a=d:Infinity===a?a=c:d>a?a=d:c<a&&(a=c);return this.translate(a,0,1,0,1)};e.prototype.autoLabelAlign=function(a){var c=(y(a,0)-90*this.side+720)%360;a={align:"center"};J(this,"autoLabelAlign",a,function(a){15<c&&165>c?a.align="right":195<c&&345>c&&(a.align="left")});return a.align};e.prototype.tickSize=function(a){var c=this.options,d=c["tick"===a?"tickLength":"minorTickLength"],g=y(c["tick"===a?"tickWidth":"minorTickWidth"],"tick"===a&&this.isXAxis&&
!this.categories?1:0);if(g&&d){"inside"===c[a+"Position"]&&(d=-d);var h=[d,g]}a={tickSize:h};J(this,"afterTickSize",a);return a.tickSize};e.prototype.labelMetrics=function(){var a=this.tickPositions&&this.tickPositions[0]||0;return this.chart.renderer.fontMetrics(this.options.labels.style.fontSize,this.ticks[a]&&this.ticks[a].label)};e.prototype.unsquish=function(){var a=this.options.labels,c=this.horiz,d=this.tickInterval,h=d,b=this.len/(((this.categories?1:0)+this.max-this.min)/d),r,e=a.rotation,
f=this.labelMetrics(),m,A=Number.MAX_VALUE,l=Math.max(this.max-this.min,0),n=function(a){var c=a/(b||1);c=1<c?Math.ceil(c):1;c*d>l&&Infinity!==a&&Infinity!==b&&l&&(c=Math.ceil(l/d));return q(c*d)};if(c){if(!a.staggerLines&&!a.step)if(g(e))var k=[e];else b<a.autoRotationLimit&&(k=a.autoRotation);k&&k.forEach(function(a){if(a===e||a&&-90<=a&&90>=a){m=n(Math.abs(f.h/Math.sin(Q*a)));var c=m+Math.abs(a/360);c<A&&(A=c,r=a,h=m)}})}else a.step||(h=n(f.h));this.autoRotation=k;this.labelRotation=y(r,g(e)?e:
0);return h};e.prototype.getSlotWidth=function(a){var c=this.chart,d=this.horiz,h=this.options.labels,b=Math.max(this.tickPositions.length-(this.categories?0:1),1),r=c.margin[3];if(a&&g(a.slotWidth))return a.slotWidth;if(d&&2>h.step)return h.rotation?0:(this.staggerLines||1)*this.len/b;if(!d){a=h.style.width;if(void 0!==a)return parseInt(String(a),10);if(r)return r-c.spacing[3]}return.33*c.chartWidth};e.prototype.renderUnsquish=function(){var c=this.chart,d=c.renderer,g=this.tickPositions,h=this.ticks,
b=this.options.labels,r=b.style,e=this.horiz,f=this.getSlotWidth(),m=Math.max(1,Math.round(f-2*b.padding)),A={},y=this.labelMetrics(),l=r.textOverflow,n=0;a(b.rotation)||(A.rotation=b.rotation||0);g.forEach(function(a){a=h[a];a.movedLabel&&a.replaceMovedLabel();a&&a.label&&a.label.textPxLength>n&&(n=a.label.textPxLength)});this.maxLabelLength=n;if(this.autoRotation)n>m&&n>y.h?A.rotation=this.labelRotation:this.labelRotation=0;else if(f){var k=m;if(!l){var L="clip";for(m=g.length;!e&&m--;){var u=g[m];
if(u=h[u].label)u.styles&&"ellipsis"===u.styles.textOverflow?u.css({textOverflow:"clip"}):u.textPxLength>f&&u.css({width:f+"px"}),u.getBBox().height>this.len/g.length-(y.h-y.f)&&(u.specificTextOverflow="ellipsis")}}}A.rotation&&(k=n>.5*c.chartHeight?.33*c.chartHeight:n,l||(L="ellipsis"));if(this.labelAlign=b.align||this.autoLabelAlign(this.labelRotation))A.align=this.labelAlign;g.forEach(function(a){var c=(a=h[a])&&a.label,d=r.width,g={};c&&(c.attr(A),a.shortenLabel?a.shortenLabel():k&&!d&&"nowrap"!==
r.whiteSpace&&(k<c.textPxLength||"SPAN"===c.element.tagName)?(g.width=k+"px",l||(g.textOverflow=c.specificTextOverflow||L),c.css(g)):c.styles&&c.styles.width&&!g.width&&!d&&c.css({width:null}),delete c.specificTextOverflow,a.rotation=A.rotation)},this);this.tickRotCorr=d.rotCorr(y.b,this.labelRotation||0,0!==this.side)};e.prototype.hasData=function(){return this.series.some(function(a){return a.hasData()})||this.options.showEmpty&&k(this.min)&&k(this.max)};e.prototype.addTitle=function(a){var c=this.chart.renderer,
d=this.horiz,g=this.opposite,b=this.options.title,r,e=this.chart.styledMode;this.axisTitle||((r=b.textAlign)||(r=(d?{low:"left",middle:"center",high:"right"}:{low:g?"right":"left",middle:"center",high:g?"left":"right"})[b.align]),this.axisTitle=c.text(b.text||"",0,0,b.useHTML).attr({zIndex:7,rotation:b.rotation,align:r}).addClass("highcharts-axis-title"),e||this.axisTitle.css(h(b.style)),this.axisTitle.add(this.axisGroup),this.axisTitle.isNew=!0);e||b.style.width||this.isRadial||this.axisTitle.css({width:this.len+
"px"});this.axisTitle[a?"show":"hide"](a)};e.prototype.generateTick=function(a){var c=this.ticks;c[a]?c[a].addLabel():c[a]=new G(this,a)};e.prototype.getOffset=function(){var a=this,c=this,d=c.chart,g=d.renderer,h=c.options,b=c.tickPositions,r=c.ticks,e=c.horiz,f=c.side,m=d.inverted&&!c.isZAxis?[1,0,3,2][f]:f,l,n=0,L=0,u=h.title,P=h.labels,q=0,v=d.axisOffset;d=d.clipOffset;var w=[-1,1,1,-1][f],da=h.className,ia=c.axisParent;var E=c.hasData();c.showAxis=l=E||h.showEmpty;c.staggerLines=c.horiz&&P.staggerLines||
void 0;if(!c.axisGroup){var R=function(c,d,h){return g.g(c).attr({zIndex:h}).addClass("highcharts-"+a.coll.toLowerCase()+d+" "+(a.isRadial?"highcharts-radial-axis"+d+" ":"")+(da||"")).add(ia)};c.gridGroup=R("grid","-grid",h.gridZIndex);c.axisGroup=R("axis","",h.zIndex);c.labelGroup=R("axis-labels","-labels",P.zIndex)}E||c.isLinked?(b.forEach(function(a,d){c.generateTick(a,d)}),c.renderUnsquish(),c.reserveSpaceDefault=0===f||2===f||{1:"left",3:"right"}[f]===c.labelAlign,y(P.reserveSpace,"center"===
c.labelAlign?!0:null,c.reserveSpaceDefault)&&b.forEach(function(a){q=Math.max(r[a].getLabelSize(),q)}),c.staggerLines&&(q*=c.staggerLines),c.labelOffset=q*(c.opposite?-1:1)):A(r,function(a,c){a.destroy();delete r[c]});if(u&&u.text&&!1!==u.enabled&&(c.addTitle(l),l&&!1!==u.reserveSpace)){c.titleOffset=n=c.axisTitle.getBBox()[e?"height":"width"];var Q=u.offset;L=k(Q)?0:y(u.margin,e?5:10)}c.renderLine();c.offset=w*y(h.offset,v[f]?v[f]+(h.margin||0):0);c.tickRotCorr=c.tickRotCorr||{x:0,y:0};u=0===f?-c.labelMetrics().h:
2===f?c.tickRotCorr.y:0;L=Math.abs(q)+L;q&&(L=L-u+w*(e?y(P.y,c.tickRotCorr.y+8*w):P.x));c.axisTitleMargin=y(Q,L);c.getMaxLabelDimensions&&(c.maxLabelDimensions=c.getMaxLabelDimensions(r,b));e=this.tickSize("tick");v[f]=Math.max(v[f],(c.axisTitleMargin||0)+n+w*c.offset,L,b&&b.length&&e?e[0]+w*c.offset:0);h=h.offset?0:2*Math.floor(c.axisLine.strokeWidth()/2);d[m]=Math.max(d[m],h);J(this,"afterGetOffset")};e.prototype.getLinePath=function(a){var c=this.chart,d=this.opposite,g=this.offset,h=this.horiz,
b=this.left+(d?this.width:0)+g;g=c.chartHeight-this.bottom-(d?this.height:0)+g;d&&(a*=-1);return c.renderer.crispLine([["M",h?this.left:b,h?g:this.top],["L",h?c.chartWidth-this.right:b,h?g:c.chartHeight-this.bottom]],a)};e.prototype.renderLine=function(){this.axisLine||(this.axisLine=this.chart.renderer.path().addClass("highcharts-axis-line").add(this.axisGroup),this.chart.styledMode||this.axisLine.attr({stroke:this.options.lineColor,"stroke-width":this.options.lineWidth,zIndex:7}))};e.prototype.getTitlePosition=
function(){var a=this.horiz,c=this.left,d=this.top,g=this.len,h=this.options.title,b=a?c:d,r=this.opposite,e=this.offset,f=h.x,m=h.y,A=this.axisTitle,y=this.chart.renderer.fontMetrics(h.style.fontSize,A);A=Math.max(A.getBBox(null,0).height-y.h-1,0);g={low:b+(a?0:g),middle:b+g/2,high:b+(a?g:0)}[h.align];c=(a?d+this.height:c)+(a?1:-1)*(r?-1:1)*this.axisTitleMargin+[-A,A,y.f,-A][this.side];a={x:a?g+f:c+(r?this.width:0)+e+f,y:a?c+m-(r?this.height:0)+e:g+m};J(this,"afterGetTitlePosition",{titlePosition:a});
return a};e.prototype.renderMinorTick=function(a){var c=this.chart.hasRendered&&this.old,d=this.minorTicks;d[a]||(d[a]=new G(this,a,"minor"));c&&d[a].isNew&&d[a].render(null,!0);d[a].render(null,!1,1)};e.prototype.renderTick=function(a,c){var d=this.ticks,g=this.chart.hasRendered&&this.old;if(!this.isLinked||a>=this.min&&a<=this.max||this.grid&&this.grid.isColumn)d[a]||(d[a]=new G(this,a)),g&&d[a].isNew&&d[a].render(c,!0,-1),d[a].render(c)};e.prototype.render=function(){var a=this,c=a.chart,d=a.logarithmic,
h=a.options,b=a.isLinked,r=a.tickPositions,e=a.axisTitle,f=a.ticks,m=a.minorTicks,y=a.alternateBands,l=h.stackLabels,n=h.alternateGridColor,k=a.tickmarkOffset,L=a.axisLine,u=a.showAxis,q=B(c.renderer.globalAnimation),P,v;a.labelEdge.length=0;a.overlap=!1;[f,m,y].forEach(function(a){A(a,function(a){a.isActive=!1})});if(a.hasData()||b)a.minorTickInterval&&!a.categories&&a.getMinorTickPositions().forEach(function(c){a.renderMinorTick(c)}),r.length&&(r.forEach(function(c,d){a.renderTick(c,d)}),k&&(0===
a.min||a.single)&&(f[-1]||(f[-1]=new G(a,-1,null,!0)),f[-1].render(-1))),n&&r.forEach(function(g,h){v="undefined"!==typeof r[h+1]?r[h+1]+k:a.max-k;0===h%2&&g<a.max&&v<=a.max+(c.polar?-k:k)&&(y[g]||(y[g]=new I.PlotLineOrBand(a)),P=g+k,y[g].options={from:d?d.lin2log(P):P,to:d?d.lin2log(v):v,color:n,className:"highcharts-alternate-grid"},y[g].render(),y[g].isActive=!0)}),a._addedPlotLB||(a._addedPlotLB=!0,(h.plotLines||[]).concat(h.plotBands||[]).forEach(function(c){a.addPlotBandOrLine(c)}));[f,m,y].forEach(function(a){var d,
g=[],h=q.duration;A(a,function(a,c){a.isActive||(a.render(c,!1,0),a.isActive=!1,g.push(c))});V(function(){for(d=g.length;d--;)a[g[d]]&&!a[g[d]].isActive&&(a[g[d]].destroy(),delete a[g[d]])},a!==y&&c.hasRendered&&h?h:0)});L&&(L[L.isPlaced?"animate":"attr"]({d:this.getLinePath(L.strokeWidth())}),L.isPlaced=!0,L[u?"show":"hide"](u));e&&u&&(h=a.getTitlePosition(),g(h.y)?(e[e.isNew?"attr":"animate"](h),e.isNew=!1):(e.attr("y",-9999),e.isNew=!0));l&&l.enabled&&a.stacking&&a.stacking.renderStackTotals();
a.old={len:a.len,max:a.max,min:a.min,transA:a.transA,userMax:a.userMax,userMin:a.userMin};a.isDirty=!1;J(this,"afterRender")};e.prototype.redraw=function(){this.visible&&(this.render(),this.plotLinesAndBands.forEach(function(a){a.render()}));this.series.forEach(function(a){a.isDirty=!0})};e.prototype.getKeepProps=function(){return this.keepProps||e.keepProps};e.prototype.destroy=function(a){var c=this,d=c.plotLinesAndBands,g;J(this,"destroy",{keepEvents:a});a||P(c);[c.ticks,c.minorTicks,c.alternateBands].forEach(function(a){l(a)});
if(d)for(a=d.length;a--;)d[a].destroy();"axisLine axisTitle axisGroup gridGroup labelGroup cross scrollbar".split(" ").forEach(function(a){c[a]&&(c[a]=c[a].destroy())});for(g in c.plotLinesAndBandsGroups)c.plotLinesAndBandsGroups[g]=c.plotLinesAndBandsGroups[g].destroy();A(c,function(a,d){-1===c.getKeepProps().indexOf(d)&&delete c[d]})};e.prototype.drawCrosshair=function(a,c){var d=this.crosshair,g=y(d&&d.snap,!0),h,r=this.cross,e=this.chart;J(this,"drawCrosshair",{e:a,point:c});a||(a=this.cross&&
this.cross.e);if(d&&!1!==(k(c)||!g)){g?k(c)&&(h=y("colorAxis"!==this.coll?c.crosshairPos:null,this.isXAxis?c.plotX:this.len-c.plotY)):h=a&&(this.horiz?a.chartX-this.pos:this.len-a.chartY+this.pos);if(k(h)){var f={value:c&&(this.isXAxis?c.x:y(c.stackY,c.y)),translatedValue:h};e.polar&&n(f,{isCrosshair:!0,chartX:a&&a.chartX,chartY:a&&a.chartY,point:c});f=this.getPlotLinePath(f)||null}if(!k(f)){this.hideCrosshair();return}g=this.categories&&!this.isRadial;r||(this.cross=r=e.renderer.path().addClass("highcharts-crosshair highcharts-crosshair-"+
(g?"category ":"thin ")+(d.className||"")).attr({zIndex:y(d.zIndex,2)}).add(),e.styledMode||(r.attr({stroke:d.color||(g?b.parse(z.highlightColor20).setOpacity(.25).get():z.neutralColor20),"stroke-width":y(d.width,1)}).css({"pointer-events":"none"}),d.dashStyle&&r.attr({dashstyle:d.dashStyle})));r.show().attr({d:f});g&&!d.width&&r.attr({"stroke-width":this.transA});this.cross.e=a}else this.hideCrosshair();J(this,"afterDrawCrosshair",{e:a,point:c})};e.prototype.hideCrosshair=function(){this.cross&&
this.cross.hide();J(this,"afterHideCrosshair")};e.prototype.hasVerticalPanning=function(){var a=this.chart.options.chart.panning;return!!(a&&a.enabled&&/y/.test(a.type))};e.prototype.validatePositiveValue=function(a){return g(a)&&0<a};e.prototype.update=function(a,c){var d=this.chart,g=a&&a.events||{};a=h(this.userOptions,a);A(d.options[this.coll].events,function(a,c){"undefined"===typeof g[c]&&(g[c]=void 0)});this.destroy(!0);this.init(d,n(a,{events:g}));d.isDirtyBox=!0;y(c,!0)&&d.redraw()};e.prototype.remove=
function(a){for(var c=this.chart,d=this.coll,g=this.series,h=g.length;h--;)g[h]&&g[h].remove(!1);N(c.axes,this);N(c[d],this);c[d].forEach(function(a,c){a.options.index=a.userOptions.index=c});this.destroy();c.isDirtyBox=!0;y(a,!0)&&c.redraw()};e.prototype.setTitle=function(a,c){this.update({title:a},c)};e.prototype.setCategories=function(a,c){this.update({categories:a},c)};e.defaultOptions={alignTicks:!0,allowDecimals:void 0,zIndex:2,zoomEnabled:!0,dateTimeLabelFormats:{millisecond:{main:"%H:%M:%S.%L",
range:!1},second:{main:"%H:%M:%S",range:!1},minute:{main:"%H:%M",range:!1},hour:{main:"%H:%M",range:!1},day:{main:"%e. %b"},week:{main:"%e. %b"},month:{main:"%b '%y"},year:{main:"%Y"}},endOnTick:!1,gridLineDashStyle:"Solid",gridZIndex:1,labels:{autoRotation:void 0,autoRotationLimit:80,distance:void 0,enabled:!0,indentation:10,overflow:"justify",padding:5,reserveSpace:void 0,rotation:void 0,staggerLines:0,step:0,useHTML:!1,x:0,zIndex:7,style:{color:z.neutralColor60,cursor:"default",fontSize:"11px"}},
maxPadding:.01,minorGridLineDashStyle:"Solid",minorTickLength:2,minorTickPosition:"outside",minPadding:.01,offset:void 0,opposite:!1,reversed:void 0,reversedStacks:!1,showEmpty:!0,showFirstLabel:!0,showLastLabel:!0,startOfWeek:1,startOnTick:!1,tickLength:10,tickPixelInterval:100,tickmarkPlacement:"between",tickPosition:"outside",title:{align:"middle",rotation:0,useHTML:!1,x:0,y:0,style:{color:z.neutralColor60}},type:"linear",uniqueNames:!0,visible:!0,minorGridLineColor:z.neutralColor5,minorGridLineWidth:1,
minorTickColor:z.neutralColor40,lineColor:z.highlightColor20,lineWidth:1,gridLineColor:z.neutralColor10,gridLineWidth:void 0,tickColor:z.highlightColor20};e.defaultYAxisOptions={reversedStacks:!0,endOnTick:!0,maxPadding:.05,minPadding:.05,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8},startOnTick:!0,title:{rotation:270,text:"Values"},stackLabels:{animation:{},allowOverlap:!1,enabled:!1,crop:!0,overflow:"justify",formatter:function(){var a=this.axis.chart.numberFormatter;return a(this.total,-1)},
style:{color:z.neutralColor100,fontSize:"11px",fontWeight:"bold",textOutline:"1px contrast"}},gridLineWidth:1,lineWidth:0};e.defaultLeftAxisOptions={labels:{x:-15},title:{rotation:270}};e.defaultRightAxisOptions={labels:{x:15},title:{rotation:90}};e.defaultBottomAxisOptions={labels:{autoRotation:[-45],x:0},margin:15,title:{rotation:0}};e.defaultTopAxisOptions={labels:{autoRotation:[-45],x:0},margin:15,title:{rotation:0}};e.keepProps="extKey hcEvents names series userMax userMin".split(" ");return e}();
I.Axis=e;return I.Axis});O(e,"Core/Axis/DateTimeAxis.js",[e["Core/Axis/Axis.js"],e["Core/Utilities.js"]],function(e,b){var D=b.addEvent,z=b.getMagnitude,H=b.normalizeTickInterval,G=b.timeUnits,C=function(){function b(b){this.axis=b}b.prototype.normalizeTimeTickInterval=function(b,e){var v=e||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day",[1,2]],["week",[1,2]],["month",[1,2,3,4,6]],["year",null]];e=v[v.length-
1];var f=G[e[0]],d=e[1],q;for(q=0;q<v.length&&!(e=v[q],f=G[e[0]],d=e[1],v[q+1]&&b<=(f*d[d.length-1]+G[v[q+1][0]])/2);q++);f===G.year&&b<5*f&&(d=[1,2,5]);b=H(b/f,d,"year"===e[0]?Math.max(z(b/f),1):1);return{unitRange:f,count:b,unitName:e[0]}};return b}();b=function(){function b(){}b.compose=function(b){b.keepProps.push("dateTime");b.prototype.getTimeTicks=function(){return this.chart.time.getTimeTicks.apply(this.chart.time,arguments)};D(b,"init",function(b){"datetime"!==b.userOptions.type?this.dateTime=
void 0:this.dateTime||(this.dateTime=new C(this))})};b.AdditionsClass=C;return b}();b.compose(e);return b});O(e,"Core/Axis/LogarithmicAxis.js",[e["Core/Axis/Axis.js"],e["Core/Utilities.js"]],function(e,b){var D=b.addEvent,z=b.getMagnitude,H=b.normalizeTickInterval,G=b.pick,C=function(){function b(b){this.axis=b}b.prototype.getLogTickPositions=function(b,e,v,f){var d=this.axis,q=d.len,k=d.options,l=[];f||(this.minorAutoInterval=void 0);if(.5<=b)b=Math.round(b),l=d.getLinearTickPositions(b,e,v);else if(.08<=
b){var w=Math.floor(e),u,n=k=void 0;for(q=.3<b?[1,2,4]:.15<b?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];w<v+1&&!n;w++){var J=q.length;for(u=0;u<J&&!n;u++){var E=this.log2lin(this.lin2log(w)*q[u]);E>e&&(!f||k<=v)&&"undefined"!==typeof k&&l.push(k);k>v&&(n=!0);k=E}}}else e=this.lin2log(e),v=this.lin2log(v),b=f?d.getMinorTickInterval():k.tickInterval,b=G("auto"===b?null:b,this.minorAutoInterval,k.tickPixelInterval/(f?5:1)*(v-e)/((f?q/d.tickPositions.length:q)||1)),b=H(b,void 0,z(b)),l=d.getLinearTickPositions(b,
e,v).map(this.log2lin),f||(this.minorAutoInterval=b/5);f||(d.tickInterval=b);return l};b.prototype.lin2log=function(b){return Math.pow(10,b)};b.prototype.log2lin=function(b){return Math.log(b)/Math.LN10};return b}();b=function(){function b(){}b.compose=function(b){b.keepProps.push("logarithmic");D(b,"init",function(b){var e=this.logarithmic;"logarithmic"!==b.userOptions.type?this.logarithmic=void 0:e||(this.logarithmic=new C(this))});D(b,"afterInit",function(){var b=this.logarithmic;b&&(this.lin2val=
function(e){return b.lin2log(e)},this.val2lin=function(e){return b.log2lin(e)})})};return b}();b.compose(e);return b});O(e,"Core/Axis/PlotLineOrBand.js",[e["Core/Axis/Axis.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=z.arrayMax,G=z.arrayMin,C=z.defined,B=z.destroyObjectProperties,x=z.erase,w=z.extend,v=z.fireEvent,f=z.isNumber,d=z.merge,q=z.objectEach,k=z.pick;z=function(){function b(d,b){this.axis=d;b&&(this.options=b,this.id=b.id)}b.prototype.render=
function(){v(this,"render");var b=this,e=b.axis,f=e.horiz,l=e.logarithmic,E=b.options,m=E.label,c=b.label,g=E.to,a=E.from,h=E.value,r=C(a)&&C(g),A=C(h),y=b.svgElem,L=!y,P=[],R=E.color,w=k(E.zIndex,0),Q=E.events;P={"class":"highcharts-plot-"+(r?"band ":"line ")+(E.className||"")};var M={},t=e.chart.renderer,p=r?"bands":"lines";l&&(a=l.log2lin(a),g=l.log2lin(g),h=l.log2lin(h));e.chart.styledMode||(A?(P.stroke=R||I.neutralColor40,P["stroke-width"]=k(E.width,1),E.dashStyle&&(P.dashstyle=E.dashStyle)):
r&&(P.fill=R||I.highlightColor10,E.borderWidth&&(P.stroke=E.borderColor,P["stroke-width"]=E.borderWidth)));M.zIndex=w;p+="-"+w;(l=e.plotLinesAndBandsGroups[p])||(e.plotLinesAndBandsGroups[p]=l=t.g("plot-"+p).attr(M).add());L&&(b.svgElem=y=t.path().attr(P).add(l));if(A)P=e.getPlotLinePath({value:h,lineWidth:y.strokeWidth(),acrossPanes:E.acrossPanes});else if(r)P=e.getPlotBandPath(a,g,E);else return;!b.eventsAdded&&Q&&(q(Q,function(a,c){y.on(c,function(a){Q[c].apply(b,[a])})}),b.eventsAdded=!0);(L||
!y.d)&&P&&P.length?y.attr({d:P}):y&&(P?(y.show(!0),y.animate({d:P})):y.d&&(y.hide(),c&&(b.label=c=c.destroy())));m&&(C(m.text)||C(m.formatter))&&P&&P.length&&0<e.width&&0<e.height&&!P.isFlat?(m=d({align:f&&r&&"center",x:f?!r&&4:10,verticalAlign:!f&&r&&"middle",y:f?r?16:10:r?6:-4,rotation:f&&!r&&90},m),this.renderLabel(m,P,r,w)):c&&c.hide();return b};b.prototype.renderLabel=function(d,b,e,f){var l=this.label,m=this.axis.chart.renderer;l||(l={align:d.textAlign||d.align,rotation:d.rotation,"class":"highcharts-plot-"+
(e?"band":"line")+"-label "+(d.className||"")},l.zIndex=f,f=this.getLabelText(d),this.label=l=m.text(f,0,0,d.useHTML).attr(l).add(),this.axis.chart.styledMode||l.css(d.style));m=b.xBounds||[b[0][1],b[1][1],e?b[2][1]:b[0][1]];b=b.yBounds||[b[0][2],b[1][2],e?b[2][2]:b[0][2]];e=G(m);f=G(b);l.align(d,!1,{x:e,y:f,width:D(m)-e,height:D(b)-f});l.show(!0)};b.prototype.getLabelText=function(d){return C(d.formatter)?d.formatter.call(this):d.text};b.prototype.destroy=function(){x(this.axis.plotLinesAndBands,
this);delete this.axis;B(this)};return b}();w(e.prototype,{getPlotBandPath:function(d,b,e){void 0===e&&(e=this.options);var l=this.getPlotLinePath({value:b,force:!0,acrossPanes:e.acrossPanes});e=this.getPlotLinePath({value:d,force:!0,acrossPanes:e.acrossPanes});var k=[],q=this.horiz,m=1;d=!f(this.min)||!f(this.max)||d<this.min&&b<this.min||d>this.max&&b>this.max;if(e&&l){if(d){var c=e.toString()===l.toString();m=0}for(d=0;d<e.length;d+=2){b=e[d];var g=e[d+1],a=l[d],h=l[d+1];"M"!==b[0]&&"L"!==b[0]||
"M"!==g[0]&&"L"!==g[0]||"M"!==a[0]&&"L"!==a[0]||"M"!==h[0]&&"L"!==h[0]||(q&&a[1]===b[1]?(a[1]+=m,h[1]+=m):q||a[2]!==b[2]||(a[2]+=m,h[2]+=m),k.push(["M",b[1],b[2]],["L",g[1],g[2]],["L",h[1],h[2]],["L",a[1],a[2]],["Z"]));k.isFlat=c}}return k},addPlotBand:function(d){return this.addPlotBandOrLine(d,"plotBands")},addPlotLine:function(d){return this.addPlotBandOrLine(d,"plotLines")},addPlotBandOrLine:function(d,e){var f=this,l=new b.PlotLineOrBand(this,d),k=this.userOptions;this.visible&&(l=l.render());
if(l){this._addedPlotLB||(this._addedPlotLB=!0,(k.plotLines||[]).concat(k.plotBands||[]).forEach(function(d){f.addPlotBandOrLine(d)}));if(e){var q=k[e]||[];q.push(d);k[e]=q}this.plotLinesAndBands.push(l)}return l},removePlotBandOrLine:function(d){for(var b=this.plotLinesAndBands,e=this.options,f=this.userOptions,l=b.length;l--;)b[l].id===d&&b[l].destroy();[e.plotLines||[],f.plotLines||[],e.plotBands||[],f.plotBands||[]].forEach(function(b){for(l=b.length;l--;)(b[l]||{}).id===d&&x(b,b[l])})},removePlotBand:function(d){this.removePlotBandOrLine(d)},
removePlotLine:function(d){this.removePlotBandOrLine(d)}});b.PlotLineOrBand=z;return b.PlotLineOrBand});O(e,"Core/Tooltip.js",[e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=e.format,G=b.doc,C=z.clamp,B=z.css,x=z.defined,w=z.discardElement,v=z.extend,f=z.fireEvent,d=z.isArray,q=z.isNumber,k=z.isString,l=z.merge,N=z.pick,u=z.splat,n=z.syncTimeout,J=z.timeUnits;"";e=function(){function e(d,c){this.container=void 0;this.crosshairs=
[];this.distance=0;this.isHidden=!0;this.isSticky=!1;this.now={};this.options={};this.outside=!1;this.chart=d;this.init(d,c)}e.prototype.applyFilter=function(){var d=this.chart;d.renderer.definition({tagName:"filter",attributes:{id:"drop-shadow-"+d.index,opacity:.5},children:[{tagName:"feGaussianBlur",attributes:{"in":"SourceAlpha",stdDeviation:1}},{tagName:"feOffset",attributes:{dx:1,dy:1}},{tagName:"feComponentTransfer",children:[{tagName:"feFuncA",attributes:{type:"linear",slope:.3}}]},{tagName:"feMerge",
children:[{tagName:"feMergeNode"},{tagName:"feMergeNode",attributes:{"in":"SourceGraphic"}}]}]});d.renderer.definition({tagName:"style",textContent:".highcharts-tooltip-"+d.index+"{filter:url(#drop-shadow-"+d.index+")}"})};e.prototype.bodyFormatter=function(d){return d.map(function(c){var d=c.series.tooltipOptions;return(d[(c.point.formatPrefix||"point")+"Formatter"]||c.point.tooltipFormatter).call(c.point,d[(c.point.formatPrefix||"point")+"Format"]||"")})};e.prototype.cleanSplit=function(d){this.chart.series.forEach(function(c){var b=
c&&c.tt;b&&(!b.isActive||d?c.tt=b.destroy():b.isActive=!1)})};e.prototype.defaultFormatter=function(d){var c=this.points||u(this);var b=[d.tooltipFooterHeaderFormatter(c[0])];b=b.concat(d.bodyFormatter(c));b.push(d.tooltipFooterHeaderFormatter(c[0],!0));return b};e.prototype.destroy=function(){this.label&&(this.label=this.label.destroy());this.split&&this.tt&&(this.cleanSplit(this.chart,!0),this.tt=this.tt.destroy());this.renderer&&(this.renderer=this.renderer.destroy(),w(this.container));z.clearTimeout(this.hideTimer);
z.clearTimeout(this.tooltipTimeout)};e.prototype.getAnchor=function(d,c){var b=this.chart;var a=b.pointer;var h=b.inverted,e=b.plotTop,f=b.plotLeft,m=0,l=0,k,n;d=u(d);this.followPointer&&c?("undefined"===typeof c.chartX&&(c=a.normalize(c)),a=[c.chartX-f,c.chartY-e]):d[0].tooltipPos?a=d[0].tooltipPos:(d.forEach(function(a){k=a.series.yAxis;n=a.series.xAxis;m+=a.plotX||0;l+=a.plotLow?(a.plotLow+(a.plotHigh||0))/2:a.plotY||0;n&&k&&(h?(m+=e+b.plotHeight-n.len-n.pos,l+=f+b.plotWidth-k.len-k.pos):(m+=n.pos-
f,l+=k.pos-e))}),m/=d.length,l/=d.length,a=[h?b.plotWidth-l:m,h?b.plotHeight-m:l],this.shared&&1<d.length&&c&&(h?a[0]=c.chartX-f:a[1]=c.chartY-e));return a.map(Math.round)};e.prototype.getDateFormat=function(d,c,b,a){var h=this.chart.time,g=h.dateFormat("%m-%d %H:%M:%S.%L",c),e={millisecond:15,second:12,minute:9,hour:6,day:3},f="millisecond";for(m in J){if(d===J.week&&+h.dateFormat("%w",c)===b&&"00:00:00.000"===g.substr(6)){var m="week";break}if(J[m]>d){m=f;break}if(e[m]&&g.substr(e[m])!=="01-01 00:00:00.000".substr(e[m]))break;
"week"!==m&&(f=m)}if(m)var l=h.resolveDTLFormat(a[m]).main;return l};e.prototype.getLabel=function(){var d=this,c=this.chart.renderer,g=this.chart.styledMode,a=this.options,h="tooltip"+(x(a.className)?" "+a.className:""),e=a.style&&a.style.pointerEvents||(!this.followPointer&&a.stickOnContact?"auto":"none"),f,y=function(){d.inContact=!0},l=function(){var a=d.chart.hoverSeries;d.inContact=!1;if(a&&a.onMouseOut)a.onMouseOut()};if(!this.label){if(this.outside){var k=this.chart.options.chart.style;this.container=
f=b.doc.createElement("div");f.className="highcharts-tooltip-container";B(f,{position:"absolute",top:"1px",pointerEvents:e,zIndex:Math.max(this.options.style&&this.options.style.zIndex||0,(k&&k.zIndex||0)+3)});b.doc.body.appendChild(f);this.renderer=c=new b.Renderer(f,0,0,k,void 0,void 0,c.styledMode)}this.split?this.label=c.g(h):(this.label=c.label("",0,0,a.shape||"callout",null,null,a.useHTML,null,h).attr({padding:a.padding,r:a.borderRadius}),g||this.label.attr({fill:a.backgroundColor,"stroke-width":a.borderWidth}).css(a.style).css({pointerEvents:e}).shadow(a.shadow));
g&&(this.applyFilter(),this.label.addClass("highcharts-tooltip-"+this.chart.index));if(d.outside&&!d.split){var n=this.label,q=n.xSetter,u=n.ySetter;n.xSetter=function(a){q.call(n,d.distance);f.style.left=a+"px"};n.ySetter=function(a){u.call(n,d.distance);f.style.top=a+"px"}}this.label.on("mouseenter",y).on("mouseleave",l).attr({zIndex:8}).add()}return this.label};e.prototype.getPosition=function(d,c,b){var a=this.chart,h=this.distance,g={},e=a.inverted&&b.h||0,f,m=this.outside,l=m?G.documentElement.clientWidth-
2*h:a.chartWidth,k=m?Math.max(G.body.scrollHeight,G.documentElement.scrollHeight,G.body.offsetHeight,G.documentElement.offsetHeight,G.documentElement.clientHeight):a.chartHeight,n=a.pointer.getChartPosition(),q=function(g){var e="x"===g;return[g,e?l:k,e?d:c].concat(m?[e?d*n.scaleX:c*n.scaleY,e?n.left-h+(b.plotX+a.plotLeft)*n.scaleX:n.top-h+(b.plotY+a.plotTop)*n.scaleY,0,e?l:k]:[e?d:c,e?b.plotX+a.plotLeft:b.plotY+a.plotTop,e?a.plotLeft:a.plotTop,e?a.plotLeft+a.plotWidth:a.plotTop+a.plotHeight])},u=
q("y"),t=q("x"),p=!this.followPointer&&N(b.ttBelow,!a.inverted===!!b.negative),v=function(a,c,d,b,r,f,A){var y=m?"y"===a?h*n.scaleY:h*n.scaleX:h,l=(d-b)/2,F=b<r-h,k=r+h+b<c,K=r-y-d+l;r=r+y-l;if(p&&k)g[a]=r;else if(!p&&F)g[a]=K;else if(F)g[a]=Math.min(A-b,0>K-e?K:K-e);else if(k)g[a]=Math.max(f,r+e+d>c?r:r+e);else return!1},w=function(a,c,d,b,e){var r;e<h||e>c-h?r=!1:g[a]=e<d/2?1:e>c-b/2?c-b-2:e-d/2;return r},E=function(a){var c=u;u=t;t=c;f=a},F=function(){!1!==v.apply(0,u)?!1!==w.apply(0,t)||f||(E(!0),
F()):f?g.x=g.y=0:(E(!0),F())};(a.inverted||1<this.len)&&E();F();return g};e.prototype.getXDateFormat=function(d,c,b){c=c.dateTimeLabelFormats;var a=b&&b.closestPointRange;return(a?this.getDateFormat(a,d.x,b.options.startOfWeek,c):c.day)||c.year};e.prototype.hide=function(d){var c=this;z.clearTimeout(this.hideTimer);d=N(d,this.options.hideDelay,500);this.isHidden||(this.hideTimer=n(function(){c.getLabel().fadeOut(d?void 0:d);c.isHidden=!0},d))};e.prototype.init=function(d,c){this.chart=d;this.options=
c;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.split=c.split&&!d.inverted&&!d.polar;this.shared=c.shared||this.split;this.outside=N(c.outside,!(!d.scrollablePixelsX&&!d.scrollablePixelsY))};e.prototype.isStickyOnContact=function(){return!(this.followPointer||!this.options.stickOnContact||!this.inContact)};e.prototype.move=function(d,c,b,a){var h=this,g=h.now,e=!1!==h.options.animation&&!h.isHidden&&(1<Math.abs(d-g.x)||1<Math.abs(c-g.y)),f=h.followPointer||1<h.len;v(g,{x:e?(2*g.x+d)/
3:d,y:e?(g.y+c)/2:c,anchorX:f?void 0:e?(2*g.anchorX+b)/3:b,anchorY:f?void 0:e?(g.anchorY+a)/2:a});h.getLabel().attr(g);h.drawTracker();e&&(z.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){h&&h.move(d,c,b,a)},32))};e.prototype.refresh=function(b,c){var g=this.chart,a=this.options,h=u(b),e=h[0],m={},y=[],l=a.formatter||this.defaultFormatter;m=this.shared;var k=g.styledMode;if(a.enabled){z.clearTimeout(this.hideTimer);this.followPointer=!this.split&&e.series.tooltipOptions.followPointer;
var n=this.getAnchor(b,c);var q=n[0];var v=n[1];!m||!d(b)&&b.series&&b.series.noSharedTooltip?m=e.getLabelConfig():(g.pointer.applyInactiveState(h),h.forEach(function(a){a.setState("hover");y.push(a.getLabelConfig())}),m={x:e.category,y:e.y},m.points=y);this.len=y.length;b=l.call(m,this);l=e.series;this.distance=N(l.tooltipOptions.distance,16);if(!1===b)this.hide();else{if(this.split)this.renderSplit(b,h);else if(h=q,m=v,c&&g.pointer.isDirectTouch&&(h=c.chartX-g.plotLeft,m=c.chartY-g.plotTop),g.polar||
!1===l.options.clip||l.shouldShowTooltip(h,m))c=this.getLabel(),a.style.width&&!k||c.css({width:this.chart.spacingBox.width+"px"}),c.attr({text:b&&b.join?b.join(""):b}),c.removeClass(/highcharts-color-[\d]+/g).addClass("highcharts-color-"+N(e.colorIndex,l.colorIndex)),k||c.attr({stroke:a.borderColor||e.color||l.color||I.neutralColor60}),this.updatePosition({plotX:q,plotY:v,negative:e.negative,ttBelow:e.ttBelow,h:n[2]||0});else{this.hide();return}this.isHidden&&this.label&&this.label.attr({opacity:1}).show();
this.isHidden=!1}f(this,"refresh")}};e.prototype.renderSplit=function(d,c){function g(c,d,b,g,h){void 0===h&&(h=!0);b?(d=X?0:ba,c=C(c-g/2,S.left,S.right-g-(a.outside?U:0))):(d-=B,c=h?c-g-J:c+J,c=C(c,h?c:S.left,S.right));return{x:c,y:d}}var a=this,h=a.chart,e=a.chart,f=e.chartWidth,m=e.chartHeight,l=e.plotHeight,n=e.plotLeft,q=e.plotTop,u=e.pointer,w=e.scrollablePixelsY;w=void 0===w?0:w;var E=e.scrollablePixelsX,t=e.scrollingContainer;t=void 0===t?{scrollLeft:0,scrollTop:0}:t;var p=t.scrollLeft;t=
t.scrollTop;var x=e.styledMode,J=a.distance,D=a.options,F=a.options.positioner,S=a.outside&&"number"!==typeof E?G.documentElement.getBoundingClientRect():{left:p,right:p+f,top:t,bottom:t+m},K=a.getLabel(),T=this.renderer||h.renderer,X=!(!h.xAxis[0]||!h.xAxis[0].opposite);h=u.getChartPosition();var U=h.left;h=h.top;var B=q+t,z=0,ba=l-w;k(d)&&(d=[!1,d]);d=d.slice(0,c.length+1).reduce(function(d,b,h){if(!1!==b&&""!==b){h=c[h-1]||{isHeader:!0,plotX:c[0].plotX,plotY:l,series:{}};var e=h.isHeader,r=e?a:
h.series;b=b.toString();var f=r.tt,m=h.isHeader;var A=h.series;var y="highcharts-color-"+N(h.colorIndex,A.colorIndex,"none");f||(f={padding:D.padding,r:D.borderRadius},x||(f.fill=D.backgroundColor,f["stroke-width"]=D.borderWidth),f=T.label("",0,0,D[m?"headerShape":"shape"]||"callout",void 0,void 0,D.useHTML).addClass((m?"highcharts-tooltip-header ":"")+"highcharts-tooltip-box "+y).attr(f).add(K));f.isActive=!0;f.attr({text:b});x||f.css(D.style).shadow(D.shadow).attr({stroke:D.borderColor||h.color||
A.color||I.neutralColor80});r=r.tt=f;m=r.getBBox();b=m.width+r.strokeWidth();e&&(z=m.height,ba+=z,X&&(B-=z));A=h.plotX;A=void 0===A?0:A;y=h.plotY;y=void 0===y?0:y;f=h.series;if(h.isHeader){A=n+A;var k=q+l/2}else{var p=f.xAxis,t=f.yAxis;A=p.pos+C(A,-J,p.len+J);f.shouldShowTooltip(0,t.pos-q+y,{ignoreX:!0})&&(k=t.pos+y)}A=C(A,S.left-J,S.right+J);"number"===typeof k?(m=m.height+1,y=F?F.call(a,b,m,h):g(A,k,e,b),d.push({align:F?0:void 0,anchorX:A,anchorY:k,boxWidth:b,point:h,rank:N(y.rank,e?1:0),size:m,
target:y.y,tt:r,x:y.x})):r.isActive=!1}return d},[]);!F&&d.some(function(c){var d=(a.outside?U:0)+c.anchorX;return d<S.left&&d+c.boxWidth<S.right?!0:d<U-S.left+c.boxWidth&&S.right-d>d})&&(d=d.map(function(a){var c=g(a.anchorX,a.anchorY,a.point.isHeader,a.boxWidth,!1);return v(a,{target:c.y,x:c.x})}));a.cleanSplit();b.distribute(d,ba);var H=U,ca=U;d.forEach(function(c){var d=c.x,b=c.boxWidth;c=c.isHeader;c||(a.outside&&U+d<H&&(H=U+d),!c&&a.outside&&H+b>ca&&(ca=U+d))});d.forEach(function(c){var d=c.x,
b=c.anchorX,h=c.pos,g=c.point.isHeader;h={visibility:"undefined"===typeof h?"hidden":"inherit",x:d,y:h+B,anchorX:b,anchorY:c.anchorY};if(a.outside&&d<b){var e=U-H;0<e&&(g||(h.x=d+e,h.anchorX=b+e),g&&(h.x=(ca-H)/2,h.anchorX=b+e))}c.tt.attr(h)});d=a.container;w=a.renderer;a.outside&&d&&w&&(e=K.getBBox(),w.setSize(e.width+e.x,e.height+e.y,!1),d.style.left=H+"px",d.style.top=h+"px")};e.prototype.drawTracker=function(){if(this.followPointer||!this.options.stickOnContact)this.tracker&&this.tracker.destroy();
else{var d=this.chart,c=this.label,b=d.hoverPoint;if(c&&b){var a={x:0,y:0,width:0,height:0};b=this.getAnchor(b);var h=c.getBBox();b[0]+=d.plotLeft-c.translateX;b[1]+=d.plotTop-c.translateY;a.x=Math.min(0,b[0]);a.y=Math.min(0,b[1]);a.width=0>b[0]?Math.max(Math.abs(b[0]),h.width-b[0]):Math.max(Math.abs(b[0]),h.width);a.height=0>b[1]?Math.max(Math.abs(b[1]),h.height-Math.abs(b[1])):Math.max(Math.abs(b[1]),h.height);this.tracker?this.tracker.attr(a):(this.tracker=c.renderer.rect(a).addClass("highcharts-tracker").add(c),
d.styledMode||this.tracker.attr({fill:"rgba(0,0,0,0)"}))}}};e.prototype.styledModeFormat=function(d){return d.replace('style="font-size: 10px"','class="highcharts-header"').replace(/style="color:{(point|series)\.color}"/g,'class="highcharts-color-{$1.colorIndex}"')};e.prototype.tooltipFooterHeaderFormatter=function(d,c){var b=c?"footer":"header",a=d.series,h=a.tooltipOptions,e=h.xDateFormat,m=a.xAxis,l=m&&"datetime"===m.options.type&&q(d.key),k=h[b+"Format"];c={isFooter:c,labelConfig:d};f(this,"headerFormatter",
c,function(c){l&&!e&&(e=this.getXDateFormat(d,h,m));l&&e&&(d.point&&d.point.tooltipDateKeys||["key"]).forEach(function(a){k=k.replace("{point."+a+"}","{point."+a+":"+e+"}")});a.chart.styledMode&&(k=this.styledModeFormat(k));c.text=D(k,{point:d,series:a},this.chart)});return c.text};e.prototype.update=function(d){this.destroy();l(!0,this.chart.options.tooltip.userOptions,d);this.init(this.chart,l(!0,this.options,d))};e.prototype.updatePosition=function(d){var c=this.chart,b=c.pointer,a=this.getLabel(),
h=d.plotX+c.plotLeft;c=d.plotY+c.plotTop;b=b.getChartPosition();d=(this.options.positioner||this.getPosition).call(this,a.width,a.height,d);if(this.outside){var e=(this.options.borderWidth||0)+2*this.distance;this.renderer.setSize(a.width+e,a.height+e,!1);if(1!==b.scaleX||1!==b.scaleY)B(this.container,{transform:"scale("+b.scaleX+", "+b.scaleY+")"}),h*=b.scaleX,c*=b.scaleY;h+=b.left-d.x;c+=b.top-d.y}this.move(Math.round(d.x),Math.round(d.y||0),h,c)};return e}();b.Tooltip=e;return b.Tooltip});O(e,
"Core/Pointer.js",[e["Core/Color/Color.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Tooltip.js"],e["Core/Utilities.js"]],function(e,b,I,z,H){var D=e.parse,C=b.charts,B=b.noop,x=H.addEvent,w=H.attr,v=H.css,f=H.defined,d=H.extend,q=H.find,k=H.fireEvent,l=H.isNumber,N=H.isObject,u=H.objectEach,n=H.offset,J=H.pick,E=H.splat;"";e=function(){function e(c,d){this.lastValidTouch={};this.pinchDown=[];this.runChartClick=!1;this.eventsToUnbind=[];this.chart=c;this.hasDragged=!1;this.options=
d;this.init(c,d)}e.prototype.applyInactiveState=function(c){var d=[],a;(c||[]).forEach(function(c){a=c.series;d.push(a);a.linkedParent&&d.push(a.linkedParent);a.linkedSeries&&(d=d.concat(a.linkedSeries));a.navigatorSeries&&d.push(a.navigatorSeries)});this.chart.series.forEach(function(a){-1===d.indexOf(a)?a.setState("inactive",!0):a.options.inactiveOtherPoints&&a.setAllPointsToState("inactive")})};e.prototype.destroy=function(){var c=this;this.eventsToUnbind.forEach(function(c){return c()});this.eventsToUnbind=
[];b.chartCount||(b.unbindDocumentMouseUp&&(b.unbindDocumentMouseUp=b.unbindDocumentMouseUp()),b.unbindDocumentTouchEnd&&(b.unbindDocumentTouchEnd=b.unbindDocumentTouchEnd()));clearInterval(c.tooltipTimeout);u(c,function(d,a){c[a]=void 0})};e.prototype.drag=function(c){var d=this.chart,a=d.options.chart,b=c.chartX,e=c.chartY,f=this.zoomHor,l=this.zoomVert,m=d.plotLeft,k=d.plotTop,n=d.plotWidth,q=d.plotHeight,u=this.selectionMarker,v=this.mouseDownX||0,t=this.mouseDownY||0,p=N(a.panning)?a.panning&&
a.panning.enabled:a.panning,w=a.panKey&&c[a.panKey+"Key"];if(!u||!u.touch)if(b<m?b=m:b>m+n&&(b=m+n),e<k?e=k:e>k+q&&(e=k+q),this.hasDragged=Math.sqrt(Math.pow(v-b,2)+Math.pow(t-e,2)),10<this.hasDragged){var E=d.isInsidePlot(v-m,t-k,{visiblePlotOnly:!0});d.hasCartesianSeries&&(this.zoomX||this.zoomY)&&E&&!w&&!u&&(this.selectionMarker=u=d.renderer.rect(m,k,f?1:n,l?1:q,0).attr({"class":"highcharts-selection-marker",zIndex:7}).add(),d.styledMode||u.attr({fill:a.selectionMarkerFill||D(I.highlightColor80).setOpacity(.25).get()}));
u&&f&&(b-=v,u.attr({width:Math.abs(b),x:(0<b?0:b)+v}));u&&l&&(b=e-t,u.attr({height:Math.abs(b),y:(0<b?0:b)+t}));E&&!u&&p&&d.pan(c,a.panning)}};e.prototype.dragStart=function(c){var d=this.chart;d.mouseIsDown=c.type;d.cancelClick=!1;d.mouseDownX=this.mouseDownX=c.chartX;d.mouseDownY=this.mouseDownY=c.chartY};e.prototype.drop=function(c){var b=this,a=this.chart,h=this.hasPinched;if(this.selectionMarker){var e={originalEvent:c,xAxis:[],yAxis:[]},A=this.selectionMarker,m=A.attr?A.attr("x"):A.x,n=A.attr?
A.attr("y"):A.y,q=A.attr?A.attr("width"):A.width,u=A.attr?A.attr("height"):A.height,w;if(this.hasDragged||h)a.axes.forEach(function(a){if(a.zoomEnabled&&f(a.min)&&(h||b[{xAxis:"zoomX",yAxis:"zoomY"}[a.coll]])&&l(m)&&l(n)){var d=a.horiz,g="touchend"===c.type?a.minPixelPadding:0,r=a.toValue((d?m:n)+g);d=a.toValue((d?m+q:n+u)-g);e[a.coll].push({axis:a,min:Math.min(r,d),max:Math.max(r,d)});w=!0}}),w&&k(a,"selection",e,function(c){a.zoom(d(c,h?{animation:!1}:null))});l(a.index)&&(this.selectionMarker=
this.selectionMarker.destroy());h&&this.scaleGroups()}a&&l(a.index)&&(v(a.container,{cursor:a._cursor}),a.cancelClick=10<this.hasDragged,a.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[])};e.prototype.findNearestKDPoint=function(c,d,a){var b=this.chart,g=b.hoverPoint;b=b.tooltip;if(g&&b&&b.isStickyOnContact())return g;var e;c.forEach(function(c){var b=!(c.noSharedTooltip&&d)&&0>c.options.findNearestPointBy.indexOf("y");c=c.searchPoint(a,b);if((b=N(c,!0)&&c.series)&&!(b=!N(e,!0))){b=
e.distX-c.distX;var h=e.dist-c.dist,g=(c.series.group&&c.series.group.zIndex)-(e.series.group&&e.series.group.zIndex);b=0<(0!==b&&d?b:0!==h?h:0!==g?g:e.series.index>c.series.index?-1:1)}b&&(e=c)});return e};e.prototype.getChartCoordinatesFromPoint=function(c,d){var a=c.series,b=a.xAxis;a=a.yAxis;var g=c.shapeArgs;if(b&&a){var e=J(c.clientX,c.plotX),f=c.plotY||0;c.isNode&&g&&l(g.x)&&l(g.y)&&(e=g.x,f=g.y);return d?{chartX:a.len+a.pos-f,chartY:b.len+b.pos-e}:{chartX:e+b.pos,chartY:f+a.pos}}if(g&&g.x&&
g.y)return{chartX:g.x,chartY:g.y}};e.prototype.getChartPosition=function(){if(this.chartPosition)return this.chartPosition;var c=this.chart.container,d=n(c);this.chartPosition={left:d.left,top:d.top,scaleX:1,scaleY:1};var a=c.offsetWidth;c=c.offsetHeight;2<a&&2<c&&(this.chartPosition.scaleX=d.width/a,this.chartPosition.scaleY=d.height/c);return this.chartPosition};e.prototype.getCoordinates=function(c){var d={xAxis:[],yAxis:[]};this.chart.axes.forEach(function(a){d[a.isXAxis?"xAxis":"yAxis"].push({axis:a,
value:a.toValue(c[a.horiz?"chartX":"chartY"])})});return d};e.prototype.getHoverData=function(c,d,a,b,e,f){var h,g=[];b=!(!b||!c);var r=d&&!d.stickyTracking,l={chartX:f?f.chartX:void 0,chartY:f?f.chartY:void 0,shared:e};k(this,"beforeGetHoverData",l);r=r?[d]:a.filter(function(a){return l.filter?l.filter(a):a.visible&&!(!e&&a.directTouch)&&J(a.options.enableMouseTracking,!0)&&a.stickyTracking});d=(h=b||!f?c:this.findNearestKDPoint(r,e,f))&&h.series;h&&(e&&!d.noSharedTooltip?(r=a.filter(function(a){return l.filter?
l.filter(a):a.visible&&!(!e&&a.directTouch)&&J(a.options.enableMouseTracking,!0)&&!a.noSharedTooltip}),r.forEach(function(a){var c=q(a.points,function(a){return a.x===h.x&&!a.isNull});N(c)&&(a.chart.isBoosting&&(c=a.getPoint(c)),g.push(c))})):g.push(h));l={hoverPoint:h};k(this,"afterGetHoverData",l);return{hoverPoint:l.hoverPoint,hoverSeries:d,hoverPoints:g}};e.prototype.getPointFromEvent=function(c){c=c.target;for(var d;c&&!d;)d=c.point,c=c.parentNode;return d};e.prototype.onTrackerMouseOut=function(c){c=
c.relatedTarget||c.toElement;var d=this.chart.hoverSeries;this.isDirectTouch=!1;if(!(!d||!c||d.stickyTracking||this.inClass(c,"highcharts-tooltip")||this.inClass(c,"highcharts-series-"+d.index)&&this.inClass(c,"highcharts-tracker")))d.onMouseOut()};e.prototype.inClass=function(c,d){for(var a;c;){if(a=w(c,"class")){if(-1!==a.indexOf(d))return!0;if(-1!==a.indexOf("highcharts-container"))return!1}c=c.parentNode}};e.prototype.init=function(c,d){this.options=d;this.chart=c;this.runChartClick=!(!d.chart.events||
!d.chart.events.click);this.pinchDown=[];this.lastValidTouch={};z&&(c.tooltip=new z(c,d.tooltip),this.followTouchMove=J(d.tooltip.followTouchMove,!0));this.setDOMEvents()};e.prototype.normalize=function(c,b){var a=c.touches,h=a?a.length?a.item(0):J(a.changedTouches,c.changedTouches)[0]:c;b||(b=this.getChartPosition());a=h.pageX-b.left;h=h.pageY-b.top;a/=b.scaleX;h/=b.scaleY;return d(c,{chartX:Math.round(a),chartY:Math.round(h)})};e.prototype.onContainerClick=function(c){var b=this.chart,a=b.hoverPoint;
c=this.normalize(c);var h=b.plotLeft,e=b.plotTop;b.cancelClick||(a&&this.inClass(c.target,"highcharts-tracker")?(k(a.series,"click",d(c,{point:a})),b.hoverPoint&&a.firePointEvent("click",c)):(d(c,this.getCoordinates(c)),b.isInsidePlot(c.chartX-h,c.chartY-e,{visiblePlotOnly:!0})&&k(b,"click",c)))};e.prototype.onContainerMouseDown=function(c){var d=1===((c.buttons||c.button)&1);c=this.normalize(c);if(b.isFirefox&&0!==c.button)this.onContainerMouseMove(c);if("undefined"===typeof c.button||d)this.zoomOption(c),
d&&c.preventDefault&&c.preventDefault(),this.dragStart(c)};e.prototype.onContainerMouseLeave=function(c){var d=C[J(b.hoverChartIndex,-1)],a=this.chart.tooltip;c=this.normalize(c);d&&(c.relatedTarget||c.toElement)&&(d.pointer.reset(),d.pointer.chartPosition=void 0);a&&!a.isHidden&&this.reset()};e.prototype.onContainerMouseEnter=function(c){delete this.chartPosition};e.prototype.onContainerMouseMove=function(c){var d=this.chart;c=this.normalize(c);this.setHoverChartIndex();c.preventDefault||(c.returnValue=
!1);("mousedown"===d.mouseIsDown||this.touchSelect(c))&&this.drag(c);d.openMenu||!this.inClass(c.target,"highcharts-tracker")&&!d.isInsidePlot(c.chartX-d.plotLeft,c.chartY-d.plotTop,{visiblePlotOnly:!0})||this.runPointActions(c)};e.prototype.onDocumentTouchEnd=function(c){C[b.hoverChartIndex]&&C[b.hoverChartIndex].pointer.drop(c)};e.prototype.onContainerTouchMove=function(c){if(this.touchSelect(c))this.onContainerMouseMove(c);else this.touch(c)};e.prototype.onContainerTouchStart=function(c){if(this.touchSelect(c))this.onContainerMouseDown(c);
else this.zoomOption(c),this.touch(c,!0)};e.prototype.onDocumentMouseMove=function(c){var d=this.chart,a=this.chartPosition;c=this.normalize(c,a);var b=d.tooltip;!a||b&&b.isStickyOnContact()||d.isInsidePlot(c.chartX-d.plotLeft,c.chartY-d.plotTop,{visiblePlotOnly:!0})||this.inClass(c.target,"highcharts-tracker")||this.reset()};e.prototype.onDocumentMouseUp=function(c){var d=C[J(b.hoverChartIndex,-1)];d&&d.pointer.drop(c)};e.prototype.pinch=function(c){var b=this,a=b.chart,h=b.pinchDown,e=c.touches||
[],f=e.length,l=b.lastValidTouch,m=b.hasZoom,k=b.selectionMarker,n={},q=1===f&&(b.inClass(c.target,"highcharts-tracker")&&a.runTrackerClick||b.runChartClick),u={};1<f&&(b.initiated=!0);m&&b.initiated&&!q&&!1!==c.cancelable&&c.preventDefault();[].map.call(e,function(a){return b.normalize(a)});"touchstart"===c.type?([].forEach.call(e,function(a,c){h[c]={chartX:a.chartX,chartY:a.chartY}}),l.x=[h[0].chartX,h[1]&&h[1].chartX],l.y=[h[0].chartY,h[1]&&h[1].chartY],a.axes.forEach(function(c){if(c.zoomEnabled){var d=
a.bounds[c.horiz?"h":"v"],b=c.minPixelPadding,h=c.toPixels(Math.min(J(c.options.min,c.dataMin),c.dataMin)),e=c.toPixels(Math.max(J(c.options.max,c.dataMax),c.dataMax)),g=Math.max(h,e);d.min=Math.min(c.pos,Math.min(h,e)-b);d.max=Math.max(c.pos+c.len,g+b)}}),b.res=!0):b.followTouchMove&&1===f?this.runPointActions(b.normalize(c)):h.length&&(k||(b.selectionMarker=k=d({destroy:B,touch:!0},a.plotBox)),b.pinchTranslate(h,e,n,k,u,l),b.hasPinched=m,b.scaleGroups(n,u),b.res&&(b.res=!1,this.reset(!1,0)))};e.prototype.pinchTranslate=
function(c,d,a,b,e,f){this.zoomHor&&this.pinchTranslateDirection(!0,c,d,a,b,e,f);this.zoomVert&&this.pinchTranslateDirection(!1,c,d,a,b,e,f)};e.prototype.pinchTranslateDirection=function(c,d,a,b,e,f,l,m){var h=this.chart,g=c?"x":"y",r=c?"X":"Y",k="chart"+r,n=c?"width":"height",A=h["plot"+(c?"Left":"Top")],y,q,u=m||1,L=h.inverted,F=h.bounds[c?"h":"v"],v=1===d.length,K=d[0][k],w=a[0][k],E=!v&&d[1][k],x=!v&&a[1][k];a=function(){"number"===typeof x&&20<Math.abs(K-E)&&(u=m||Math.abs(w-x)/Math.abs(K-E));
q=(A-w)/u+K;y=h["plot"+(c?"Width":"Height")]/u};a();d=q;if(d<F.min){d=F.min;var J=!0}else d+y>F.max&&(d=F.max-y,J=!0);J?(w-=.8*(w-l[g][0]),"number"===typeof x&&(x-=.8*(x-l[g][1])),a()):l[g]=[w,x];L||(f[g]=q-A,f[n]=y);f=L?1/u:u;e[n]=y;e[g]=d;b[L?c?"scaleY":"scaleX":"scale"+r]=u;b["translate"+r]=f*A+(w-f*K)};e.prototype.reset=function(c,d){var a=this.chart,b=a.hoverSeries,e=a.hoverPoint,g=a.hoverPoints,f=a.tooltip,l=f&&f.shared?g:e;c&&l&&E(l).forEach(function(a){a.series.isCartesian&&"undefined"===
typeof a.plotX&&(c=!1)});if(c)f&&l&&E(l).length&&(f.refresh(l),f.shared&&g?g.forEach(function(a){a.setState(a.state,!0);a.series.isCartesian&&(a.series.xAxis.crosshair&&a.series.xAxis.drawCrosshair(null,a),a.series.yAxis.crosshair&&a.series.yAxis.drawCrosshair(null,a))}):e&&(e.setState(e.state,!0),a.axes.forEach(function(a){a.crosshair&&e.series[a.coll]===a&&a.drawCrosshair(null,e)})));else{if(e)e.onMouseOut();g&&g.forEach(function(a){a.setState()});if(b)b.onMouseOut();f&&f.hide(d);this.unDocMouseMove&&
(this.unDocMouseMove=this.unDocMouseMove());a.axes.forEach(function(a){a.hideCrosshair()});this.hoverX=a.hoverPoints=a.hoverPoint=null}};e.prototype.runPointActions=function(c,d){var a=this.chart,h=a.tooltip&&a.tooltip.options.enabled?a.tooltip:void 0,e=h?h.shared:!1,g=d||a.hoverPoint,f=g&&g.series||a.hoverSeries;f=this.getHoverData(g,f,a.series,(!c||"touchmove"!==c.type)&&(!!d||f&&f.directTouch&&this.isDirectTouch),e,c);g=f.hoverPoint;var l=f.hoverPoints;d=(f=f.hoverSeries)&&f.tooltipOptions.followPointer&&
!f.tooltipOptions.split;e=e&&f&&!f.noSharedTooltip;if(g&&(g!==a.hoverPoint||h&&h.isHidden)){(a.hoverPoints||[]).forEach(function(a){-1===l.indexOf(a)&&a.setState()});if(a.hoverSeries!==f)f.onMouseOver();this.applyInactiveState(l);(l||[]).forEach(function(a){a.setState("hover")});a.hoverPoint&&a.hoverPoint.firePointEvent("mouseOut");if(!g.series)return;a.hoverPoints=l;a.hoverPoint=g;g.firePointEvent("mouseOver");h&&h.refresh(e?l:g,c)}else d&&h&&!h.isHidden&&(g=h.getAnchor([{}],c),a.isInsidePlot(g[0],
g[1],{visiblePlotOnly:!0})&&h.updatePosition({plotX:g[0],plotY:g[1]}));this.unDocMouseMove||(this.unDocMouseMove=x(a.container.ownerDocument,"mousemove",function(a){var c=C[b.hoverChartIndex];if(c)c.pointer.onDocumentMouseMove(a)}),this.eventsToUnbind.push(this.unDocMouseMove));a.axes.forEach(function(d){var b=J((d.crosshair||{}).snap,!0),h;b&&((h=a.hoverPoint)&&h.series[d.coll]===d||(h=q(l,function(a){return a.series[d.coll]===d})));h||!b?d.drawCrosshair(c,h):d.hideCrosshair()})};e.prototype.scaleGroups=
function(c,d){var a=this.chart,b;a.series.forEach(function(h){b=c||h.getPlotBox();h.xAxis&&h.xAxis.zoomEnabled&&h.group&&(h.group.attr(b),h.markerGroup&&(h.markerGroup.attr(b),h.markerGroup.clip(d?a.clipRect:null)),h.dataLabelsGroup&&h.dataLabelsGroup.attr(b))});a.clipRect.attr(d||a.clipBox)};e.prototype.setDOMEvents=function(){var c=this,d=this.chart.container,a=d.ownerDocument;d.onmousedown=this.onContainerMouseDown.bind(this);d.onmousemove=this.onContainerMouseMove.bind(this);d.onclick=this.onContainerClick.bind(this);
this.eventsToUnbind.push(x(d,"mouseenter",this.onContainerMouseEnter.bind(this)));this.eventsToUnbind.push(x(d,"mouseleave",this.onContainerMouseLeave.bind(this)));b.unbindDocumentMouseUp||(b.unbindDocumentMouseUp=x(a,"mouseup",this.onDocumentMouseUp.bind(this)));for(var h=this.chart.renderTo.parentElement;h&&"BODY"!==h.tagName;)this.eventsToUnbind.push(x(h,"scroll",function(){delete c.chartPosition})),h=h.parentElement;b.hasTouch&&(this.eventsToUnbind.push(x(d,"touchstart",this.onContainerTouchStart.bind(this),
{passive:!1})),this.eventsToUnbind.push(x(d,"touchmove",this.onContainerTouchMove.bind(this),{passive:!1})),b.unbindDocumentTouchEnd||(b.unbindDocumentTouchEnd=x(a,"touchend",this.onDocumentTouchEnd.bind(this),{passive:!1})))};e.prototype.setHoverChartIndex=function(){var c=this.chart,d=b.charts[J(b.hoverChartIndex,-1)];if(d&&d!==c)d.pointer.onContainerMouseLeave({relatedTarget:!0});d&&d.mouseIsDown||(b.hoverChartIndex=c.index)};e.prototype.touch=function(c,d){var a=this.chart,b;this.setHoverChartIndex();
if(1===c.touches.length)if(c=this.normalize(c),(b=a.isInsidePlot(c.chartX-a.plotLeft,c.chartY-a.plotTop,{visiblePlotOnly:!0}))&&!a.openMenu){d&&this.runPointActions(c);if("touchmove"===c.type){d=this.pinchDown;var e=d[0]?4<=Math.sqrt(Math.pow(d[0].chartX-c.chartX,2)+Math.pow(d[0].chartY-c.chartY,2)):!1}J(e,!0)&&this.pinch(c)}else d&&this.reset();else 2===c.touches.length&&this.pinch(c)};e.prototype.touchSelect=function(c){return!(!this.chart.options.chart.zoomBySingleTouch||!c.touches||1!==c.touches.length)};
e.prototype.zoomOption=function(c){var d=this.chart,a=d.options.chart,b=a.zoomType||"";d=d.inverted;/touch/.test(c.type)&&(b=J(a.pinchType,b));this.zoomX=c=/x/.test(b);this.zoomY=b=/y/.test(b);this.zoomHor=c&&!d||b&&d;this.zoomVert=b&&!d||c&&d;this.hasZoom=c||b};return e}();return b.Pointer=e});O(e,"Core/MSPointer.js",[e["Core/Globals.js"],e["Core/Pointer.js"],e["Core/Utilities.js"]],function(e,b,I){function D(){var d=[];d.item=function(d){return this[d]};f(q,function(b){d.push({pageX:b.pageX,pageY:b.pageY,
target:b.target})});return d}function H(d,b,f,k){"touch"!==d.pointerType&&d.pointerType!==d.MSPOINTER_TYPE_TOUCH||!C[e.hoverChartIndex]||(k(d),k=C[e.hoverChartIndex].pointer,k[b]({type:f,target:d.currentTarget,preventDefault:x,touches:D()}))}var G=this&&this.__extends||function(){var d=function(b,e){d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var e in b)b.hasOwnProperty(e)&&(d[e]=b[e])};return d(b,e)};return function(b,e){function f(){this.constructor=
b}d(b,e);b.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)}}(),C=e.charts,B=e.doc,x=e.noop,w=I.addEvent,v=I.css,f=I.objectEach,d=I.removeEvent,q={},k=!!e.win.PointerEvent;return function(b){function e(){return null!==b&&b.apply(this,arguments)||this}G(e,b);e.prototype.batchMSEvents=function(d){d(this.chart.container,k?"pointerdown":"MSPointerDown",this.onContainerPointerDown);d(this.chart.container,k?"pointermove":"MSPointerMove",this.onContainerPointerMove);d(B,k?"pointerup":
"MSPointerUp",this.onDocumentPointerUp)};e.prototype.destroy=function(){this.batchMSEvents(d);b.prototype.destroy.call(this)};e.prototype.init=function(d,e){b.prototype.init.call(this,d,e);this.hasZoom&&v(d.container,{"-ms-touch-action":"none","touch-action":"none"})};e.prototype.onContainerPointerDown=function(d){H(d,"onContainerTouchStart","touchstart",function(d){q[d.pointerId]={pageX:d.pageX,pageY:d.pageY,target:d.currentTarget}})};e.prototype.onContainerPointerMove=function(d){H(d,"onContainerTouchMove",
"touchmove",function(d){q[d.pointerId]={pageX:d.pageX,pageY:d.pageY};q[d.pointerId].target||(q[d.pointerId].target=d.currentTarget)})};e.prototype.onDocumentPointerUp=function(d){H(d,"onDocumentTouchEnd","touchend",function(d){delete q[d.pointerId]})};e.prototype.setDOMEvents=function(){b.prototype.setDOMEvents.call(this);(this.hasZoom||this.followTouchMove)&&this.batchMSEvents(w)};return e}(b)});O(e,"Core/Series/Point.js",[e["Core/Renderer/HTML/AST.js"],e["Core/Animation/AnimationUtilities.js"],
e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Options.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G){var D=b.animObject,B=I.format,x=H.defaultOptions,w=G.addEvent,v=G.defined,f=G.erase,d=G.extend,q=G.fireEvent,k=G.getNestedProperty,l=G.isArray,N=G.isFunction,u=G.isNumber,n=G.isObject,J=G.merge,E=G.objectEach,m=G.pick,c=G.syncTimeout,g=G.removeEvent,a=G.uniqueKey;"";b=function(){function b(){this.colorIndex=this.category=void 0;this.formatPrefix="point";this.id=void 0;this.isNull=!1;
this.percentage=this.options=this.name=void 0;this.selected=!1;this.total=this.series=void 0;this.visible=!0;this.x=void 0}b.prototype.animateBeforeDestroy=function(){var a=this,c={x:a.startXPos,opacity:0},b,e=a.getGraphicalProps();e.singular.forEach(function(d){b="dataLabel"===d;a[d]=a[d].animate(b?{x:a[d].startXPos,y:a[d].startYPos,opacity:0}:c)});e.plural.forEach(function(c){a[c].forEach(function(c){c.element&&c.animate(d({x:a.startXPos},c.startYPos?{x:c.startXPos,y:c.startYPos}:{}))})})};b.prototype.applyOptions=
function(a,c){var e=this.series,h=e.options.pointValKey||e.pointValKey;a=b.prototype.optionsToObject.call(this,a);d(this,a);this.options=this.options?d(this.options,a):a;a.group&&delete this.group;a.dataLabels&&delete this.dataLabels;h&&(this.y=b.prototype.getNestedProperty.call(this,h));this.formatPrefix=(this.isNull=m(this.isValid&&!this.isValid(),null===this.x||!u(this.y)))?"null":"point";this.selected&&(this.state="select");"name"in this&&"undefined"===typeof c&&e.xAxis&&e.xAxis.hasNames&&(this.x=
e.xAxis.nameToX(this));"undefined"===typeof this.x&&e&&(this.x="undefined"===typeof c?e.autoIncrement(this):c);return this};b.prototype.destroy=function(){function a(){if(d.graphic||d.dataLabel||d.dataLabels)g(d),d.destroyElements();for(m in d)d[m]=null}var d=this,b=d.series,e=b.chart;b=b.options.dataSorting;var h=e.hoverPoints,l=D(d.series.chart.renderer.globalAnimation),m;d.legendItem&&e.legend.destroyItem(d);h&&(d.setState(),f(h,d),h.length||(e.hoverPoints=null));if(d===e.hoverPoint)d.onMouseOut();
b&&b.enabled?(this.animateBeforeDestroy(),c(a,l.duration)):a();e.pointCount--};b.prototype.destroyElements=function(a){var c=this;a=c.getGraphicalProps(a);a.singular.forEach(function(a){c[a]=c[a].destroy()});a.plural.forEach(function(a){c[a].forEach(function(a){a.element&&a.destroy()});delete c[a]})};b.prototype.firePointEvent=function(a,c,d){var b=this,e=this.series.options;(e.point.events[a]||b.options&&b.options.events&&b.options.events[a])&&b.importEvents();"click"===a&&e.allowPointSelect&&(d=
function(a){b.select&&b.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});q(b,a,c,d)};b.prototype.getClassName=function(){return"highcharts-point"+(this.selected?" highcharts-point-select":"")+(this.negative?" highcharts-negative":"")+(this.isNull?" highcharts-null-point":"")+("undefined"!==typeof this.colorIndex?" highcharts-color-"+this.colorIndex:"")+(this.options.className?" "+this.options.className:"")+(this.zone&&this.zone.className?" "+this.zone.className.replace("highcharts-negative",""):"")};
b.prototype.getGraphicalProps=function(a){var c=this,d=[],b,e={singular:[],plural:[]};a=a||{graphic:1,dataLabel:1};a.graphic&&d.push("graphic","upperGraphic","shadowGroup");a.dataLabel&&d.push("dataLabel","dataLabelUpper","connector");for(b=d.length;b--;){var h=d[b];c[h]&&e.singular.push(h)}["dataLabel","connector"].forEach(function(d){var b=d+"s";a[d]&&c[b]&&e.plural.push(b)});return e};b.prototype.getLabelConfig=function(){return{x:this.category,y:this.y,color:this.color,colorIndex:this.colorIndex,
key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}};b.prototype.getNestedProperty=function(a){if(a)return 0===a.indexOf("custom.")?k(a,this.options):this[a]};b.prototype.getZone=function(){var a=this.series,c=a.zones;a=a.zoneAxis||"y";var d=0,b;for(b=c[d];this[a]>=b.value;)b=c[++d];this.nonZonedColor||(this.nonZonedColor=this.color);this.color=b&&b.color&&!this.options.color?b.color:this.nonZonedColor;return b};b.prototype.hasNewShapeType=
function(){return(this.graphic&&(this.graphic.symbolName||this.graphic.element.nodeName))!==this.shapeType};b.prototype.init=function(c,d,b){this.series=c;this.applyOptions(d,b);this.id=v(this.id)?this.id:a();this.resolveColor();c.chart.pointCount++;q(this,"afterInit");return this};b.prototype.optionsToObject=function(a){var c={},d=this.series,e=d.options.keys,h=e||d.pointArrayMap||["y"],g=h.length,f=0,r=0;if(u(a)||null===a)c[h[0]]=a;else if(l(a))for(!e&&a.length>g&&(d=typeof a[0],"string"===d?c.name=
a[0]:"number"===d&&(c.x=a[0]),f++);r<g;)e&&"undefined"===typeof a[f]||(0<h[r].indexOf(".")?b.prototype.setNestedProperty(c,a[f],h[r]):c[h[r]]=a[f]),f++,r++;else"object"===typeof a&&(c=a,a.dataLabels&&(d._hasPointLabels=!0),a.marker&&(d._hasPointMarkers=!0));return c};b.prototype.resolveColor=function(){var a=this.series;var c=a.chart.options.chart.colorCount;var d=a.chart.styledMode;delete this.nonZonedColor;if(a.options.colorByPoint){if(!d){c=a.options.colors||a.chart.options.colors;var b=c[a.colorCounter];
c=c.length}d=a.colorCounter;a.colorCounter++;a.colorCounter===c&&(a.colorCounter=0)}else d||(b=a.color),d=a.colorIndex;this.colorIndex=m(this.options.colorIndex,d);this.color=m(this.options.color,b)};b.prototype.setNestedProperty=function(a,c,d){d.split(".").reduce(function(a,d,b,e){a[d]=e.length-1===b?c:n(a[d],!0)?a[d]:{};return a[d]},a);return a};b.prototype.tooltipFormatter=function(a){var c=this.series,d=c.tooltipOptions,b=m(d.valueDecimals,""),e=d.valuePrefix||"",h=d.valueSuffix||"";c.chart.styledMode&&
(a=c.chart.tooltip.styledModeFormat(a));(c.pointArrayMap||["y"]).forEach(function(c){c="{point."+c;if(e||h)a=a.replace(RegExp(c+"}","g"),e+c+"}"+h);a=a.replace(RegExp(c+"}","g"),c+":,."+b+"f}")});return B(a,{point:this,series:this.series},c.chart)};b.prototype.update=function(a,c,d,b){function e(){h.applyOptions(a);var b=f&&h.hasDummyGraphic;b=null===h.y?!b:b;f&&b&&(h.graphic=f.destroy(),delete h.hasDummyGraphic);n(a,!0)&&(f&&f.element&&a&&a.marker&&"undefined"!==typeof a.marker.symbol&&(h.graphic=
f.destroy()),a&&a.dataLabels&&h.dataLabel&&(h.dataLabel=h.dataLabel.destroy()),h.connector&&(h.connector=h.connector.destroy()));r=h.index;g.updateParallelArrays(h,r);k.data[r]=n(k.data[r],!0)||n(a,!0)?h.options:m(a,k.data[r]);g.isDirty=g.isDirtyData=!0;!g.fixedBox&&g.hasCartesianSeries&&(l.isDirtyBox=!0);"point"===k.legendType&&(l.isDirtyLegend=!0);c&&l.redraw(d)}var h=this,g=h.series,f=h.graphic,r,l=g.chart,k=g.options;c=m(c,!0);!1===b?e():h.firePointEvent("update",{options:a},e)};b.prototype.remove=
function(a,c){this.series.removePoint(this.series.data.indexOf(this),a,c)};b.prototype.select=function(a,c){var d=this,b=d.series,e=b.chart;this.selectedStaging=a=m(a,!d.selected);d.firePointEvent(a?"select":"unselect",{accumulate:c},function(){d.selected=d.options.selected=a;b.options.data[b.data.indexOf(d)]=d.options;d.setState(a&&"select");c||e.getSelectedPoints().forEach(function(a){var c=a.series;a.selected&&a!==d&&(a.selected=a.options.selected=!1,c.options.data[c.data.indexOf(a)]=a.options,
a.setState(e.hoverPoints&&c.options.inactiveOtherPoints?"inactive":""),a.firePointEvent("unselect"))})});delete this.selectedStaging};b.prototype.onMouseOver=function(a){var c=this.series.chart,d=c.pointer;a=a?d.normalize(a):d.getChartCoordinatesFromPoint(this,c.inverted);d.runPointActions(a,this)};b.prototype.onMouseOut=function(){var a=this.series.chart;this.firePointEvent("mouseOut");this.series.options.inactiveOtherPoints||(a.hoverPoints||[]).forEach(function(a){a.setState()});a.hoverPoints=a.hoverPoint=
null};b.prototype.importEvents=function(){if(!this.hasImportedEvents){var a=this,c=J(a.series.options.point,a.options).events;a.events=c;E(c,function(c,d){N(c)&&w(a,d,c)});this.hasImportedEvents=!0}};b.prototype.setState=function(a,c){var b=this.series,h=this.state,g=b.options.states[a||"normal"]||{},f=x.plotOptions[b.type].marker&&b.options.marker,r=f&&!1===f.enabled,l=f&&f.states&&f.states[a||"normal"]||{},k=!1===l.enabled,n=b.stateMarkerGraphic,p=this.marker||{},A=b.chart,v=b.halo,w,F=f&&b.markerAttribs;
a=a||"";if(!(a===this.state&&!c||this.selected&&"select"!==a||!1===g.enabled||a&&(k||r&&!1===l.enabled)||a&&p.states&&p.states[a]&&!1===p.states[a].enabled)){this.state=a;F&&(w=b.markerAttribs(this,a));if(this.graphic&&!this.hasDummyGraphic){h&&this.graphic.removeClass("highcharts-point-"+h);a&&this.graphic.addClass("highcharts-point-"+a);if(!A.styledMode){var S=b.pointAttribs(this,a);var K=m(A.options.chart.animation,g.animation);b.options.inactiveOtherPoints&&u(S.opacity)&&((this.dataLabels||[]).forEach(function(a){a&&
a.animate({opacity:S.opacity},K)}),this.connector&&this.connector.animate({opacity:S.opacity},K));this.graphic.animate(S,K)}w&&this.graphic.animate(w,m(A.options.chart.animation,l.animation,f.animation));n&&n.hide()}else{if(a&&l){h=p.symbol||b.symbol;n&&n.currentSymbol!==h&&(n=n.destroy());if(w)if(n)n[c?"animate":"attr"]({x:w.x,y:w.y});else h&&(b.stateMarkerGraphic=n=A.renderer.symbol(h,w.x,w.y,w.width,w.height).add(b.markerGroup),n.currentSymbol=h);!A.styledMode&&n&&n.attr(b.pointAttribs(this,a))}n&&
(n[a&&this.isInside?"show":"hide"](),n.element.point=this)}g=g.halo;w=(n=this.graphic||n)&&n.visibility||"inherit";g&&g.size&&n&&"hidden"!==w&&!this.isCluster?(v||(b.halo=v=A.renderer.path().add(n.parentGroup)),v.show()[c?"animate":"attr"]({d:this.haloPath(g.size)}),v.attr({"class":"highcharts-halo highcharts-color-"+m(this.colorIndex,b.colorIndex)+(this.className?" "+this.className:""),visibility:w,zIndex:-1}),v.point=this,A.styledMode||v.attr(d({fill:this.color||b.color,"fill-opacity":g.opacity},
e.filterUserAttributes(g.attributes||{})))):v&&v.point&&v.point.haloPath&&v.animate({d:v.point.haloPath(0)},null,v.hide);q(this,"afterSetState",{state:a})}};b.prototype.haloPath=function(a){return this.series.chart.renderer.symbols.circle(Math.floor(this.plotX)-a,this.plotY-a,2*a,2*a)};return b}();return z.Point=b});O(e,"Core/Legend.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Series/Point.js"],e["Core/Utilities.js"]],function(e,b,I,z,H){var D=
e.animObject,C=e.setAnimation,B=b.format;e=I.isFirefox;var x=I.marginNames;b=I.win;var w=H.addEvent,v=H.createElement,f=H.css,d=H.defined,q=H.discardElement,k=H.find,l=H.fireEvent,N=H.isNumber,u=H.merge,n=H.pick,J=H.relativeLength,E=H.stableSort,m=H.syncTimeout;H=H.wrap;var c=function(){function c(a,c){this.allItems=[];this.contentGroup=this.box=void 0;this.display=!1;this.group=void 0;this.offsetWidth=this.maxLegendWidth=this.maxItemWidth=this.legendWidth=this.legendHeight=this.lastLineHeight=this.lastItemY=
this.itemY=this.itemX=this.itemMarginTop=this.itemMarginBottom=this.itemHeight=this.initialItemY=0;this.options={};this.padding=0;this.pages=[];this.proximate=!1;this.scrollGroup=void 0;this.widthOption=this.totalItemWidth=this.titleHeight=this.symbolWidth=this.symbolHeight=0;this.chart=a;this.init(a,c)}c.prototype.init=function(a,c){this.chart=a;this.setOptions(c);c.enabled&&(this.render(),w(this.chart,"endResize",function(){this.legend.positionCheckboxes()}),this.proximate?this.unchartrender=w(this.chart,
"render",function(){this.legend.proximatePositions();this.legend.positionItems()}):this.unchartrender&&this.unchartrender())};c.prototype.setOptions=function(a){var c=n(a.padding,8);this.options=a;this.chart.styledMode||(this.itemStyle=a.itemStyle,this.itemHiddenStyle=u(this.itemStyle,a.itemHiddenStyle));this.itemMarginTop=a.itemMarginTop||0;this.itemMarginBottom=a.itemMarginBottom||0;this.padding=c;this.initialItemY=c-5;this.symbolWidth=n(a.symbolWidth,16);this.pages=[];this.proximate="proximate"===
a.layout&&!this.chart.inverted;this.baseline=void 0};c.prototype.update=function(a,c){var d=this.chart;this.setOptions(u(!0,this.options,a));this.destroy();d.isDirtyLegend=d.isDirtyBox=!0;n(c,!0)&&d.redraw();l(this,"afterUpdate")};c.prototype.colorizeItem=function(a,c){a.legendGroup[c?"removeClass":"addClass"]("highcharts-legend-item-hidden");if(!this.chart.styledMode){var d=this.options,b=a.legendItem,e=a.legendLine,h=a.legendSymbol,g=this.itemHiddenStyle.color;d=c?d.itemStyle.color:g;var f=c?a.color||
g:g,m=a.options&&a.options.marker,k={fill:f};b&&b.css({fill:d,color:d});e&&e.attr({stroke:f});h&&(m&&h.isMarker&&(k=a.pointAttribs(),c||(k.stroke=k.fill=g)),h.attr(k))}l(this,"afterColorizeItem",{item:a,visible:c})};c.prototype.positionItems=function(){this.allItems.forEach(this.positionItem,this);this.chart.isResizing||this.positionCheckboxes()};c.prototype.positionItem=function(a){var c=this,b=this.options,e=b.symbolPadding,g=!b.rtl,f=a._legendItemPos;b=f[0];f=f[1];var k=a.checkbox,m=a.legendGroup;
m&&m.element&&(e={translateX:g?b:this.legendWidth-b-2*e-4,translateY:f},g=function(){l(c,"afterPositionItem",{item:a})},d(m.translateY)?m.animate(e,void 0,g):(m.attr(e),g()));k&&(k.x=b,k.y=f)};c.prototype.destroyItem=function(a){var c=a.checkbox;["legendItem","legendLine","legendSymbol","legendGroup"].forEach(function(c){a[c]&&(a[c]=a[c].destroy())});c&&q(a.checkbox)};c.prototype.destroy=function(){function a(a){this[a]&&(this[a]=this[a].destroy())}this.getAllItems().forEach(function(c){["legendItem",
"legendGroup"].forEach(a,c)});"clipRect up down pager nav box title group".split(" ").forEach(a,this);this.display=null};c.prototype.positionCheckboxes=function(){var a=this.group&&this.group.alignAttr,c=this.clipHeight||this.legendHeight,d=this.titleHeight;if(a){var b=a.translateY;this.allItems.forEach(function(e){var h=e.checkbox;if(h){var g=b+d+h.y+(this.scrollOffset||0)+3;f(h,{left:a.translateX+e.checkboxOffset+h.x-20+"px",top:g+"px",display:this.proximate||g>b-6&&g<b+c-6?"":"none"})}},this)}};
c.prototype.renderTitle=function(){var a=this.options,c=this.padding,d=a.title,b=0;d.text&&(this.title||(this.title=this.chart.renderer.label(d.text,c-3,c-4,null,null,null,a.useHTML,null,"legend-title").attr({zIndex:1}),this.chart.styledMode||this.title.css(d.style),this.title.add(this.group)),d.width||this.title.css({width:this.maxLegendWidth+"px"}),a=this.title.getBBox(),b=a.height,this.offsetWidth=a.width,this.contentGroup.attr({translateY:b}));this.titleHeight=b};c.prototype.setText=function(a){var c=
this.options;a.legendItem.attr({text:c.labelFormat?B(c.labelFormat,a,this.chart):c.labelFormatter.call(a)})};c.prototype.renderItem=function(a){var c=this.chart,d=c.renderer,b=this.options,e=this.symbolWidth,g=b.symbolPadding||0,f=this.itemStyle,l=this.itemHiddenStyle,k="horizontal"===b.layout?n(b.itemDistance,20):0,m=!b.rtl,q=a.legendItem,t=!a.series,p=!t&&a.series.drawLegendSymbol?a.series:a,v=p.options,w=this.createCheckboxForItem&&v&&v.showCheckbox;v=e+g+k+(w?20:0);var E=b.useHTML,F=a.options.className;
q||(a.legendGroup=d.g("legend-item").addClass("highcharts-"+p.type+"-series highcharts-color-"+a.colorIndex+(F?" "+F:"")+(t?" highcharts-series-"+a.index:"")).attr({zIndex:1}).add(this.scrollGroup),a.legendItem=q=d.text("",m?e+g:-g,this.baseline||0,E),c.styledMode||q.css(u(a.visible?f:l)),q.attr({align:m?"left":"right",zIndex:2}).add(a.legendGroup),this.baseline||(this.fontMetrics=d.fontMetrics(c.styledMode?12:f.fontSize,q),this.baseline=this.fontMetrics.f+3+this.itemMarginTop,q.attr("y",this.baseline),
this.symbolHeight=b.symbolHeight||this.fontMetrics.f,b.squareSymbol&&(this.symbolWidth=n(b.symbolWidth,Math.max(this.symbolHeight,16)),v=this.symbolWidth+g+k+(w?20:0),m&&q.attr("x",this.symbolWidth+g))),p.drawLegendSymbol(this,a),this.setItemEvents&&this.setItemEvents(a,q,E));w&&!a.checkbox&&this.createCheckboxForItem&&this.createCheckboxForItem(a);this.colorizeItem(a,a.visible);!c.styledMode&&f.width||q.css({width:(b.itemWidth||this.widthOption||c.spacingBox.width)-v+"px"});this.setText(a);c=q.getBBox();
a.itemWidth=a.checkboxOffset=b.itemWidth||a.legendItemWidth||c.width+v;this.maxItemWidth=Math.max(this.maxItemWidth,a.itemWidth);this.totalItemWidth+=a.itemWidth;this.itemHeight=a.itemHeight=Math.round(a.legendItemHeight||c.height||this.symbolHeight)};c.prototype.layoutItem=function(a){var c=this.options,d=this.padding,b="horizontal"===c.layout,e=a.itemHeight,g=this.itemMarginBottom,f=this.itemMarginTop,l=b?n(c.itemDistance,20):0,m=this.maxLegendWidth;c=c.alignColumns&&this.totalItemWidth>m?this.maxItemWidth:
a.itemWidth;b&&this.itemX-d+c>m&&(this.itemX=d,this.lastLineHeight&&(this.itemY+=f+this.lastLineHeight+g),this.lastLineHeight=0);this.lastItemY=f+this.itemY+g;this.lastLineHeight=Math.max(e,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];b?this.itemX+=c:(this.itemY+=f+e+g,this.lastLineHeight=e);this.offsetWidth=this.widthOption||Math.max((b?this.itemX-d-(a.checkbox?0:l):c)+d,this.offsetWidth)};c.prototype.getAllItems=function(){var a=[];this.chart.series.forEach(function(c){var b=c&&
c.options;c&&n(b.showInLegend,d(b.linkedTo)?!1:void 0,!0)&&(a=a.concat(c.legendItems||("point"===b.legendType?c.data:c)))});l(this,"afterGetAllItems",{allItems:a});return a};c.prototype.getAlignment=function(){var a=this.options;return this.proximate?a.align.charAt(0)+"tv":a.floating?"":a.align.charAt(0)+a.verticalAlign.charAt(0)+a.layout.charAt(0)};c.prototype.adjustMargins=function(a,c){var b=this.chart,e=this.options,h=this.getAlignment();h&&[/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/,/(lbv|lm|ltv)/].forEach(function(g,
f){g.test(h)&&!d(a[f])&&(b[x[f]]=Math.max(b[x[f]],b.legend[(f+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][f]*e[f%2?"x":"y"]+n(e.margin,12)+c[f]+(b.titleOffset[f]||0)))})};c.prototype.proximatePositions=function(){var a=this.chart,c=[],d="left"===this.options.align;this.allItems.forEach(function(b){var e;var h=d;if(b.yAxis){b.xAxis.options.reversed&&(h=!h);b.points&&(e=k(h?b.points:b.points.slice(0).reverse(),function(a){return N(a.plotY)}));h=this.itemMarginTop+b.legendItem.getBBox().height+this.itemMarginBottom;
var g=b.yAxis.top-a.plotTop;b.visible?(e=e?e.plotY:b.yAxis.height,e+=g-.3*h):e=g+b.yAxis.height;c.push({target:e,size:h,item:b})}},this);I.distribute(c,a.plotHeight);c.forEach(function(c){c.item._legendItemPos[1]=a.plotTop-a.spacing[0]+c.pos})};c.prototype.render=function(){var a=this.chart,c=a.renderer,d=this.group,b=this.box,e=this.options,g=this.padding;this.itemX=g;this.itemY=this.initialItemY;this.lastItemY=this.offsetWidth=0;this.widthOption=J(e.width,a.spacingBox.width-g);var f=a.spacingBox.width-
2*g-e.x;-1<["rm","lm"].indexOf(this.getAlignment().substring(0,2))&&(f/=2);this.maxLegendWidth=this.widthOption||f;d||(this.group=d=c.g("legend").attr({zIndex:7}).add(),this.contentGroup=c.g().attr({zIndex:1}).add(d),this.scrollGroup=c.g().add(this.contentGroup));this.renderTitle();var m=this.getAllItems();E(m,function(a,c){return(a.options&&a.options.legendIndex||0)-(c.options&&c.options.legendIndex||0)});e.reversed&&m.reverse();this.allItems=m;this.display=f=!!m.length;this.itemHeight=this.totalItemWidth=
this.maxItemWidth=this.lastLineHeight=0;m.forEach(this.renderItem,this);m.forEach(this.layoutItem,this);m=(this.widthOption||this.offsetWidth)+g;var k=this.lastItemY+this.lastLineHeight+this.titleHeight;k=this.handleOverflow(k);k+=g;b||(this.box=b=c.rect().addClass("highcharts-legend-box").attr({r:e.borderRadius}).add(d),b.isNew=!0);a.styledMode||b.attr({stroke:e.borderColor,"stroke-width":e.borderWidth||0,fill:e.backgroundColor||"none"}).shadow(e.shadow);0<m&&0<k&&(b[b.isNew?"attr":"animate"](b.crisp.call({},
{x:0,y:0,width:m,height:k},b.strokeWidth())),b.isNew=!1);b[f?"show":"hide"]();a.styledMode&&"none"===d.getStyle("display")&&(m=k=0);this.legendWidth=m;this.legendHeight=k;f&&this.align();this.proximate||this.positionItems();l(this,"afterRender")};c.prototype.align=function(a){void 0===a&&(a=this.chart.spacingBox);var c=this.chart,d=this.options,b=a.y;/(lth|ct|rth)/.test(this.getAlignment())&&0<c.titleOffset[0]?b+=c.titleOffset[0]:/(lbh|cb|rbh)/.test(this.getAlignment())&&0<c.titleOffset[2]&&(b-=c.titleOffset[2]);
b!==a.y&&(a=u(a,{y:b}));this.group.align(u(d,{width:this.legendWidth,height:this.legendHeight,verticalAlign:this.proximate?"top":d.verticalAlign}),!0,a)};c.prototype.handleOverflow=function(a){var c=this,d=this.chart,b=d.renderer,e=this.options,g=e.y,f=this.padding;g=d.spacingBox.height+("top"===e.verticalAlign?-g:g)-f;var m=e.maxHeight,k,l=this.clipRect,q=e.navigation,t=n(q.animation,!0),p=q.arrowSize||12,u=this.nav,v=this.pages,w,F=this.allItems,S=function(a){"number"===typeof a?l.attr({height:a}):
l&&(c.clipRect=l.destroy(),c.contentGroup.clip());c.contentGroup.div&&(c.contentGroup.div.style.clip=a?"rect("+f+"px,9999px,"+(f+a)+"px,0)":"auto")},K=function(a){c[a]=b.circle(0,0,1.3*p).translate(p/2,p/2).add(u);d.styledMode||c[a].attr("fill","rgba(0,0,0,0.0001)");return c[a]};"horizontal"!==e.layout||"middle"===e.verticalAlign||e.floating||(g/=2);m&&(g=Math.min(g,m));v.length=0;a&&0<g&&a>g&&!1!==q.enabled?(this.clipHeight=k=Math.max(g-20-this.titleHeight-f,0),this.currentPage=n(this.currentPage,
1),this.fullHeight=a,F.forEach(function(a,c){var d=a._legendItemPos[1],b=Math.round(a.legendItem.getBBox().height),e=v.length;if(!e||d-v[e-1]>k&&(w||d)!==v[e-1])v.push(w||d),e++;a.pageIx=e-1;w&&(F[c-1].pageIx=e-1);c===F.length-1&&d+b-v[e-1]>k&&d!==w&&(v.push(d),a.pageIx=e);d!==w&&(w=d)}),l||(l=c.clipRect=b.clipRect(0,f,9999,0),c.contentGroup.clip(l)),S(k),u||(this.nav=u=b.g().attr({zIndex:1}).add(this.group),this.up=b.symbol("triangle",0,0,p,p).add(u),K("upTracker").on("click",function(){c.scroll(-1,
t)}),this.pager=b.text("",15,10).addClass("highcharts-legend-navigation"),d.styledMode||this.pager.css(q.style),this.pager.add(u),this.down=b.symbol("triangle-down",0,0,p,p).add(u),K("downTracker").on("click",function(){c.scroll(1,t)})),c.scroll(0),a=g):u&&(S(),this.nav=u.destroy(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return a};c.prototype.scroll=function(a,c){var d=this,b=this.chart,e=this.pages,h=e.length,g=this.currentPage+a;a=this.clipHeight;var f=this.options.navigation,k=
this.pager,q=this.padding;g>h&&(g=h);0<g&&("undefined"!==typeof c&&C(c,b),this.nav.attr({translateX:q,translateY:a+this.padding+7+this.titleHeight,visibility:"visible"}),[this.up,this.upTracker].forEach(function(a){a.attr({"class":1===g?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"})}),k.attr({text:g+"/"+h}),[this.down,this.downTracker].forEach(function(a){a.attr({x:18+this.pager.getBBox().width,"class":g===h?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"})},this),
b.styledMode||(this.up.attr({fill:1===g?f.inactiveColor:f.activeColor}),this.upTracker.css({cursor:1===g?"default":"pointer"}),this.down.attr({fill:g===h?f.inactiveColor:f.activeColor}),this.downTracker.css({cursor:g===h?"default":"pointer"})),this.scrollOffset=-e[g-1]+this.initialItemY,this.scrollGroup.animate({translateY:this.scrollOffset}),this.currentPage=g,this.positionCheckboxes(),c=D(n(c,b.renderer.globalAnimation,!0)),m(function(){l(d,"afterScroll",{currentPage:g})},c.duration))};c.prototype.setItemEvents=
function(a,c,d){var b=this,e=b.chart.renderer.boxWrapper,h=a instanceof z,g="highcharts-legend-"+(h?"point":"series")+"-active",f=b.chart.styledMode;(d?[c,a.legendSymbol]:[a.legendGroup]).forEach(function(d){if(d)d.on("mouseover",function(){a.visible&&b.allItems.forEach(function(c){a!==c&&c.setState("inactive",!h)});a.setState("hover");a.visible&&e.addClass(g);f||c.css(b.options.itemHoverStyle)}).on("mouseout",function(){b.chart.styledMode||c.css(u(a.visible?b.itemStyle:b.itemHiddenStyle));b.allItems.forEach(function(c){a!==
c&&c.setState("",!h)});e.removeClass(g);a.setState()}).on("click",function(c){var d=function(){a.setVisible&&a.setVisible();b.allItems.forEach(function(c){a!==c&&c.setState(a.visible?"inactive":"",!h)})};e.removeClass(g);c={browserEvent:c};a.firePointEvent?a.firePointEvent("legendItemClick",c,d):l(a,"legendItemClick",c,d)})})};c.prototype.createCheckboxForItem=function(a){a.checkbox=v("input",{type:"checkbox",className:"highcharts-legend-checkbox",checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,
this.chart.container);w(a.checkbox,"click",function(c){l(a.series||a,"checkboxClick",{checked:c.target.checked,item:a},function(){a.select()})})};return c}();(/Trident\/7\.0/.test(b.navigator&&b.navigator.userAgent)||e)&&H(c.prototype,"positionItem",function(c,a){var d=this,b=function(){a._legendItemPos&&c.call(d,a)};b();d.bubbleLegend||setTimeout(b)});I.Legend=c;return I.Legend});O(e,"Core/Series/SeriesRegistry.js",[e["Core/Globals.js"],e["Core/Options.js"],e["Core/Series/Point.js"],e["Core/Utilities.js"]],
function(e,b,I,z){var D=b.defaultOptions,G=z.error,C=z.extendClass,B=z.merge,x;(function(b){function v(e,d){var f=D.plotOptions||{},k=d.defaultOptions;d.prototype.pointClass||(d.prototype.pointClass=I);d.prototype.type=e;k&&(f[e]=k);b.seriesTypes[e]=d}b.seriesTypes=e.seriesTypes;b.getSeries=function(e,d){void 0===d&&(d={});var f=e.options.chart;f=d.type||f.type||f.defaultSeriesType||"";var k=b.seriesTypes[f];b||G(17,!0,e,{missingModuleFor:f});f=new k;"function"===typeof f.init&&f.init(e,d);return f};
b.registerSeriesType=v;b.seriesType=function(e,d,q,k,l){var f=D.plotOptions||{};d=d||"";f[e]=B(f[d],q);v(e,C(b.seriesTypes[d]||function(){},k));b.seriesTypes[e].prototype.type=e;l&&(b.seriesTypes[e].prototype.pointClass=C(I,l));return b.seriesTypes[e]}})(x||(x={}));e.seriesType=x.seriesType;return x});O(e,"Core/Chart/Chart.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Axis/Axis.js"],e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Legend.js"],e["Core/MSPointer.js"],e["Core/Options.js"],
e["Core/Color/Palette.js"],e["Core/Pointer.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Time.js"],e["Core/Utilities.js"],e["Core/Renderer/HTML/AST.js"]],function(e,b,I,z,H,G,C,B,x,w,v,f,d){var q=e.animate,k=e.animObject,l=e.setAnimation,D=I.numberFormat,u=z.charts,n=z.doc,J=z.win,E=C.defaultOptions,m=C.defaultTime,c=w.seriesTypes,g=f.addEvent,a=f.attr,h=f.cleanRecursively,r=f.createElement,A=f.css,y=f.defined,L=f.discardElement,P=f.erase,R=f.error,V=f.extend,Q=f.find,M=f.fireEvent,t=f.getStyle,
p=f.isArray,O=f.isFunction,Z=f.isNumber,ea=f.isObject,F=f.isString,S=f.merge,K=f.objectEach,T=f.pick,X=f.pInt,U=f.relativeLength,fa=f.removeEvent,Y=f.splat,ba=f.syncTimeout,ha=f.uniqueKey,ca=z.marginNames,aa=function(){function e(a,c,d){this.series=this.renderTo=this.renderer=this.pointer=this.pointCount=this.plotWidth=this.plotTop=this.plotLeft=this.plotHeight=this.plotBox=this.options=this.numberFormatter=this.margin=this.legend=this.labelCollectors=this.isResizing=this.index=this.container=this.colorCounter=
this.clipBox=this.chartWidth=this.chartHeight=this.bounds=this.axisOffset=this.axes=void 0;this.sharedClips={};this.yAxis=this.xAxis=this.userOptions=this.titleOffset=this.time=this.symbolCounter=this.spacingBox=this.spacing=void 0;this.getArgs(a,c,d)}e.prototype.getArgs=function(a,c,d){F(a)||a.nodeName?(this.renderTo=a,this.init(c,d)):this.init(a,c)};e.prototype.init=function(a,c){var d=a.plotOptions||{};M(this,"init",{args:arguments},function(){var b=S(E,a),e=b.chart;K(b.plotOptions,function(a,
c){ea(a)&&(a.tooltip=d[c]&&S(d[c].tooltip)||void 0)});b.tooltip.userOptions=a.chart&&a.chart.forExport&&a.tooltip.userOptions||a.tooltip;this.userOptions=a;var h=e.events;this.margin=[];this.spacing=[];this.bounds={h:{},v:{}};this.labelCollectors=[];this.callback=c;this.isResizing=0;this.options=b;this.axes=[];this.series=[];this.time=a.time&&Object.keys(a.time).length?new v(a.time):z.time;this.numberFormatter=e.numberFormatter||D;this.styledMode=e.styledMode;this.hasCartesianSeries=e.showAxes;var f=
this;f.index=u.length;u.push(f);z.chartCount++;h&&K(h,function(a,c){O(a)&&g(f,c,a)});f.xAxis=[];f.yAxis=[];f.pointCount=f.colorCounter=f.symbolCounter=0;M(f,"afterInit");f.firstRender()})};e.prototype.initSeries=function(a){var d=this.options.chart;d=a.type||d.type||d.defaultSeriesType;var b=c[d];b||R(17,!0,this,{missingModuleFor:d});d=new b;"function"===typeof d.init&&d.init(this,a);return d};e.prototype.setSeriesData=function(){this.getSeriesOrderByLinks().forEach(function(a){a.points||a.data||
!a.enabledDataSorting||a.setData(a.options.data,!1)})};e.prototype.getSeriesOrderByLinks=function(){return this.series.concat().sort(function(a,c){return a.linkedSeries.length||c.linkedSeries.length?c.linkedSeries.length-a.linkedSeries.length:0})};e.prototype.orderSeries=function(a){var c=this.series;for(a=a||0;a<c.length;a++)c[a]&&(c[a].index=a,c[a].name=c[a].getName())};e.prototype.isInsidePlot=function(a,c,d){void 0===d&&(d={});var b=this.inverted,e=this.plotBox,h=this.plotLeft,g=this.plotTop,
f=this.scrollablePlotBox,m=this.scrollingContainer;m=void 0===m?{scrollLeft:0,scrollTop:0}:m;var k=m.scrollLeft;m=m.scrollTop;var l=d.series;e=d.visiblePlotOnly&&f||e;f=d.inverted?c:a;c=d.inverted?a:c;a={x:f,y:c,isInsidePlot:!0};if(!d.ignoreX){var F=l&&(b?l.yAxis:l.xAxis)||{pos:h,len:Infinity};f=d.paneCoordinates?F.pos+f:h+f;f>=Math.max(k+h,F.pos)&&f<=Math.min(k+h+e.width,F.pos+F.len)||(a.isInsidePlot=!1)}!d.ignoreY&&a.isInsidePlot&&(b=l&&(b?l.xAxis:l.yAxis)||{pos:g,len:Infinity},d=d.paneCoordinates?
b.pos+c:g+c,d>=Math.max(m+g,b.pos)&&d<=Math.min(m+g+e.height,b.pos+b.len)||(a.isInsidePlot=!1));M(this,"afterIsInsidePlot",a);return a.isInsidePlot};e.prototype.redraw=function(a){M(this,"beforeRedraw");var c=this.hasCartesianSeries?this.axes:this.colorAxis||[],d=this.series,b=this.pointer,e=this.legend,h=this.userOptions.legend,g=this.isDirtyLegend,f=this.isDirtyBox,m=this.renderer,k=m.isHidden(),F=[];this.setResponsive&&this.setResponsive(!1);l(this.hasRendered?a:!1,this);k&&this.temporaryDisplay();
this.layOutTitles();for(a=d.length;a--;){var n=d[a];if(n.options.stacking||n.options.centerInCategory){var r=!0;if(n.isDirty){var K=!0;break}}}if(K)for(a=d.length;a--;)n=d[a],n.options.stacking&&(n.isDirty=!0);d.forEach(function(a){a.isDirty&&("point"===a.options.legendType?("function"===typeof a.updateTotals&&a.updateTotals(),g=!0):h&&(h.labelFormatter||h.labelFormat)&&(g=!0));a.isDirtyData&&M(a,"updatedData")});g&&e&&e.options.enabled&&(e.render(),this.isDirtyLegend=!1);r&&this.getStacks();c.forEach(function(a){a.updateNames();
a.setScale()});this.getMargins();c.forEach(function(a){a.isDirty&&(f=!0)});c.forEach(function(a){var c=a.min+","+a.max;a.extKey!==c&&(a.extKey=c,F.push(function(){M(a,"afterSetExtremes",V(a.eventArgs,a.getExtremes()));delete a.eventArgs}));(f||r)&&a.redraw()});f&&this.drawChartBox();M(this,"predraw");d.forEach(function(a){(f||a.isDirty)&&a.visible&&a.redraw();a.isDirtyData=!1});b&&b.reset(!0);m.draw();M(this,"redraw");M(this,"render");k&&this.temporaryDisplay(!0);F.forEach(function(a){a.call()})};
e.prototype.get=function(a){function c(c){return c.id===a||c.options&&c.options.id===a}var d=this.series,b;var e=Q(this.axes,c)||Q(this.series,c);for(b=0;!e&&b<d.length;b++)e=Q(d[b].points||[],c);return e};e.prototype.getAxes=function(){var a=this,c=this.options,d=c.xAxis=Y(c.xAxis||{});c=c.yAxis=Y(c.yAxis||{});M(this,"getAxes");d.forEach(function(a,c){a.index=c;a.isX=!0});c.forEach(function(a,c){a.index=c});d.concat(c).forEach(function(c){new b(a,c)});M(this,"afterGetAxes")};e.prototype.getSelectedPoints=
function(){var a=[];this.series.forEach(function(c){a=a.concat(c.getPointsCollection().filter(function(a){return T(a.selectedStaging,a.selected)}))});return a};e.prototype.getSelectedSeries=function(){return this.series.filter(function(a){return a.selected})};e.prototype.setTitle=function(a,c,d){this.applyDescription("title",a);this.applyDescription("subtitle",c);this.applyDescription("caption",void 0);this.layOutTitles(d)};e.prototype.applyDescription=function(a,c){var d=this,b="title"===a?{color:B.neutralColor80,
fontSize:this.options.isStock?"16px":"18px"}:{color:B.neutralColor60};b=this.options[a]=S(!this.styledMode&&{style:b},this.options[a],c);var e=this[a];e&&c&&(this[a]=e=e.destroy());b&&!e&&(e=this.renderer.text(b.text,0,0,b.useHTML).attr({align:b.align,"class":"highcharts-"+a,zIndex:b.zIndex||4}).add(),e.update=function(c){d[{title:"setTitle",subtitle:"setSubtitle",caption:"setCaption"}[a]](c)},this.styledMode||e.css(b.style),this[a]=e)};e.prototype.layOutTitles=function(a){var c=[0,0,0],d=this.renderer,
b=this.spacingBox;["title","subtitle","caption"].forEach(function(a){var e=this[a],h=this.options[a],g=h.verticalAlign||"top";a="title"===a?-3:"top"===g?c[0]+2:0;if(e){if(!this.styledMode)var f=h.style.fontSize;f=d.fontMetrics(f,e).b;e.css({width:(h.width||b.width+(h.widthAdjust||0))+"px"});var m=Math.round(e.getBBox(h.useHTML).height);e.align(V({y:"bottom"===g?f:a+f,height:m},h),!1,"spacingBox");h.floating||("top"===g?c[0]=Math.ceil(c[0]+m):"bottom"===g&&(c[2]=Math.ceil(c[2]+m)))}},this);c[0]&&"top"===
(this.options.title.verticalAlign||"top")&&(c[0]+=this.options.title.margin);c[2]&&"bottom"===this.options.caption.verticalAlign&&(c[2]+=this.options.caption.margin);var e=!this.titleOffset||this.titleOffset.join(",")!==c.join(",");this.titleOffset=c;M(this,"afterLayOutTitles");!this.isDirtyBox&&e&&(this.isDirtyBox=this.isDirtyLegend=e,this.hasRendered&&T(a,!0)&&this.isDirtyBox&&this.redraw())};e.prototype.getChartSize=function(){var a=this.options.chart,c=a.width;a=a.height;var d=this.renderTo;y(c)||
(this.containerWidth=t(d,"width"));y(a)||(this.containerHeight=t(d,"height"));this.chartWidth=Math.max(0,c||this.containerWidth||600);this.chartHeight=Math.max(0,U(a,this.chartWidth)||(1<this.containerHeight?this.containerHeight:400))};e.prototype.temporaryDisplay=function(a){var c=this.renderTo;if(a)for(;c&&c.style;)c.hcOrigStyle&&(A(c,c.hcOrigStyle),delete c.hcOrigStyle),c.hcOrigDetached&&(n.body.removeChild(c),c.hcOrigDetached=!1),c=c.parentNode;else for(;c&&c.style;){n.body.contains(c)||c.parentNode||
(c.hcOrigDetached=!0,n.body.appendChild(c));if("none"===t(c,"display",!1)||c.hcOricDetached)c.hcOrigStyle={display:c.style.display,height:c.style.height,overflow:c.style.overflow},a={display:"block",overflow:"hidden"},c!==this.renderTo&&(a.height=0),A(c,a),c.offsetWidth||c.style.setProperty("display","block","important");c=c.parentNode;if(c===n.body)break}};e.prototype.setClassName=function(a){this.container.className="highcharts-container "+(a||"")};e.prototype.getContainer=function(){var c=this.options,
d=c.chart;var b=this.renderTo;var e=ha(),h,g;b||(this.renderTo=b=d.renderTo);F(b)&&(this.renderTo=b=n.getElementById(b));b||R(13,!0,this);var f=X(a(b,"data-highcharts-chart"));Z(f)&&u[f]&&u[f].hasRendered&&u[f].destroy();a(b,"data-highcharts-chart",this.index);b.innerHTML="";d.skipClone||b.offsetWidth||this.temporaryDisplay();this.getChartSize();f=this.chartWidth;var m=this.chartHeight;A(b,{overflow:"hidden"});this.styledMode||(h=V({position:"relative",overflow:"hidden",width:f+"px",height:m+"px",
textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)",userSelect:"none","touch-action":"manipulation",outline:"none"},d.style||{}));this.container=b=r("div",{id:e},h,b);this._cursor=b.style.cursor;this.renderer=new (z[d.renderer]||z.Renderer)(b,f,m,null,d.forExport,c.exporting&&c.exporting.allowHTML,this.styledMode);l(void 0,this);this.setClassName(d.className);if(this.styledMode)for(g in c.defs)this.renderer.definition(c.defs[g]);else this.renderer.setStyle(d.style);
this.renderer.chartIndex=this.index;M(this,"afterGetContainer")};e.prototype.getMargins=function(a){var c=this.spacing,d=this.margin,b=this.titleOffset;this.resetMargins();b[0]&&!y(d[0])&&(this.plotTop=Math.max(this.plotTop,b[0]+c[0]));b[2]&&!y(d[2])&&(this.marginBottom=Math.max(this.marginBottom,b[2]+c[2]));this.legend&&this.legend.display&&this.legend.adjustMargins(d,c);M(this,"getMargins");a||this.getAxisMargins()};e.prototype.getAxisMargins=function(){var a=this,c=a.axisOffset=[0,0,0,0],d=a.colorAxis,
b=a.margin,e=function(a){a.forEach(function(a){a.visible&&a.getOffset()})};a.hasCartesianSeries?e(a.axes):d&&d.length&&e(d);ca.forEach(function(d,e){y(b[e])||(a[d]+=c[e])});a.setChartSize()};e.prototype.reflow=function(a){var c=this,d=c.options.chart,b=c.renderTo,e=y(d.width)&&y(d.height),h=d.width||t(b,"width");d=d.height||t(b,"height");b=a?a.target:J;delete c.pointer.chartPosition;if(!e&&!c.isPrinting&&h&&d&&(b===J||b===n)){if(h!==c.containerWidth||d!==c.containerHeight)f.clearTimeout(c.reflowTimeout),
c.reflowTimeout=ba(function(){c.container&&c.setSize(void 0,void 0,!1)},a?100:0);c.containerWidth=h;c.containerHeight=d}};e.prototype.setReflow=function(a){var c=this;!1===a||this.unbindReflow?!1===a&&this.unbindReflow&&(this.unbindReflow=this.unbindReflow()):(this.unbindReflow=g(J,"resize",function(a){c.options&&c.reflow(a)}),g(this,"destroy",this.unbindReflow))};e.prototype.setSize=function(a,c,d){var b=this,e=b.renderer;b.isResizing+=1;l(d,b);d=e.globalAnimation;b.oldChartHeight=b.chartHeight;
b.oldChartWidth=b.chartWidth;"undefined"!==typeof a&&(b.options.chart.width=a);"undefined"!==typeof c&&(b.options.chart.height=c);b.getChartSize();b.styledMode||(d?q:A)(b.container,{width:b.chartWidth+"px",height:b.chartHeight+"px"},d);b.setChartSize(!0);e.setSize(b.chartWidth,b.chartHeight,d);b.axes.forEach(function(a){a.isDirty=!0;a.setScale()});b.isDirtyLegend=!0;b.isDirtyBox=!0;b.layOutTitles();b.getMargins();b.redraw(d);b.oldChartHeight=null;M(b,"resize");ba(function(){b&&M(b,"endResize",null,
function(){--b.isResizing})},k(d).duration)};e.prototype.setChartSize=function(a){var c=this.inverted,d=this.renderer,b=this.chartWidth,e=this.chartHeight,h=this.options.chart,g=this.spacing,f=this.clipOffset,m,l,k,F;this.plotLeft=m=Math.round(this.plotLeft);this.plotTop=l=Math.round(this.plotTop);this.plotWidth=k=Math.max(0,Math.round(b-m-this.marginRight));this.plotHeight=F=Math.max(0,Math.round(e-l-this.marginBottom));this.plotSizeX=c?F:k;this.plotSizeY=c?k:F;this.plotBorderWidth=h.plotBorderWidth||
0;this.spacingBox=d.spacingBox={x:g[3],y:g[0],width:b-g[3]-g[1],height:e-g[0]-g[2]};this.plotBox=d.plotBox={x:m,y:l,width:k,height:F};e=2*Math.floor(this.plotBorderWidth/2);c=Math.ceil(Math.max(e,f[3])/2);b=Math.ceil(Math.max(e,f[0])/2);this.clipBox={x:c,y:b,width:Math.floor(this.plotSizeX-Math.max(e,f[1])/2-c),height:Math.max(0,Math.floor(this.plotSizeY-Math.max(e,f[2])/2-b))};a||(this.axes.forEach(function(a){a.setAxisSize();a.setAxisTranslation()}),d.alignElements());M(this,"afterSetChartSize",
{skipAxes:a})};e.prototype.resetMargins=function(){M(this,"resetMargins");var a=this,c=a.options.chart;["margin","spacing"].forEach(function(d){var b=c[d],e=ea(b)?b:[b,b,b,b];["Top","Right","Bottom","Left"].forEach(function(b,h){a[d][h]=T(c[d+b],e[h])})});ca.forEach(function(c,d){a[c]=T(a.margin[d],a.spacing[d])});a.axisOffset=[0,0,0,0];a.clipOffset=[0,0,0,0]};e.prototype.drawChartBox=function(){var a=this.options.chart,c=this.renderer,d=this.chartWidth,b=this.chartHeight,e=this.chartBackground,h=
this.plotBackground,g=this.plotBorder,f=this.styledMode,m=this.plotBGImage,k=a.backgroundColor,l=a.plotBackgroundColor,F=a.plotBackgroundImage,n,r=this.plotLeft,K=this.plotTop,q=this.plotWidth,p=this.plotHeight,u=this.plotBox,v=this.clipRect,t=this.clipBox,w="animate";e||(this.chartBackground=e=c.rect().addClass("highcharts-background").add(),w="attr");if(f)var y=n=e.strokeWidth();else{y=a.borderWidth||0;n=y+(a.shadow?8:0);k={fill:k||"none"};if(y||e["stroke-width"])k.stroke=a.borderColor,k["stroke-width"]=
y;e.attr(k).shadow(a.shadow)}e[w]({x:n/2,y:n/2,width:d-n-y%2,height:b-n-y%2,r:a.borderRadius});w="animate";h||(w="attr",this.plotBackground=h=c.rect().addClass("highcharts-plot-background").add());h[w](u);f||(h.attr({fill:l||"none"}).shadow(a.plotShadow),F&&(m?(F!==m.attr("href")&&m.attr("href",F),m.animate(u)):this.plotBGImage=c.image(F,r,K,q,p).add()));v?v.animate({width:t.width,height:t.height}):this.clipRect=c.clipRect(t);w="animate";g||(w="attr",this.plotBorder=g=c.rect().addClass("highcharts-plot-border").attr({zIndex:1}).add());
f||g.attr({stroke:a.plotBorderColor,"stroke-width":a.plotBorderWidth||0,fill:"none"});g[w](g.crisp({x:r,y:K,width:q,height:p},-g.strokeWidth()));this.isDirtyBox=!1;M(this,"afterDrawChartBox")};e.prototype.propFromSeries=function(){var a=this,d=a.options.chart,b,e=a.options.series,h,g;["inverted","angular","polar"].forEach(function(f){b=c[d.type||d.defaultSeriesType];g=d[f]||b&&b.prototype[f];for(h=e&&e.length;!g&&h--;)(b=c[e[h].type])&&b.prototype[f]&&(g=!0);a[f]=g})};e.prototype.linkSeries=function(){var a=
this,c=a.series;c.forEach(function(a){a.linkedSeries.length=0});c.forEach(function(c){var d=c.options.linkedTo;F(d)&&(d=":previous"===d?a.series[c.index-1]:a.get(d))&&d.linkedParent!==c&&(d.linkedSeries.push(c),c.linkedParent=d,d.enabledDataSorting&&c.setDataSortingOptions(),c.visible=T(c.options.visible,d.options.visible,c.visible))});M(this,"afterLinkSeries")};e.prototype.renderSeries=function(){this.series.forEach(function(a){a.translate();a.render()})};e.prototype.renderLabels=function(){var a=
this,c=a.options.labels;c.items&&c.items.forEach(function(d){var b=V(c.style,d.style),e=X(b.left)+a.plotLeft,h=X(b.top)+a.plotTop+12;delete b.left;delete b.top;a.renderer.text(d.html,e,h).attr({zIndex:2}).css(b).add()})};e.prototype.render=function(){var a=this.axes,c=this.colorAxis,d=this.renderer,b=this.options,e=0,h=function(a){a.forEach(function(a){a.visible&&a.render()})};this.setTitle();this.legend=new H(this,b.legend);this.getStacks&&this.getStacks();this.getMargins(!0);this.setChartSize();
b=this.plotWidth;a.some(function(a){if(a.horiz&&a.visible&&a.options.labels.enabled&&a.series.length)return e=21,!0});var g=this.plotHeight=Math.max(this.plotHeight-e,0);a.forEach(function(a){a.setScale()});this.getAxisMargins();var f=1.1<b/this.plotWidth;var m=1.05<g/this.plotHeight;if(f||m)a.forEach(function(a){(a.horiz&&f||!a.horiz&&m)&&a.setTickInterval(!0)}),this.getMargins();this.drawChartBox();this.hasCartesianSeries?h(a):c&&c.length&&h(c);this.seriesGroup||(this.seriesGroup=d.g("series-group").attr({zIndex:3}).add());
this.renderSeries();this.renderLabels();this.addCredits();this.setResponsive&&this.setResponsive();this.hasRendered=!0};e.prototype.addCredits=function(a){var c=this,d=S(!0,this.options.credits,a);d.enabled&&!this.credits&&(this.credits=this.renderer.text(d.text+(this.mapCredits||""),0,0).addClass("highcharts-credits").on("click",function(){d.href&&(J.location.href=d.href)}).attr({align:d.position.align,zIndex:8}),c.styledMode||this.credits.css(d.style),this.credits.add().align(d.position),this.credits.update=
function(a){c.credits=c.credits.destroy();c.addCredits(a)})};e.prototype.destroy=function(){var a=this,c=a.axes,d=a.series,b=a.container,e,h=b&&b.parentNode;M(a,"destroy");a.renderer.forExport?P(u,a):u[a.index]=void 0;z.chartCount--;a.renderTo.removeAttribute("data-highcharts-chart");fa(a);for(e=c.length;e--;)c[e]=c[e].destroy();this.scroller&&this.scroller.destroy&&this.scroller.destroy();for(e=d.length;e--;)d[e]=d[e].destroy();"title subtitle chartBackground plotBackground plotBGImage plotBorder seriesGroup clipRect credits pointer rangeSelector legend resetZoomButton tooltip renderer".split(" ").forEach(function(c){var d=
a[c];d&&d.destroy&&(a[c]=d.destroy())});b&&(b.innerHTML="",fa(b),h&&L(b));K(a,function(c,d){delete a[d]})};e.prototype.firstRender=function(){var a=this,c=a.options;if(!a.isReadyToRender||a.isReadyToRender()){a.getContainer();a.resetMargins();a.setChartSize();a.propFromSeries();a.getAxes();(p(c.series)?c.series:[]).forEach(function(c){a.initSeries(c)});a.linkSeries();a.setSeriesData();M(a,"beforeRender");x&&(a.pointer=z.hasTouch||!J.PointerEvent&&!J.MSPointerEvent?new x(a,c):new G(a,c));a.render();
a.pointer.getChartPosition();if(!a.renderer.imgCount&&!a.hasLoaded)a.onload();a.temporaryDisplay(!0)}};e.prototype.onload=function(){this.callbacks.concat([this.callback]).forEach(function(a){a&&"undefined"!==typeof this.index&&a.apply(this,[this])},this);M(this,"load");M(this,"render");y(this.index)&&this.setReflow(this.options.chart.reflow);this.hasLoaded=!0};e.prototype.addSeries=function(a,c,d){var b,e=this;a&&(c=T(c,!0),M(e,"addSeries",{options:a},function(){b=e.initSeries(a);e.isDirtyLegend=
!0;e.linkSeries();b.enabledDataSorting&&b.setData(a.data,!1);M(e,"afterAddSeries",{series:b});c&&e.redraw(d)}));return b};e.prototype.addAxis=function(a,c,d,b){return this.createAxis(c?"xAxis":"yAxis",{axis:a,redraw:d,animation:b})};e.prototype.addColorAxis=function(a,c,d){return this.createAxis("colorAxis",{axis:a,redraw:c,animation:d})};e.prototype.createAxis=function(a,c){var d="colorAxis"===a,e=c.redraw,h=c.animation;a=S(c.axis,{index:this[a].length,isX:"xAxis"===a});a=d?new z.ColorAxis(this,
a):new b(this,a);d&&(this.isDirtyLegend=!0,this.axes.forEach(function(a){a.series=[]}),this.series.forEach(function(a){a.bindAxes();a.isDirtyData=!0}));T(e,!0)&&this.redraw(h);return a};e.prototype.showLoading=function(a){var c=this,b=c.options,e=c.loadingDiv,h=c.loadingSpan,f=b.loading,m=function(){e&&A(e,{left:c.plotLeft+"px",top:c.plotTop+"px",width:c.plotWidth+"px",height:c.plotHeight+"px"})};e||(c.loadingDiv=e=r("div",{className:"highcharts-loading highcharts-loading-hidden"},null,c.container));
h||(c.loadingSpan=h=r("span",{className:"highcharts-loading-inner"},null,e),g(c,"redraw",m));e.className="highcharts-loading";d.setElementHTML(h,T(a,b.lang.loading,""));c.styledMode||(A(e,V(f.style,{zIndex:10})),A(h,f.labelStyle),c.loadingShown||(A(e,{opacity:0,display:""}),q(e,{opacity:f.style.opacity||.5},{duration:f.showDuration||0})));c.loadingShown=!0;m()};e.prototype.hideLoading=function(){var a=this.options,c=this.loadingDiv;c&&(c.className="highcharts-loading highcharts-loading-hidden",this.styledMode||
q(c,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){A(c,{display:"none"})}}));this.loadingShown=!1};e.prototype.update=function(a,c,d,b){var e=this,g={credits:"addCredits",title:"setTitle",subtitle:"setSubtitle",caption:"setCaption"},f,k,l,n=a.isResponsiveOptions,r=[];M(e,"update",{options:a});n||e.setResponsive(!1,!0);a=h(a,e.options);e.userOptions=S(e.userOptions,a);if(f=a.chart){S(!0,e.options.chart,f);"className"in f&&e.setClassName(f.className);"reflow"in f&&e.setReflow(f.reflow);
if("inverted"in f||"polar"in f||"type"in f){e.propFromSeries();var q=!0}"alignTicks"in f&&(q=!0);K(f,function(a,c){-1!==e.propsRequireUpdateSeries.indexOf("chart."+c)&&(k=!0);-1!==e.propsRequireDirtyBox.indexOf(c)&&(e.isDirtyBox=!0);-1!==e.propsRequireReflow.indexOf(c)&&(n?e.isDirtyBox=!0:l=!0)});!e.styledMode&&"style"in f&&e.renderer.setStyle(f.style)}!e.styledMode&&a.colors&&(this.options.colors=a.colors);a.time&&(this.time===m&&(this.time=new v(a.time)),S(!0,e.options.time,a.time));K(a,function(c,
d){if(e[d]&&"function"===typeof e[d].update)e[d].update(c,!1);else if("function"===typeof e[g[d]])e[g[d]](c);else"colors"!==d&&-1===e.collectionsWithUpdate.indexOf(d)&&S(!0,e.options[d],a[d]);"chart"!==d&&-1!==e.propsRequireUpdateSeries.indexOf(d)&&(k=!0)});this.collectionsWithUpdate.forEach(function(c){if(a[c]){var b=[];e[c].forEach(function(a,c){a.options.isInternal||b.push(T(a.options.index,c))});Y(a[c]).forEach(function(a,h){var g=y(a.id),f;g&&(f=e.get(a.id));!f&&e[c]&&(f=e[c][b?b[h]:h])&&g&&
y(f.options.id)&&(f=void 0);f&&f.coll===c&&(f.update(a,!1),d&&(f.touched=!0));!f&&d&&e.collectionsWithInit[c]&&(e.collectionsWithInit[c][0].apply(e,[a].concat(e.collectionsWithInit[c][1]||[]).concat([!1])).touched=!0)});d&&e[c].forEach(function(a){a.touched||a.options.isInternal?delete a.touched:r.push(a)})}});r.forEach(function(a){a.chart&&a.remove(!1)});q&&e.axes.forEach(function(a){a.update({},!1)});k&&e.getSeriesOrderByLinks().forEach(function(a){a.chart&&a.update({},!1)},this);q=f&&f.width;f=
f&&f.height;F(f)&&(f=U(f,q||e.chartWidth));l||Z(q)&&q!==e.chartWidth||Z(f)&&f!==e.chartHeight?e.setSize(q,f,b):T(c,!0)&&e.redraw(b);M(e,"afterUpdate",{options:a,redraw:c,animation:b})};e.prototype.setSubtitle=function(a,c){this.applyDescription("subtitle",a);this.layOutTitles(c)};e.prototype.setCaption=function(a,c){this.applyDescription("caption",a);this.layOutTitles(c)};e.prototype.showResetZoom=function(){function a(){c.zoomOut()}var c=this,d=E.lang,b=c.options.chart.resetZoomButton,e=b.theme,
h=e.states,g="chart"===b.relativeTo||"spacingBox"===b.relativeTo?null:"scrollablePlotBox";M(this,"beforeShowResetZoom",null,function(){c.resetZoomButton=c.renderer.button(d.resetZoom,null,null,a,e,h&&h.hover).attr({align:b.position.align,title:d.resetZoomTitle}).addClass("highcharts-reset-zoom").add().align(b.position,!1,g)});M(this,"afterShowResetZoom")};e.prototype.zoomOut=function(){M(this,"selection",{resetSelection:!0},this.zoom)};e.prototype.zoom=function(a){var c=this,d,b=c.pointer,e=!1,h=
c.inverted?b.mouseDownX:b.mouseDownY;!a||a.resetSelection?(c.axes.forEach(function(a){d=a.zoom()}),b.initiated=!1):a.xAxis.concat(a.yAxis).forEach(function(a){var g=a.axis,f=c.inverted?g.left:g.top,m=c.inverted?f+g.width:f+g.height,k=g.isXAxis,l=!1;if(!k&&h>=f&&h<=m||k||!y(h))l=!0;b[k?"zoomX":"zoomY"]&&l&&(d=g.zoom(a.min,a.max),g.displayBtn&&(e=!0))});var g=c.resetZoomButton;e&&!g?c.showResetZoom():!e&&ea(g)&&(c.resetZoomButton=g.destroy());d&&c.redraw(T(c.options.chart.animation,a&&a.animation,100>
c.pointCount))};e.prototype.pan=function(a,c){var d=this,b=d.hoverPoints,e=d.options.chart,h=d.options.mapNavigation&&d.options.mapNavigation.enabled,g;c="object"===typeof c?c:{enabled:c,type:"x"};e&&e.panning&&(e.panning=c);var f=c.type;M(this,"pan",{originalEvent:a},function(){b&&b.forEach(function(a){a.setState()});var c=[1];"xy"===f?c=[1,0]:"y"===f&&(c=[0]);c.forEach(function(c){var b=d[c?"xAxis":"yAxis"][0],e=b.horiz,m=a[e?"chartX":"chartY"];e=e?"mouseDownX":"mouseDownY";var k=d[e],l=(b.pointRange||
0)/2,F=b.reversed&&!d.inverted||!b.reversed&&d.inverted?-1:1,n=b.getExtremes(),r=b.toValue(k-m,!0)+l*F;F=b.toValue(k+b.len-m,!0)-l*F;var K=F<r;k=K?F:r;r=K?r:F;F=b.hasVerticalPanning();var q=b.panningState;!F||c||q&&!q.isDirty||b.series.forEach(function(a){var c=a.getProcessedData(!0);c=a.getExtremes(c.yData,!0);q||(q={startMin:Number.MAX_VALUE,startMax:-Number.MAX_VALUE});Z(c.dataMin)&&Z(c.dataMax)&&(q.startMin=Math.min(T(a.options.threshold,Infinity),c.dataMin,q.startMin),q.startMax=Math.max(T(a.options.threshold,
-Infinity),c.dataMax,q.startMax))});c=Math.min(T(q&&q.startMin,n.dataMin),l?n.min:b.toValue(b.toPixels(n.min)-b.minPixelPadding));l=Math.max(T(q&&q.startMax,n.dataMax),l?n.max:b.toValue(b.toPixels(n.max)+b.minPixelPadding));b.panningState=q;b.isOrdinal||(F=c-k,0<F&&(r+=F,k=c),F=r-l,0<F&&(r=l,k-=F),b.series.length&&k!==n.min&&r!==n.max&&k>=c&&r<=l&&(b.setExtremes(k,r,!1,!1,{trigger:"pan"}),d.resetZoomButton||h||k===c||r===l||!f.match("y")||(d.showResetZoom(),b.displayBtn=!1),g=!0),d[e]=m)});g&&d.redraw(!1);
A(d.container,{cursor:"move"})})};return e}();V(aa.prototype,{callbacks:[],collectionsWithInit:{xAxis:[aa.prototype.addAxis,[!0]],yAxis:[aa.prototype.addAxis,[!1]],series:[aa.prototype.addSeries]},collectionsWithUpdate:["xAxis","yAxis","zAxis","series"],propsRequireDirtyBox:"backgroundColor borderColor borderWidth borderRadius plotBackgroundColor plotBackgroundImage plotBorderColor plotBorderWidth plotShadow shadow".split(" "),propsRequireReflow:"margin marginTop marginRight marginBottom marginLeft spacing spacingTop spacingRight spacingBottom spacingLeft".split(" "),
propsRequireUpdateSeries:"chart.inverted chart.polar chart.ignoreHiddenSeries chart.type colors plotOptions time tooltip".split(" ")});z.chart=function(a,c,d){return new aa(a,c,d)};z.Chart=aa;"";return aa});O(e,"Mixins/LegendSymbol.js",[e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b){var D=b.merge,z=b.pick;return e.LegendSymbolMixin={drawRectangle:function(b,e){var D=b.symbolHeight,B=b.options.squareSymbol;e.legendSymbol=this.chart.renderer.rect(B?(b.symbolWidth-D)/2:0,b.baseline-D+1,B?
D:b.symbolWidth,D,z(b.options.symbolRadius,D/2)).addClass("highcharts-point").attr({zIndex:3}).add(e.legendGroup)},drawLineMarker:function(b){var e=this.options,C=e.marker,B=b.symbolWidth,x=b.symbolHeight,w=x/2,v=this.chart.renderer,f=this.legendGroup;b=b.baseline-Math.round(.3*b.fontMetrics.b);var d={};this.chart.styledMode||(d={"stroke-width":e.lineWidth||0},e.dashStyle&&(d.dashstyle=e.dashStyle));this.legendLine=v.path([["M",0,b],["L",B,b]]).addClass("highcharts-graph").attr(d).add(f);C&&!1!==
C.enabled&&B&&(e=Math.min(z(C.radius,w),w),0===this.symbol.indexOf("url")&&(C=D(C,{width:x,height:x}),e=0),this.legendSymbol=C=v.symbol(this.symbol,B/2-e,b-e,2*e,2*e,C).addClass("highcharts-point").add(f),C.isMarker=!0)}}});O(e,"Core/Series/Series.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Globals.js"],e["Mixins/LegendSymbol.js"],e["Core/Options.js"],e["Core/Color/Palette.js"],e["Core/Series/Point.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Renderer/SVG/SVGElement.js"],e["Core/Utilities.js"]],
function(e,b,I,z,H,G,C,B,x){var w=e.animObject,v=e.setAnimation,f=b.hasTouch,d=b.svg,q=b.win,k=z.defaultOptions,l=C.seriesTypes,D=x.addEvent,u=x.arrayMax,n=x.arrayMin,J=x.clamp,E=x.cleanRecursively,m=x.correctFloat,c=x.defined,g=x.erase,a=x.error,h=x.extend,r=x.find,A=x.fireEvent,y=x.getNestedProperty,L=x.isArray,P=x.isFunction,R=x.isNumber,V=x.isString,Q=x.merge,M=x.objectEach,t=x.pick,p=x.removeEvent,O=x.splat,Z=x.syncTimeout;e=function(){function b(){this.zones=this.yAxis=this.xAxis=this.userOptions=
this.tooltipOptions=this.processedYData=this.processedXData=this.points=this.options=this.linkedSeries=this.index=this.eventsToUnbind=this.eventOptions=this.data=this.chart=this._i=void 0}b.prototype.init=function(a,c){A(this,"init",{options:c});var d=this,b=a.series,e;this.eventOptions=this.eventOptions||{};this.eventsToUnbind=[];d.chart=a;d.options=d.setOptions(c);var g=d.options;d.linkedSeries=[];d.bindAxes();h(d,{name:g.name,state:"",visible:!1!==g.visible,selected:!0===g.selected});c=g.events;
M(c,function(a,c){P(a)&&d.eventOptions[c]!==a&&(P(d.eventOptions[c])&&p(d,c,d.eventOptions[c]),d.eventOptions[c]=a,D(d,c,a))});if(c&&c.click||g.point&&g.point.events&&g.point.events.click||g.allowPointSelect)a.runTrackerClick=!0;d.getColor();d.getSymbol();d.parallelArrays.forEach(function(a){d[a+"Data"]||(d[a+"Data"]=[])});d.isCartesian&&(a.hasCartesianSeries=!0);b.length&&(e=b[b.length-1]);d._i=t(e&&e._i,-1)+1;d.opacity=d.options.opacity;a.orderSeries(this.insert(b));g.dataSorting&&g.dataSorting.enabled?
d.setDataSortingOptions():d.points||d.data||d.setData(g.data,!1);A(this,"afterInit")};b.prototype.is=function(a){return l[a]&&this instanceof l[a]};b.prototype.insert=function(a){var c=this.options.index,d;if(R(c)){for(d=a.length;d--;)if(c>=t(a[d].options.index,a[d]._i)){a.splice(d+1,0,this);break}-1===d&&a.unshift(this);d+=1}else a.push(this);return t(d,a.length-1)};b.prototype.bindAxes=function(){var c=this,d=c.options,b=c.chart,e;A(this,"bindAxes",null,function(){(c.axisTypes||[]).forEach(function(h){var g=
0;b[h].forEach(function(a){e=a.options;if(d[h]===g&&!e.isInternal||"undefined"!==typeof d[h]&&d[h]===e.id||"undefined"===typeof d[h]&&0===e.index)c.insert(a.series),c[h]=a,a.isDirty=!0;e.isInternal||g++});c[h]||c.optionalAxis===h||a(18,!0,b)})});A(this,"afterBindAxes")};b.prototype.updateParallelArrays=function(a,c){var d=a.series,b=arguments,e=R(c)?function(b){var e="y"===b&&d.toYData?d.toYData(a):a[b];d[b+"Data"][c]=e}:function(a){Array.prototype[c].apply(d[a+"Data"],Array.prototype.slice.call(b,
2))};d.parallelArrays.forEach(e)};b.prototype.hasData=function(){return this.visible&&"undefined"!==typeof this.dataMax&&"undefined"!==typeof this.dataMin||this.visible&&this.yData&&0<this.yData.length};b.prototype.autoIncrement=function(){var a=this.options,c=this.xIncrement,d,b=a.pointIntervalUnit,e=this.chart.time;c=t(c,a.pointStart,0);this.pointInterval=d=t(this.pointInterval,a.pointInterval,1);b&&(a=new e.Date(c),"day"===b?e.set("Date",a,e.get("Date",a)+d):"month"===b?e.set("Month",a,e.get("Month",
a)+d):"year"===b&&e.set("FullYear",a,e.get("FullYear",a)+d),d=a.getTime()-c);this.xIncrement=c+d;return c};b.prototype.setDataSortingOptions=function(){var a=this.options;h(this,{requireSorting:!1,sorted:!1,enabledDataSorting:!0,allowDG:!1});c(a.pointRange)||(a.pointRange=1)};b.prototype.setOptions=function(a){var d=this.chart,b=d.options,e=b.plotOptions,h=d.userOptions||{};a=Q(a);d=d.styledMode;var g={plotOptions:e,userOptions:a};A(this,"setOptions",g);var f=g.plotOptions[this.type],m=h.plotOptions||
{};this.userOptions=g.userOptions;h=Q(f,e.series,h.plotOptions&&h.plotOptions[this.type],a);this.tooltipOptions=Q(k.tooltip,k.plotOptions.series&&k.plotOptions.series.tooltip,k.plotOptions[this.type].tooltip,b.tooltip.userOptions,e.series&&e.series.tooltip,e[this.type].tooltip,a.tooltip);this.stickyTracking=t(a.stickyTracking,m[this.type]&&m[this.type].stickyTracking,m.series&&m.series.stickyTracking,this.tooltipOptions.shared&&!this.noSharedTooltip?!0:h.stickyTracking);null===f.marker&&delete h.marker;
this.zoneAxis=h.zoneAxis;b=this.zones=(h.zones||[]).slice();!h.negativeColor&&!h.negativeFillColor||h.zones||(e={value:h[this.zoneAxis+"Threshold"]||h.threshold||0,className:"highcharts-negative"},d||(e.color=h.negativeColor,e.fillColor=h.negativeFillColor),b.push(e));b.length&&c(b[b.length-1].value)&&b.push(d?{}:{color:this.color,fillColor:this.fillColor});A(this,"afterSetOptions",{options:h});return h};b.prototype.getName=function(){return t(this.options.name,"Series "+(this.index+1))};b.prototype.getCyclic=
function(a,d,b){var e=this.chart,h=this.userOptions,g=a+"Index",f=a+"Counter",m=b?b.length:t(e.options.chart[a+"Count"],e[a+"Count"]);if(!d){var k=t(h[g],h["_"+g]);c(k)||(e.series.length||(e[f]=0),h["_"+g]=k=e[f]%m,e[f]+=1);b&&(d=b[k])}"undefined"!==typeof k&&(this[g]=k);this[a]=d};b.prototype.getColor=function(){this.chart.styledMode?this.getCyclic("color"):this.options.colorByPoint?this.color=H.neutralColor20:this.getCyclic("color",this.options.color||k.plotOptions[this.type].color,this.chart.options.colors)};
b.prototype.getPointsCollection=function(){return(this.hasGroupedData?this.points:this.data)||[]};b.prototype.getSymbol=function(){this.getCyclic("symbol",this.options.marker.symbol,this.chart.options.symbols)};b.prototype.findPointIndex=function(a,c){var d=a.id,b=a.x,e=this.points,h,g=this.options.dataSorting;if(d)var f=this.chart.get(d);else if(this.linkedParent||this.enabledDataSorting){var m=g&&g.matchByName?"name":"index";f=r(e,function(c){return!c.touched&&c[m]===a[m]});if(!f)return}if(f){var k=
f&&f.index;"undefined"!==typeof k&&(h=!0)}"undefined"===typeof k&&R(b)&&(k=this.xData.indexOf(b,c));-1!==k&&"undefined"!==typeof k&&this.cropped&&(k=k>=this.cropStart?k-this.cropStart:k);!h&&e[k]&&e[k].touched&&(k=void 0);return k};b.prototype.updateData=function(a,d){var b=this.options,e=b.dataSorting,h=this.points,g=[],f,k,m,l=this.requireSorting,n=a.length===h.length,r=!0;this.xIncrement=null;a.forEach(function(a,d){var k=c(a)&&this.pointClass.prototype.optionsToObject.call({series:this},a)||{};
var r=k.x;if(k.id||R(r)){if(r=this.findPointIndex(k,m),-1===r||"undefined"===typeof r?g.push(a):h[r]&&a!==b.data[r]?(h[r].update(a,!1,null,!1),h[r].touched=!0,l&&(m=r+1)):h[r]&&(h[r].touched=!0),!n||d!==r||e&&e.enabled||this.hasDerivedData)f=!0}else g.push(a)},this);if(f)for(a=h.length;a--;)(k=h[a])&&!k.touched&&k.remove&&k.remove(!1,d);else!n||e&&e.enabled?r=!1:(a.forEach(function(a,c){h[c].update&&a!==h[c].y&&h[c].update(a,!1,null,!1)}),g.length=0);h.forEach(function(a){a&&(a.touched=!1)});if(!r)return!1;
g.forEach(function(a){this.addPoint(a,!1,null,null,!1)},this);null===this.xIncrement&&this.xData&&this.xData.length&&(this.xIncrement=u(this.xData),this.autoIncrement());return!0};b.prototype.setData=function(c,d,b,e){var h=this,g=h.points,f=g&&g.length||0,k,m=h.options,l=h.chart,r=m.dataSorting,n=null,q=h.xAxis;n=m.turboThreshold;var F=this.xData,p=this.yData,u=(k=h.pointArrayMap)&&k.length,v=m.keys,K=0,w=1,y;c=c||[];k=c.length;d=t(d,!0);r&&r.enabled&&(c=this.sortData(c));!1!==e&&k&&f&&!h.cropped&&
!h.hasGroupedData&&h.visible&&!h.isSeriesBoosting&&(y=this.updateData(c,b));if(!y){h.xIncrement=null;h.colorCounter=0;this.parallelArrays.forEach(function(a){h[a+"Data"].length=0});if(n&&k>n)if(n=h.getFirstValidPoint(c),R(n))for(b=0;b<k;b++)F[b]=this.autoIncrement(),p[b]=c[b];else if(L(n))if(u)for(b=0;b<k;b++)e=c[b],F[b]=e[0],p[b]=e.slice(1,u+1);else for(v&&(K=v.indexOf("x"),w=v.indexOf("y"),K=0<=K?K:0,w=0<=w?w:1),b=0;b<k;b++)e=c[b],F[b]=e[K],p[b]=e[w];else a(12,!1,l);else for(b=0;b<k;b++)"undefined"!==
typeof c[b]&&(e={series:h},h.pointClass.prototype.applyOptions.apply(e,[c[b]]),h.updateParallelArrays(e,b));p&&V(p[0])&&a(14,!0,l);h.data=[];h.options.data=h.userOptions.data=c;for(b=f;b--;)g[b]&&g[b].destroy&&g[b].destroy();q&&(q.minRange=q.userMinRange);h.isDirty=l.isDirtyBox=!0;h.isDirtyData=!!g;b=!1}"point"===m.legendType&&(this.processData(),this.generatePoints());d&&l.redraw(b)};b.prototype.sortData=function(a){var d=this,b=d.options.dataSorting.sortKey||"y",e=function(a,d){return c(d)&&a.pointClass.prototype.optionsToObject.call({series:a},
d)||{}};a.forEach(function(c,b){a[b]=e(d,c);a[b].index=b},this);a.concat().sort(function(a,c){a=y(b,a);c=y(b,c);return c<a?-1:c>a?1:0}).forEach(function(a,c){a.x=c},this);d.linkedSeries&&d.linkedSeries.forEach(function(c){var d=c.options,b=d.data;d.dataSorting&&d.dataSorting.enabled||!b||(b.forEach(function(d,h){b[h]=e(c,d);a[h]&&(b[h].x=a[h].x,b[h].index=h)}),c.setData(b,!1))});return a};b.prototype.getProcessedData=function(c){var d=this.xData,b=this.yData,e=d.length;var h=0;var g=this.xAxis,f=
this.options;var k=f.cropThreshold;var m=c||this.getExtremesFromAll||f.getExtremesFromAll,l=this.isCartesian;c=g&&g.val2lin;f=!(!g||!g.logarithmic);var n=this.requireSorting;if(g){g=g.getExtremes();var r=g.min;var q=g.max}if(l&&this.sorted&&!m&&(!k||e>k||this.forceCrop))if(d[e-1]<r||d[0]>q)d=[],b=[];else if(this.yData&&(d[0]<r||d[e-1]>q)){h=this.cropData(this.xData,this.yData,r,q);d=h.xData;b=h.yData;h=h.start;var F=!0}for(k=d.length||1;--k;)if(e=f?c(d[k])-c(d[k-1]):d[k]-d[k-1],0<e&&("undefined"===
typeof p||e<p))var p=e;else 0>e&&n&&(a(15,!1,this.chart),n=!1);return{xData:d,yData:b,cropped:F,cropStart:h,closestPointRange:p}};b.prototype.processData=function(a){var c=this.xAxis;if(this.isCartesian&&!this.isDirty&&!c.isDirty&&!this.yAxis.isDirty&&!a)return!1;a=this.getProcessedData();this.cropped=a.cropped;this.cropStart=a.cropStart;this.processedXData=a.xData;this.processedYData=a.yData;this.closestPointRange=this.basePointRange=a.closestPointRange};b.prototype.cropData=function(a,c,d,b,e){var h=
a.length,g=0,f=h,k;e=t(e,this.cropShoulder);for(k=0;k<h;k++)if(a[k]>=d){g=Math.max(0,k-e);break}for(d=k;d<h;d++)if(a[d]>b){f=d+e;break}return{xData:a.slice(g,f),yData:c.slice(g,f),start:g,end:f}};b.prototype.generatePoints=function(){var a=this.options,c=a.data,d=this.data,b,e=this.processedXData,g=this.processedYData,f=this.pointClass,k=e.length,m=this.cropStart||0,l=this.hasGroupedData,n=a.keys,r=[],q;a=a.dataGrouping&&a.dataGrouping.groupAll?m:0;d||l||(d=[],d.length=c.length,d=this.data=d);n&&
l&&(this.options.keys=!1);for(q=0;q<k;q++){var p=m+q;if(l){var u=(new f).init(this,[e[q]].concat(O(g[q])));u.dataGroup=this.groupMap[a+q];u.dataGroup.options&&(u.options=u.dataGroup.options,h(u,u.dataGroup.options),delete u.dataLabels)}else(u=d[p])||"undefined"===typeof c[p]||(d[p]=u=(new f).init(this,c[p],e[q]));u&&(u.index=l?a+q:p,r[q]=u)}this.options.keys=n;if(d&&(k!==(b=d.length)||l))for(q=0;q<b;q++)q!==m||l||(q+=k),d[q]&&(d[q].destroyElements(),d[q].plotX=void 0);this.data=d;this.points=r;A(this,
"afterGeneratePoints")};b.prototype.getXExtremes=function(a){return{min:n(a),max:u(a)}};b.prototype.getExtremes=function(a,c){var d=this.xAxis,b=this.yAxis,e=this.processedXData||this.xData,h=[],g=0,f=0;var k=0;var m=this.requireSorting?this.cropShoulder:0,l=b?b.positiveValuesOnly:!1,r;a=a||this.stackedYData||this.processedYData||[];b=a.length;d&&(k=d.getExtremes(),f=k.min,k=k.max);for(r=0;r<b;r++){var q=e[r];var p=a[r];var F=(R(p)||L(p))&&(p.length||0<p||!l);q=c||this.getExtremesFromAll||this.options.getExtremesFromAll||
this.cropped||!d||(e[r+m]||q)>=f&&(e[r-m]||q)<=k;if(F&&q)if(F=p.length)for(;F--;)R(p[F])&&(h[g++]=p[F]);else h[g++]=p}a={dataMin:n(h),dataMax:u(h)};A(this,"afterGetExtremes",{dataExtremes:a});return a};b.prototype.applyExtremes=function(){var a=this.getExtremes();this.dataMin=a.dataMin;this.dataMax=a.dataMax;return a};b.prototype.getFirstValidPoint=function(a){for(var c=null,d=a.length,b=0;null===c&&b<d;)c=a[b],b++;return c};b.prototype.translate=function(){this.processedXData||this.processData();
this.generatePoints();var a=this.options,d=a.stacking,b=this.xAxis,e=b.categories,h=this.enabledDataSorting,g=this.yAxis,f=this.points,k=f.length,l=!!this.modifyValue,r,n=this.pointPlacementToXValue(),q=!!n,p=a.threshold,u=a.startFromThreshold?p:0,v,w=this.zoneAxis||"y",y=Number.MAX_VALUE;for(r=0;r<k;r++){var E=f[r],x=E.x,D=E.y,B=E.low,P=d&&g.stacking&&g.stacking.stacks[(this.negStacks&&D<(u?0:p)?"-":"")+this.stackKey],N=void 0,C=void 0;if(g.positiveValuesOnly&&!g.validatePositiveValue(D)||b.positiveValuesOnly&&
!b.validatePositiveValue(x))E.isNull=!0;E.plotX=v=m(J(b.translate(x,0,0,0,1,n,"flags"===this.type),-1E5,1E5));if(d&&this.visible&&P&&P[x]){var z=this.getStackIndicator(z,x,this.index);E.isNull||(N=P[x],C=N.points[z.key])}L(C)&&(B=C[0],D=C[1],B===u&&z.key===P[x].base&&(B=t(R(p)&&p,g.min)),g.positiveValuesOnly&&0>=B&&(B=null),E.total=E.stackTotal=N.total,E.percentage=N.total&&E.y/N.total*100,E.stackY=D,this.irregularWidths||N.setOffset(this.pointXOffset||0,this.barW||0));E.yBottom=c(B)?J(g.translate(B,
0,1,0,1),-1E5,1E5):null;l&&(D=this.modifyValue(D,E));E.plotY=void 0;R(D)&&(D=g.translate(D,!1,!0,!1,!0),"undefined"!==typeof D&&(E.plotY=J(D,-1E5,1E5)));E.isInside=this.isPointInside(E);E.clientX=q?m(b.translate(x,0,0,0,1,n)):v;E.negative=E[w]<(a[w+"Threshold"]||p||0);E.category=e&&"undefined"!==typeof e[E.x]?e[E.x]:E.x;if(!E.isNull&&!1!==E.visible){"undefined"!==typeof M&&(y=Math.min(y,Math.abs(v-M)));var M=v}E.zone=this.zones.length&&E.getZone();!E.graphic&&this.group&&h&&(E.isNew=!0)}this.closestPointRangePx=
y;A(this,"afterTranslate")};b.prototype.getValidPoints=function(a,c,d){var b=this.chart;return(a||this.points||[]).filter(function(a){return c&&!b.isInsidePlot(a.plotX,a.plotY,{inverted:b.inverted})?!1:!1!==a.visible&&(d||!a.isNull)})};b.prototype.getClipBox=function(a,c){var d=this.options,b=this.chart,e=b.inverted,h=this.xAxis,g=h&&this.yAxis,f=b.options.chart.scrollablePlotArea||{};a&&!1===d.clip&&g?a=e?{y:-b.chartWidth+g.len+g.pos,height:b.chartWidth,width:b.chartHeight,x:-b.chartHeight+h.len+
h.pos}:{y:-g.pos,height:b.chartHeight,width:b.chartWidth,x:-h.pos}:(a=this.clipBox||b.clipBox,c&&(a.width=b.plotSizeX,a.x=(b.scrollablePixelsX||0)*(f.scrollPositionX||0)));return c?{width:a.width,x:a.x}:a};b.prototype.getSharedClipKey=function(a){if(this.sharedClipKey)return this.sharedClipKey;var c=[a&&a.duration,a&&a.easing,a&&a.defer,this.getClipBox(a).height,this.options.xAxis,this.options.yAxis].join();if(!1!==this.options.clip||a)this.sharedClipKey=c;return c};b.prototype.setClip=function(a){var c=
this.chart,d=this.options,b=c.renderer,e=c.inverted,h=this.clipBox,g=this.getClipBox(a),f=this.getSharedClipKey(a),k=c.sharedClips[f],m=c.sharedClips[f+"m"];a&&(g.width=0,e&&(g.x=c.plotHeight+(!1!==d.clip?0:c.plotTop)));k?c.hasLoaded||k.attr(g):(a&&(c.sharedClips[f+"m"]=m=b.clipRect(e?(c.plotSizeX||0)+99:-99,e?-c.plotLeft:-c.plotTop,99,e?c.chartWidth:c.chartHeight)),c.sharedClips[f]=k=b.clipRect(g),k.count={length:0});a&&!k.count[this.index]&&(k.count[this.index]=!0,k.count.length+=1);if(!1!==d.clip||
a)this.group.clip(a||h?k:c.clipRect),this.markerGroup.clip(m);a||(k.count[this.index]&&(delete k.count[this.index],--k.count.length),0===k.count.length&&(h||(c.sharedClips[f]=k.destroy()),m&&(c.sharedClips[f+"m"]=m.destroy())))};b.prototype.animate=function(a){var c=this.chart,d=w(this.options.animation),b=this.sharedClipKey;if(a)this.setClip(d);else if(b){a=c.sharedClips[b];b=c.sharedClips[b+"m"];var e=this.getClipBox(d,!0);a&&a.animate(e,d);b&&b.animate({width:e.width+99,x:e.x-(c.inverted?0:99)},
d)}};b.prototype.afterAnimate=function(){this.setClip();A(this,"afterAnimate");this.finishedAnimating=!0};b.prototype.drawPoints=function(){var a=this.points,c=this.chart,d,b,e=this.options.marker,h=this[this.specialGroup]||this.markerGroup,g=this.xAxis,f=t(e.enabled,!g||g.isRadial?!0:null,this.closestPointRangePx>=e.enabledThreshold*e.radius);if(!1!==e.enabled||this._hasPointMarkers)for(d=0;d<a.length;d++){var k=a[d];var m=(b=k.graphic)?"animate":"attr";var l=k.marker||{};var r=!!k.marker;if((f&&
"undefined"===typeof l.enabled||l.enabled)&&!k.isNull&&!1!==k.visible){var n=t(l.symbol,this.symbol);var q=this.markerAttribs(k,k.selected&&"select");this.enabledDataSorting&&(k.startXPos=g.reversed?-(q.width||0):g.width);var p=!1!==k.isInside;b?b[p?"show":"hide"](p).animate(q):p&&(0<(q.width||0)||k.hasImage)&&(k.graphic=b=c.renderer.symbol(n,q.x,q.y,q.width,q.height,r?l:e).add(h),this.enabledDataSorting&&c.hasRendered&&(b.attr({x:k.startXPos}),m="animate"));b&&"animate"===m&&b[p?"show":"hide"](p).animate(q);
if(b&&!c.styledMode)b[m](this.pointAttribs(k,k.selected&&"select"));b&&b.addClass(k.getClassName(),!0)}else b&&(k.graphic=b.destroy())}};b.prototype.markerAttribs=function(a,c){var d=this.options,b=d.marker,e=a.marker||{},h=e.symbol||b.symbol,g=t(e.radius,b.radius);c&&(b=b.states[c],c=e.states&&e.states[c],g=t(c&&c.radius,b&&b.radius,g+(b&&b.radiusPlus||0)));a.hasImage=h&&0===h.indexOf("url");a.hasImage&&(g=0);a={x:d.crisp?Math.floor(a.plotX-g):a.plotX-g,y:a.plotY-g};g&&(a.width=a.height=2*g);return a};
b.prototype.pointAttribs=function(a,c){var d=this.options.marker,b=a&&a.options,e=b&&b.marker||{},h=this.color,g=b&&b.color,f=a&&a.color;b=t(e.lineWidth,d.lineWidth);var k=a&&a.zone&&a.zone.color;a=1;h=g||k||f||h;g=e.fillColor||d.fillColor||h;h=e.lineColor||d.lineColor||h;c=c||"normal";d=d.states[c];c=e.states&&e.states[c]||{};b=t(c.lineWidth,d.lineWidth,b+t(c.lineWidthPlus,d.lineWidthPlus,0));g=c.fillColor||d.fillColor||g;h=c.lineColor||d.lineColor||h;a=t(c.opacity,d.opacity,a);return{stroke:h,"stroke-width":b,
fill:g,opacity:a}};b.prototype.destroy=function(a){var c=this,d=c.chart,b=/AppleWebKit\/533/.test(q.navigator.userAgent),e,h,f=c.data||[],k,m;A(c,"destroy");this.removeEvents(a);(c.axisTypes||[]).forEach(function(a){(m=c[a])&&m.series&&(g(m.series,c),m.isDirty=m.forceRedraw=!0)});c.legendItem&&c.chart.legend.destroyItem(c);for(h=f.length;h--;)(k=f[h])&&k.destroy&&k.destroy();c.clips&&c.clips.forEach(function(a){return a.destroy()});x.clearTimeout(c.animationTimeout);M(c,function(a,c){a instanceof
B&&!a.survive&&(e=b&&"group"===c?"hide":"destroy",a[e]())});d.hoverSeries===c&&(d.hoverSeries=void 0);g(d.series,c);d.orderSeries();M(c,function(d,b){a&&"hcEvents"===b||delete c[b]})};b.prototype.applyZones=function(){var a=this,c=this.chart,d=c.renderer,b=this.zones,e,h,g=this.clips||[],f,k=this.graph,m=this.area,l=Math.max(c.chartWidth,c.chartHeight),r=this[(this.zoneAxis||"y")+"Axis"],n=c.inverted,q,p,u,v=!1,w,y;if(b.length&&(k||m)&&r&&"undefined"!==typeof r.min){var E=r.reversed;var A=r.horiz;
k&&!this.showLine&&k.hide();m&&m.hide();var x=r.getExtremes();b.forEach(function(b,F){e=E?A?c.plotWidth:0:A?0:r.toPixels(x.min)||0;e=J(t(h,e),0,l);h=J(Math.round(r.toPixels(t(b.value,x.max),!0)||0),0,l);v&&(e=h=r.toPixels(x.max));q=Math.abs(e-h);p=Math.min(e,h);u=Math.max(e,h);r.isXAxis?(f={x:n?u:p,y:0,width:q,height:l},A||(f.x=c.plotHeight-f.x)):(f={x:0,y:n?u:p,width:l,height:q},A&&(f.y=c.plotWidth-f.y));n&&d.isVML&&(f=r.isXAxis?{x:0,y:E?p:u,height:f.width,width:c.chartWidth}:{x:f.y-c.plotLeft-c.spacingBox.x,
y:0,width:f.height,height:c.chartHeight});g[F]?g[F].animate(f):g[F]=d.clipRect(f);w=a["zone-area-"+F];y=a["zone-graph-"+F];k&&y&&y.clip(g[F]);m&&w&&w.clip(g[F]);v=b.value>x.max;a.resetZones&&0===h&&(h=void 0)});this.clips=g}else a.visible&&(k&&k.show(!0),m&&m.show(!0))};b.prototype.invertGroups=function(a){function c(){["group","markerGroup"].forEach(function(c){d[c]&&(b.renderer.isVML&&d[c].attr({width:d.yAxis.len,height:d.xAxis.len}),d[c].width=d.yAxis.len,d[c].height=d.xAxis.len,d[c].invert(d.isRadialSeries?
!1:a))})}var d=this,b=d.chart;d.xAxis&&(d.eventsToUnbind.push(D(b,"resize",c)),c(),d.invertGroups=c)};b.prototype.plotGroup=function(a,d,b,e,h){var g=this[a],f=!g;b={visibility:b,zIndex:e||.1};"undefined"===typeof this.opacity||this.chart.styledMode||"inactive"===this.state||(b.opacity=this.opacity);f&&(this[a]=g=this.chart.renderer.g().add(h));g.addClass("highcharts-"+d+" highcharts-series-"+this.index+" highcharts-"+this.type+"-series "+(c(this.colorIndex)?"highcharts-color-"+this.colorIndex+" ":
"")+(this.options.className||"")+(g.hasClass("highcharts-tracker")?" highcharts-tracker":""),!0);g.attr(b)[f?"attr":"animate"](this.getPlotBox());return g};b.prototype.getPlotBox=function(){var a=this.chart,c=this.xAxis,d=this.yAxis;a.inverted&&(c=d,d=this.xAxis);return{translateX:c?c.left:a.plotLeft,translateY:d?d.top:a.plotTop,scaleX:1,scaleY:1}};b.prototype.removeEvents=function(a){a||p(this);this.eventsToUnbind.length&&(this.eventsToUnbind.forEach(function(a){a()}),this.eventsToUnbind.length=
0)};b.prototype.render=function(){var a=this,c=a.chart,d=a.options,b=w(d.animation),e=!a.finishedAnimating&&c.renderer.isSVG&&b.duration,h=a.visible?"inherit":"hidden",g=d.zIndex,f=a.hasRendered,k=c.seriesGroup,m=c.inverted;A(this,"render");var l=a.plotGroup("group","series",h,g,k);a.markerGroup=a.plotGroup("markerGroup","markers",h,g,k);e&&a.animate&&a.animate(!0);l.inverted=t(a.invertible,a.isCartesian)?m:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());a.visible&&a.drawPoints();a.drawDataLabels&&
a.drawDataLabels();a.redrawPoints&&a.redrawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(m);!1===d.clip||a.sharedClipKey||f||l.clip(c.clipRect);e&&a.animate&&a.animate();f||(e&&b.defer&&(e+=b.defer),a.animationTimeout=Z(function(){a.afterAnimate()},e||0));a.isDirty=!1;a.hasRendered=!0;A(a,"afterRender")};b.prototype.redraw=function(){var a=this.chart,c=this.isDirty||this.isDirtyData,d=this.group,b=this.xAxis,e=this.yAxis;d&&(a.inverted&&d.attr({width:a.plotWidth,
height:a.plotHeight}),d.animate({translateX:t(b&&b.left,a.plotLeft),translateY:t(e&&e.top,a.plotTop)}));this.translate();this.render();c&&delete this.kdTree};b.prototype.searchPoint=function(a,c){var d=this.xAxis,b=this.yAxis,e=this.chart.inverted;return this.searchKDTree({clientX:e?d.len-a.chartY+d.pos:a.chartX-d.pos,plotY:e?b.len-a.chartX+b.pos:a.chartY-b.pos},c,a)};b.prototype.buildKDTree=function(a){function c(a,b,e){var h;if(h=a&&a.length){var g=d.kdAxisArray[b%e];a.sort(function(a,c){return a[g]-
c[g]});h=Math.floor(h/2);return{point:a[h],left:c(a.slice(0,h),b+1,e),right:c(a.slice(h+1),b+1,e)}}}this.buildingKdTree=!0;var d=this,b=-1<d.options.findNearestPointBy.indexOf("y")?2:1;delete d.kdTree;Z(function(){d.kdTree=c(d.getValidPoints(null,!d.directTouch),b,b);d.buildingKdTree=!1},d.options.kdNow||a&&"touchstart"===a.type?0:1)};b.prototype.searchKDTree=function(a,d,b){function e(a,d,b,m){var l=d.point,r=h.kdAxisArray[b%m],n=l;var q=c(a[g])&&c(l[g])?Math.pow(a[g]-l[g],2):null;var p=c(a[f])&&
c(l[f])?Math.pow(a[f]-l[f],2):null;p=(q||0)+(p||0);l.dist=c(p)?Math.sqrt(p):Number.MAX_VALUE;l.distX=c(q)?Math.sqrt(q):Number.MAX_VALUE;r=a[r]-l[r];p=0>r?"left":"right";q=0>r?"right":"left";d[p]&&(p=e(a,d[p],b+1,m),n=p[k]<n[k]?p:l);d[q]&&Math.sqrt(r*r)<n[k]&&(a=e(a,d[q],b+1,m),n=a[k]<n[k]?a:n);return n}var h=this,g=this.kdAxisArray[0],f=this.kdAxisArray[1],k=d?"distX":"dist";d=-1<h.options.findNearestPointBy.indexOf("y")?2:1;this.kdTree||this.buildingKdTree||this.buildKDTree(b);if(this.kdTree)return e(a,
this.kdTree,d,d)};b.prototype.pointPlacementToXValue=function(){var a=this.options,c=a.pointRange,d=this.xAxis;a=a.pointPlacement;"between"===a&&(a=d.reversed?-.5:.5);return R(a)?a*(c||d.pointRange):0};b.prototype.isPointInside=function(a){return"undefined"!==typeof a.plotY&&"undefined"!==typeof a.plotX&&0<=a.plotY&&a.plotY<=this.yAxis.len&&0<=a.plotX&&a.plotX<=this.xAxis.len};b.prototype.drawTracker=function(){var a=this,c=a.options,b=c.trackByArea,e=[].concat(b?a.areaPath:a.graphPath),h=a.chart,
g=h.pointer,k=h.renderer,m=h.options.tooltip.snap,l=a.tracker,r=function(c){if(h.hoverSeries!==a)a.onMouseOver()},n="rgba(192,192,192,"+(d?.0001:.002)+")";l?l.attr({d:e}):a.graph&&(a.tracker=k.path(e).attr({visibility:a.visible?"visible":"hidden",zIndex:2}).addClass(b?"highcharts-tracker-area":"highcharts-tracker-line").add(a.group),h.styledMode||a.tracker.attr({"stroke-linecap":"round","stroke-linejoin":"round",stroke:n,fill:b?n:"none","stroke-width":a.graph.strokeWidth()+(b?0:2*m)}),[a.tracker,
a.markerGroup,a.dataLabelsGroup].forEach(function(a){if(a&&(a.addClass("highcharts-tracker").on("mouseover",r).on("mouseout",function(a){g.onTrackerMouseOut(a)}),c.cursor&&!h.styledMode&&a.css({cursor:c.cursor}),f))a.on("touchstart",r)}));A(this,"afterDrawTracker")};b.prototype.addPoint=function(a,c,d,b,e){var h=this.options,g=this.data,f=this.chart,k=this.xAxis;k=k&&k.hasNames&&k.names;var m=h.data,l=this.xData,r;c=t(c,!0);var n={series:this};this.pointClass.prototype.applyOptions.apply(n,[a]);var q=
n.x;var p=l.length;if(this.requireSorting&&q<l[p-1])for(r=!0;p&&l[p-1]>q;)p--;this.updateParallelArrays(n,"splice",p,0,0);this.updateParallelArrays(n,p);k&&n.name&&(k[q]=n.name);m.splice(p,0,a);r&&(this.data.splice(p,0,null),this.processData());"point"===h.legendType&&this.generatePoints();d&&(g[0]&&g[0].remove?g[0].remove(!1):(g.shift(),this.updateParallelArrays(n,"shift"),m.shift()));!1!==e&&A(this,"addPoint",{point:n});this.isDirtyData=this.isDirty=!0;c&&f.redraw(b)};b.prototype.removePoint=function(a,
c,d){var b=this,e=b.data,h=e[a],g=b.points,f=b.chart,k=function(){g&&g.length===e.length&&g.splice(a,1);e.splice(a,1);b.options.data.splice(a,1);b.updateParallelArrays(h||{series:b},"splice",a,1);h&&h.destroy();b.isDirty=!0;b.isDirtyData=!0;c&&f.redraw()};v(d,f);c=t(c,!0);h?h.firePointEvent("remove",null,k):k()};b.prototype.remove=function(a,c,d,b){function e(){h.destroy(b);g.isDirtyLegend=g.isDirtyBox=!0;g.linkSeries();t(a,!0)&&g.redraw(c)}var h=this,g=h.chart;!1!==d?A(h,"remove",null,e):e()};b.prototype.update=
function(c,d){c=E(c,this.userOptions);A(this,"update",{options:c});var b=this,e=b.chart,g=b.userOptions,f=b.initialType||b.type,k=e.options.plotOptions,m=c.type||g.type||e.options.chart.type,r=!(this.hasDerivedData||m&&m!==this.type||"undefined"!==typeof c.pointStart||"undefined"!==typeof c.pointInterval||b.hasOptionChanged("dataGrouping")||b.hasOptionChanged("pointStart")||b.hasOptionChanged("pointInterval")||b.hasOptionChanged("pointIntervalUnit")||b.hasOptionChanged("keys")),n=l[f].prototype,q,
p=["eventOptions","navigatorSeries","baseSeries"],u=b.finishedAnimating&&{animation:!1},v={};m=m||f;r&&(p.push("data","isDirtyData","points","processedXData","processedYData","xIncrement","cropped","_hasPointMarkers","_hasPointLabels","clips","nodes","layout","mapMap","mapData","minY","maxY","minX","maxX"),!1!==c.visible&&p.push("area","graph"),b.parallelArrays.forEach(function(a){p.push(a+"Data")}),c.data&&(c.dataSorting&&h(b.options.dataSorting,c.dataSorting),this.setData(c.data,!1)));c=Q(g,u,{index:"undefined"===
typeof g.index?b.index:g.index,pointStart:t(k&&k.series&&k.series.pointStart,g.pointStart,b.xData[0])},!r&&{data:b.options.data},c);r&&c.data&&(c.data=b.options.data);p=["group","markerGroup","dataLabelsGroup","transformGroup"].concat(p);p.forEach(function(a){p[a]=b[a];delete b[a]});g=!1;if(l[m]){if(g=m!==b.type,b.remove(!1,!1,!1,!0),g)if(Object.setPrototypeOf)Object.setPrototypeOf(b,l[m].prototype);else{k=Object.hasOwnProperty.call(b,"hcEvents")&&b.hcEvents;for(q in n)b[q]=void 0;h(b,l[m].prototype);
k?b.hcEvents=k:delete b.hcEvents}}else a(17,!0,e,{missingModuleFor:m});p.forEach(function(a){b[a]=p[a]});b.init(e,c);if(r&&this.points){var w=b.options;!1===w.visible?(v.graphic=1,v.dataLabel=1):b._hasPointLabels||(c=w.marker,m=w.dataLabels,c&&(!1===c.enabled||"symbol"in c)&&(v.graphic=1),m&&!1===m.enabled&&(v.dataLabel=1));this.points.forEach(function(a){a&&a.series&&(a.resolveColor(),Object.keys(v).length&&a.destroyElements(v),!1===w.showInLegend&&a.legendItem&&e.legend.destroyItem(a))},this)}b.initialType=
f;e.linkSeries();g&&b.linkedSeries.length&&(b.isDirtyData=!0);A(this,"afterUpdate");t(d,!0)&&e.redraw(r?void 0:!1)};b.prototype.setName=function(a){this.name=this.options.name=this.userOptions.name=a;this.chart.isDirtyLegend=!0};b.prototype.hasOptionChanged=function(a){var c=this.options[a],d=this.chart.options.plotOptions,b=this.userOptions[a];return b?c!==b:c!==t(d&&d[this.type]&&d[this.type][a],d&&d.series&&d.series[a],c)};b.prototype.onMouseOver=function(){var a=this.chart,c=a.hoverSeries;a.pointer.setHoverChartIndex();
if(c&&c!==this)c.onMouseOut();this.options.events.mouseOver&&A(this,"mouseOver");this.setState("hover");a.hoverSeries=this};b.prototype.onMouseOut=function(){var a=this.options,c=this.chart,d=c.tooltip,b=c.hoverPoint;c.hoverSeries=null;if(b)b.onMouseOut();this&&a.events.mouseOut&&A(this,"mouseOut");!d||this.stickyTracking||d.shared&&!this.noSharedTooltip||d.hide();c.series.forEach(function(a){a.setState("",!0)})};b.prototype.setState=function(a,c){var d=this,b=d.options,e=d.graph,h=b.inactiveOtherPoints,
g=b.states,f=b.lineWidth,k=b.opacity,m=t(g[a||"normal"]&&g[a||"normal"].animation,d.chart.options.chart.animation);b=0;a=a||"";if(d.state!==a&&([d.group,d.markerGroup,d.dataLabelsGroup].forEach(function(c){c&&(d.state&&c.removeClass("highcharts-series-"+d.state),a&&c.addClass("highcharts-series-"+a))}),d.state=a,!d.chart.styledMode)){if(g[a]&&!1===g[a].enabled)return;a&&(f=g[a].lineWidth||f+(g[a].lineWidthPlus||0),k=t(g[a].opacity,k));if(e&&!e.dashstyle)for(g={"stroke-width":f},e.animate(g,m);d["zone-graph-"+
b];)d["zone-graph-"+b].animate(g,m),b+=1;h||[d.group,d.markerGroup,d.dataLabelsGroup,d.labelBySeries].forEach(function(a){a&&a.animate({opacity:k},m)})}c&&h&&d.points&&d.setAllPointsToState(a||void 0)};b.prototype.setAllPointsToState=function(a){this.points.forEach(function(c){c.setState&&c.setState(a)})};b.prototype.setVisible=function(a,c){var d=this,b=d.chart,e=d.legendItem,h=b.options.chart.ignoreHiddenSeries,g=d.visible;var f=(d.visible=a=d.options.visible=d.userOptions.visible="undefined"===
typeof a?!g:a)?"show":"hide";["group","dataLabelsGroup","markerGroup","tracker","tt"].forEach(function(a){if(d[a])d[a][f]()});if(b.hoverSeries===d||(b.hoverPoint&&b.hoverPoint.series)===d)d.onMouseOut();e&&b.legend.colorizeItem(d,a);d.isDirty=!0;d.options.stacking&&b.series.forEach(function(a){a.options.stacking&&a.visible&&(a.isDirty=!0)});d.linkedSeries.forEach(function(c){c.setVisible(a,!1)});h&&(b.isDirtyBox=!0);A(d,f);!1!==c&&b.redraw()};b.prototype.show=function(){this.setVisible(!0)};b.prototype.hide=
function(){this.setVisible(!1)};b.prototype.select=function(a){this.selected=a=this.options.selected="undefined"===typeof a?!this.selected:a;this.checkbox&&(this.checkbox.checked=a);A(this,a?"select":"unselect")};b.prototype.shouldShowTooltip=function(a,c,d){void 0===d&&(d={});d.series=this;d.visiblePlotOnly=!0;return this.chart.isInsidePlot(a,c,d)};b.defaultOptions={lineWidth:2,allowPointSelect:!1,crisp:!0,showCheckbox:!1,animation:{duration:1E3},events:{},marker:{enabledThreshold:2,lineColor:H.backgroundColor,
lineWidth:0,radius:4,states:{normal:{animation:!0},hover:{animation:{duration:50},enabled:!0,radiusPlus:2,lineWidthPlus:1},select:{fillColor:H.neutralColor20,lineColor:H.neutralColor100,lineWidth:2}}},point:{events:{}},dataLabels:{animation:{},align:"center",defer:!0,formatter:function(){var a=this.series.chart.numberFormatter;return"number"!==typeof this.y?"":a(this.y,-1)},padding:5,style:{fontSize:"11px",fontWeight:"bold",color:"contrast",textOutline:"1px contrast"},verticalAlign:"bottom",x:0,y:0},
cropThreshold:300,opacity:1,pointRange:0,softThreshold:!0,states:{normal:{animation:!0},hover:{animation:{duration:50},lineWidthPlus:1,marker:{},halo:{size:10,opacity:.25}},select:{animation:{duration:0}},inactive:{animation:{duration:50},opacity:.2}},stickyTracking:!0,turboThreshold:1E3,findNearestPointBy:"x"};return b}();h(e.prototype,{axisTypes:["xAxis","yAxis"],coll:"series",colorCounter:0,cropShoulder:1,directTouch:!1,drawLegendSymbol:I.drawLineMarker,isCartesian:!0,kdAxisArray:["clientX","plotY"],
parallelArrays:["x","y"],pointClass:G,requireSorting:!0,sorted:!0});C.series=e;"";"";return e});O(e,"Extensions/ScrollablePlotArea.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Axis/Axis.js"],e["Core/Chart/Chart.js"],e["Core/Series/Series.js"],e["Core/Globals.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G){var D=e.stop,B=G.addEvent,x=G.createElement,w=G.merge,v=G.pick;"";B(I,"afterSetChartSize",function(b){var d=this.options.chart.scrollablePlotArea,e=d&&d.minWidth;d=d&&d.minHeight;if(!this.renderer.forExport){if(e){if(this.scrollablePixelsX=
e=Math.max(0,e-this.chartWidth)){this.scrollablePlotBox=this.renderer.scrollablePlotBox=w(this.plotBox);this.plotBox.width=this.plotWidth+=e;this.inverted?this.clipBox.height+=e:this.clipBox.width+=e;var f={1:{name:"right",value:e}}}}else d&&(this.scrollablePixelsY=e=Math.max(0,d-this.chartHeight))&&(this.scrollablePlotBox=this.renderer.scrollablePlotBox=w(this.plotBox),this.plotBox.height=this.plotHeight+=e,this.inverted?this.clipBox.width+=e:this.clipBox.height+=e,f={2:{name:"bottom",value:e}});
f&&!b.skipAxes&&this.axes.forEach(function(d){f[d.side]?d.getPlotLinePath=function(){var b=f[d.side].name,e=this[b];this[b]=e-f[d.side].value;var k=H.Axis.prototype.getPlotLinePath.apply(this,arguments);this[b]=e;return k}:(d.setAxisSize(),d.setAxisTranslation())})}});B(I,"render",function(){this.scrollablePixelsX||this.scrollablePixelsY?(this.setUpScrolling&&this.setUpScrolling(),this.applyFixed()):this.fixedDiv&&this.applyFixed()});I.prototype.setUpScrolling=function(){var b=this,d={WebkitOverflowScrolling:"touch",
overflowX:"hidden",overflowY:"hidden"};this.scrollablePixelsX&&(d.overflowX="auto");this.scrollablePixelsY&&(d.overflowY="auto");this.scrollingParent=x("div",{className:"highcharts-scrolling-parent"},{position:"relative"},this.renderTo);this.scrollingContainer=x("div",{className:"highcharts-scrolling"},d,this.scrollingParent);B(this.scrollingContainer,"scroll",function(){b.pointer&&delete b.pointer.chartPosition});this.innerContainer=x("div",{className:"highcharts-inner-container"},null,this.scrollingContainer);
this.innerContainer.appendChild(this.container);this.setUpScrolling=null};I.prototype.moveFixedElements=function(){var b=this.container,d=this.fixedRenderer,e=".highcharts-contextbutton .highcharts-credits .highcharts-legend .highcharts-legend-checkbox .highcharts-navigator-series .highcharts-navigator-xaxis .highcharts-navigator-yaxis .highcharts-navigator .highcharts-reset-zoom .highcharts-drillup-button .highcharts-scrollbar .highcharts-subtitle .highcharts-title".split(" "),k;this.scrollablePixelsX&&
!this.inverted?k=".highcharts-yaxis":this.scrollablePixelsX&&this.inverted?k=".highcharts-xaxis":this.scrollablePixelsY&&!this.inverted?k=".highcharts-xaxis":this.scrollablePixelsY&&this.inverted&&(k=".highcharts-yaxis");k&&e.push(k+":not(.highcharts-radial-axis)",k+"-labels:not(.highcharts-radial-axis-labels)");e.forEach(function(e){[].forEach.call(b.querySelectorAll(e),function(b){(b.namespaceURI===d.SVG_NS?d.box:d.box.parentNode).appendChild(b);b.style.pointerEvents="auto"})})};I.prototype.applyFixed=
function(){var b=!this.fixedDiv;var d=this.options.chart;var e=d.scrollablePlotArea;b?(this.fixedDiv=x("div",{className:"highcharts-fixed"},{position:"absolute",overflow:"hidden",pointerEvents:"none",zIndex:(d.style&&d.style.zIndex||0)+2,top:0},null,!0),this.scrollingContainer&&this.scrollingContainer.parentNode.insertBefore(this.fixedDiv,this.scrollingContainer),this.renderTo.style.overflow="visible",this.fixedRenderer=d=new H.Renderer(this.fixedDiv,this.chartWidth,this.chartHeight,this.options.chart.style),
this.scrollableMask=d.path().attr({fill:this.options.chart.backgroundColor||"#fff","fill-opacity":v(e.opacity,.85),zIndex:-1}).addClass("highcharts-scrollable-mask").add(),B(this,"afterShowResetZoom",this.moveFixedElements),B(this,"afterDrilldown",this.moveFixedElements),B(this,"afterLayOutTitles",this.moveFixedElements)):this.fixedRenderer.setSize(this.chartWidth,this.chartHeight);if(this.scrollableDirty||b)this.scrollableDirty=!1,this.moveFixedElements();d=this.chartWidth+(this.scrollablePixelsX||
0);var k=this.chartHeight+(this.scrollablePixelsY||0);D(this.container);this.container.style.width=d+"px";this.container.style.height=k+"px";this.renderer.boxWrapper.attr({width:d,height:k,viewBox:[0,0,d,k].join(" ")});this.chartBackground.attr({width:d,height:k});this.scrollingContainer.style.height=this.chartHeight+"px";b&&(e.scrollPositionX&&(this.scrollingContainer.scrollLeft=this.scrollablePixelsX*e.scrollPositionX),e.scrollPositionY&&(this.scrollingContainer.scrollTop=this.scrollablePixelsY*
e.scrollPositionY));k=this.axisOffset;b=this.plotTop-k[0]-1;e=this.plotLeft-k[3]-1;d=this.plotTop+this.plotHeight+k[2]+1;k=this.plotLeft+this.plotWidth+k[1]+1;var l=this.plotLeft+this.plotWidth-(this.scrollablePixelsX||0),w=this.plotTop+this.plotHeight-(this.scrollablePixelsY||0);b=this.scrollablePixelsX?[["M",0,b],["L",this.plotLeft-1,b],["L",this.plotLeft-1,d],["L",0,d],["Z"],["M",l,b],["L",this.chartWidth,b],["L",this.chartWidth,d],["L",l,d],["Z"]]:this.scrollablePixelsY?[["M",e,0],["L",e,this.plotTop-
1],["L",k,this.plotTop-1],["L",k,0],["Z"],["M",e,w],["L",e,this.chartHeight],["L",k,this.chartHeight],["L",k,w],["Z"]]:[["M",0,0]];"adjustHeight"!==this.redrawTrigger&&this.scrollableMask.attr({d:b})};B(b,"afterInit",function(){this.chart.scrollableDirty=!0});B(z,"show",function(){this.chart.scrollableDirty=!0})});O(e,"Core/Axis/StackingAxis.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Utilities.js"]],function(e,b){var D=e.getDeferredAnimation,z=b.addEvent,H=b.destroyObjectProperties,G=
b.fireEvent,C=b.isNumber,B=b.objectEach,x=function(){function b(b){this.oldStacks={};this.stacks={};this.stacksTouched=0;this.axis=b}b.prototype.buildStacks=function(){var b=this.axis,e=b.series,d=b.options.reversedStacks,q=e.length,k;if(!b.isXAxis){this.usePercentage=!1;for(k=q;k--;){var l=e[d?k:q-k-1];l.setStackedPoints();l.setGroupedPoints()}for(k=0;k<q;k++)e[k].modifyStacks();G(b,"afterBuildStacks")}};b.prototype.cleanStacks=function(){if(!this.axis.isXAxis){if(this.oldStacks)var b=this.stacks=
this.oldStacks;B(b,function(b){B(b,function(d){d.cumulative=d.total})})}};b.prototype.resetStacks=function(){var b=this,e=this.stacks;this.axis.isXAxis||B(e,function(d){B(d,function(e,f){C(e.touched)&&e.touched<b.stacksTouched?(e.destroy(),delete d[f]):(e.total=null,e.cumulative=null)})})};b.prototype.renderStackTotals=function(){var b=this.axis,e=b.chart,d=e.renderer,q=this.stacks;b=D(e,b.options.stackLabels&&b.options.stackLabels.animation||!1);var k=this.stackTotalGroup=this.stackTotalGroup||d.g("stack-labels").attr({visibility:"visible",
zIndex:6,opacity:0}).add();k.translate(e.plotLeft,e.plotTop);B(q,function(d){B(d,function(d){d.render(k)})});k.animate({opacity:1},b)};return b}();return function(){function b(){}b.compose=function(e){z(e,"init",b.onInit);z(e,"destroy",b.onDestroy)};b.onDestroy=function(){var b=this.stacking;if(b){var e=b.stacks;B(e,function(d,b){H(d);e[b]=null});b&&b.stackTotalGroup&&b.stackTotalGroup.destroy()}};b.onInit=function(){this.stacking||(this.stacking=new x(this))};return b}()});O(e,"Extensions/Stacking.js",
[e["Core/Axis/Axis.js"],e["Core/Chart/Chart.js"],e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Series/Series.js"],e["Core/Axis/StackingAxis.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C){var D=I.format,x=C.correctFloat,w=C.defined,v=C.destroyObjectProperties,f=C.isArray,d=C.isNumber,q=C.objectEach,k=C.pick;"";var l=function(){function b(d,b,e,f,k){var c=d.chart.inverted;this.axis=d;this.isNegative=e;this.options=b=b||{};this.x=f;this.total=null;this.points={};this.hasValidPoints=
!1;this.stack=k;this.rightCliff=this.leftCliff=0;this.alignOptions={align:b.align||(c?e?"left":"right":"center"),verticalAlign:b.verticalAlign||(c?"middle":e?"bottom":"top"),y:b.y,x:b.x};this.textAlign=b.textAlign||(c?e?"right":"left":"center")}b.prototype.destroy=function(){v(this,this.axis)};b.prototype.render=function(d){var b=this.axis.chart,e=this.options,f=e.format;f=f?D(f,this,b):e.formatter.call(this);this.label?this.label.attr({text:f,visibility:"hidden"}):(this.label=b.renderer.label(f,
null,null,e.shape,null,null,e.useHTML,!1,"stack-labels"),f={r:e.borderRadius||0,text:f,rotation:e.rotation,padding:k(e.padding,5),visibility:"hidden"},b.styledMode||(f.fill=e.backgroundColor,f.stroke=e.borderColor,f["stroke-width"]=e.borderWidth,this.label.css(e.style)),this.label.attr(f),this.label.added||this.label.add(d));this.label.labelrank=b.plotSizeY};b.prototype.setOffset=function(b,e,f,l,m){var c=this.axis,g=c.chart;l=c.translate(c.stacking.usePercentage?100:l?l:this.total,0,0,0,1);f=c.translate(f?
f:0);f=w(l)&&Math.abs(l-f);b=k(m,g.xAxis[0].translate(this.x))+b;c=w(l)&&this.getStackBox(g,this,b,l,e,f,c);e=this.label;f=this.isNegative;b="justify"===k(this.options.overflow,"justify");var a=this.textAlign;e&&c&&(m=e.getBBox(),l=e.padding,a="left"===a?g.inverted?-l:l:"right"===a?m.width:g.inverted&&"center"===a?m.width/2:g.inverted?f?m.width+l:-l:m.width/2,f=g.inverted?m.height/2:f?-l:m.height,this.alignOptions.x=k(this.options.x,0),this.alignOptions.y=k(this.options.y,0),c.x-=a,c.y-=f,e.align(this.alignOptions,
null,c),g.isInsidePlot(e.alignAttr.x+a-this.alignOptions.x,e.alignAttr.y+f-this.alignOptions.y)?e.show():(e.alignAttr.y=-9999,b=!1),b&&H.prototype.justifyDataLabel.call(this.axis,e,this.alignOptions,e.alignAttr,m,c),e.attr({x:e.alignAttr.x,y:e.alignAttr.y}),k(!b&&this.options.crop,!0)&&((g=d(e.x)&&d(e.y)&&g.isInsidePlot(e.x-l+e.width,e.y)&&g.isInsidePlot(e.x+l,e.y))||e.hide()))};b.prototype.getStackBox=function(d,b,e,f,k,c,g){var a=b.axis.reversed,h=d.inverted,m=g.height+g.pos-(h?d.plotLeft:d.plotTop);
b=b.isNegative&&!a||!b.isNegative&&a;return{x:h?b?f-g.right:f-c+g.pos-d.plotLeft:e+d.xAxis[0].transB-d.plotLeft,y:h?g.height-e-k:b?m-f-c:m-f,width:h?c:k,height:h?k:c}};return b}();b.prototype.getStacks=function(){var d=this,b=d.inverted;d.yAxis.forEach(function(d){d.stacking&&d.stacking.stacks&&d.hasVisibleSeries&&(d.stacking.oldStacks=d.stacking.stacks)});d.series.forEach(function(e){var f=e.xAxis&&e.xAxis.options||{};!e.options.stacking||!0!==e.visible&&!1!==d.options.chart.ignoreHiddenSeries||
(e.stackKey=[e.type,k(e.options.stack,""),b?f.top:f.left,b?f.height:f.width].join())})};G.compose(e);H.prototype.setGroupedPoints=function(){var d=this.yAxis.stacking;this.options.centerInCategory&&(this.is("column")||this.is("columnrange"))&&!this.options.stacking&&1<this.chart.series.length?H.prototype.setStackedPoints.call(this,"group"):d&&q(d.stacks,function(b,e){"group"===e.slice(-5)&&(q(b,function(d){return d.destroy()}),delete d.stacks[e])})};H.prototype.setStackedPoints=function(d){var b=
d||this.options.stacking;if(b&&(!0===this.visible||!1===this.chart.options.chart.ignoreHiddenSeries)){var e=this.processedXData,q=this.processedYData,v=[],m=q.length,c=this.options,g=c.threshold,a=k(c.startFromThreshold&&g,0);c=c.stack;d=d?this.type+","+b:this.stackKey;var h="-"+d,r=this.negStacks,A=this.yAxis,y=A.stacking.stacks,D=A.stacking.oldStacks,B,C;A.stacking.stacksTouched+=1;for(C=0;C<m;C++){var z=e[C];var Q=q[C];var M=this.getStackIndicator(M,z,this.index);var t=M.key;var p=(B=r&&Q<(a?0:
g))?h:d;y[p]||(y[p]={});y[p][z]||(D[p]&&D[p][z]?(y[p][z]=D[p][z],y[p][z].total=null):y[p][z]=new l(A,A.options.stackLabels,B,z,c));p=y[p][z];null!==Q?(p.points[t]=p.points[this.index]=[k(p.cumulative,a)],w(p.cumulative)||(p.base=t),p.touched=A.stacking.stacksTouched,0<M.index&&!1===this.singleStacks&&(p.points[t][0]=p.points[this.index+","+z+",0"][0])):p.points[t]=p.points[this.index]=null;"percent"===b?(B=B?d:h,r&&y[B]&&y[B][z]?(B=y[B][z],p.total=B.total=Math.max(B.total,p.total)+Math.abs(Q)||0):
p.total=x(p.total+(Math.abs(Q)||0))):"group"===b?(f(Q)&&(Q=Q[0]),null!==Q&&(p.total=(p.total||0)+1)):p.total=x(p.total+(Q||0));p.cumulative="group"===b?(p.total||1)-1:k(p.cumulative,a)+(Q||0);null!==Q&&(p.points[t].push(p.cumulative),v[C]=p.cumulative,p.hasValidPoints=!0)}"percent"===b&&(A.stacking.usePercentage=!0);"group"!==b&&(this.stackedYData=v);A.stacking.oldStacks={}}};H.prototype.modifyStacks=function(){var d=this,b=d.stackKey,e=d.yAxis.stacking.stacks,f=d.processedXData,k,m=d.options.stacking;
d[m+"Stacker"]&&[b,"-"+b].forEach(function(c){for(var b=f.length,a,h;b--;)if(a=f[b],k=d.getStackIndicator(k,a,d.index,c),h=(a=e[c]&&e[c][a])&&a.points[k.key])d[m+"Stacker"](h,a,b)})};H.prototype.percentStacker=function(d,b,e){b=b.total?100/b.total:0;d[0]=x(d[0]*b);d[1]=x(d[1]*b);this.stackedYData[e]=d[1]};H.prototype.getStackIndicator=function(d,b,e,f){!w(d)||d.x!==b||f&&d.key!==f?d={x:b,index:0,key:f}:d.index++;d.key=[e,b,d.index].join();return d};z.StackItem=l;return z.StackItem});O(e,"Series/Line/LineSeries.js",
[e["Core/Color/Palette.js"],e["Core/Series/Series.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=this&&this.__extends||function(){var b=function(e,w){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var d in e)e.hasOwnProperty(d)&&(b[d]=e[d])};return b(e,w)};return function(e,w){function v(){this.constructor=e}b(e,w);e.prototype=null===w?Object.create(w):(v.prototype=w.prototype,new v)}}(),G=z.defined,
C=z.merge;z=function(B){function x(){var b=null!==B&&B.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;return b}D(x,B);x.prototype.drawGraph=function(){var b=this,v=this.options,f=(this.gappedPath||this.getGraphPath).call(this),d=this.chart.styledMode,q=[["graph","highcharts-graph"]];d||q[0].push(v.lineColor||this.color||e.neutralColor20,v.dashStyle);q=b.getZonesGraphs(q);q.forEach(function(e,l){var k=e[0],q=b[k],n=q?"animate":"attr";q?(q.endX=b.preventGraphAnimation?null:
f.xMap,q.animate({d:f})):f.length&&(b[k]=q=b.chart.renderer.path(f).addClass(e[1]).attr({zIndex:1}).add(b.group));q&&!d&&(k={stroke:e[2],"stroke-width":v.lineWidth,fill:b.fillGraph&&b.color||"none"},e[3]?k.dashstyle=e[3]:"square"!==v.linecap&&(k["stroke-linecap"]=k["stroke-linejoin"]="round"),q[n](k).shadow(2>l&&v.shadow));q&&(q.startX=f.xMap,q.isArea=f.isArea)})};x.prototype.getGraphPath=function(b,e,f){var d=this,q=d.options,k=q.step,l,v=[],u=[],n;b=b||d.points;(l=b.reversed)&&b.reverse();(k={right:1,
center:2}[k]||k&&3)&&l&&(k=4-k);b=this.getValidPoints(b,!1,!(q.connectNulls&&!e&&!f));b.forEach(function(l,w){var m=l.plotX,c=l.plotY,g=b[w-1];(l.leftCliff||g&&g.rightCliff)&&!f&&(n=!0);l.isNull&&!G(e)&&0<w?n=!q.connectNulls:l.isNull&&!e?n=!0:(0===w||n?w=[["M",l.plotX,l.plotY]]:d.getPointSpline?w=[d.getPointSpline(b,l,w)]:k?(w=1===k?[["L",g.plotX,c]]:2===k?[["L",(g.plotX+m)/2,g.plotY],["L",(g.plotX+m)/2,c]]:[["L",m,g.plotY]],w.push(["L",m,c])):w=[["L",m,c]],u.push(l.x),k&&(u.push(l.x),2===k&&u.push(l.x)),
v.push.apply(v,w),n=!1)});v.xMap=u;return d.graphPath=v};x.prototype.getZonesGraphs=function(b){this.zones.forEach(function(e,f){f=["zone-graph-"+f,"highcharts-graph highcharts-zone-graph-"+f+" "+(e.className||"")];this.chart.styledMode||f.push(e.color||this.color,e.dashStyle||this.options.dashStyle);b.push(f)},this);return b};x.defaultOptions=C(b.defaultOptions,{});return x}(b);I.registerSeriesType("line",z);"";return z});O(e,"Series/Area/AreaSeries.js",[e["Core/Color/Color.js"],e["Mixins/LegendSymbol.js"],
e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=this&&this.__extends||function(){var b=function(e,d){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,d){b.__proto__=d}||function(b,d){for(var e in d)d.hasOwnProperty(e)&&(b[e]=d[e])};return b(e,d)};return function(e,d){function f(){this.constructor=e}b(e,d);e.prototype=null===d?Object.create(d):(f.prototype=d.prototype,new f)}}(),G=e.parse,C=I.seriesTypes.line;e=z.extend;var B=z.merge,x=z.objectEach,
w=z.pick;z=function(b){function e(){var d=null!==b&&b.apply(this,arguments)||this;d.data=void 0;d.options=void 0;d.points=void 0;return d}D(e,b);e.prototype.drawGraph=function(){this.areaPath=[];b.prototype.drawGraph.apply(this);var d=this,e=this.areaPath,f=this.options,l=[["area","highcharts-area",this.color,f.fillColor]];this.zones.forEach(function(b,e){l.push(["zone-area-"+e,"highcharts-area highcharts-zone-area-"+e+" "+b.className,b.color||d.color,b.fillColor||f.fillColor])});l.forEach(function(b){var k=
b[0],l=d[k],q=l?"animate":"attr",v={};l?(l.endX=d.preventGraphAnimation?null:e.xMap,l.animate({d:e})):(v.zIndex=0,l=d[k]=d.chart.renderer.path(e).addClass(b[1]).add(d.group),l.isArea=!0);d.chart.styledMode||(v.fill=w(b[3],G(b[2]).setOpacity(w(f.fillOpacity,.75)).get()));l[q](v);l.startX=e.xMap;l.shiftUnit=f.step?2:1})};e.prototype.getGraphPath=function(b){var d=C.prototype.getGraphPath,e=this.options,f=e.stacking,v=this.yAxis,u,n=[],x=[],E=this.index,m=v.stacking.stacks[this.stackKey],c=e.threshold,
g=Math.round(v.getThreshold(e.threshold));e=w(e.connectNulls,"percent"===f);var a=function(a,d,e){var h=b[a];a=f&&m[h.x].points[E];var k=h[e+"Null"]||0;e=h[e+"Cliff"]||0;h=!0;if(e||k){var l=(k?a[0]:a[1])+e;var q=a[0]+e;h=!!k}else!f&&b[d]&&b[d].isNull&&(l=q=c);"undefined"!==typeof l&&(x.push({plotX:r,plotY:null===l?g:v.getThreshold(l),isNull:h,isCliff:!0}),n.push({plotX:r,plotY:null===q?g:v.getThreshold(q),doCurve:!1}))};b=b||this.points;f&&(b=this.getStackPoints(b));for(u=0;u<b.length;u++){f||(b[u].leftCliff=
b[u].rightCliff=b[u].leftNull=b[u].rightNull=void 0);var h=b[u].isNull;var r=w(b[u].rectPlotX,b[u].plotX);var A=f?w(b[u].yBottom,g):g;if(!h||e)e||a(u,u-1,"left"),h&&!f&&e||(x.push(b[u]),n.push({x:u,plotX:r,plotY:A})),e||a(u,u+1,"right")}u=d.call(this,x,!0,!0);n.reversed=!0;h=d.call(this,n,!0,!0);(A=h[0])&&"M"===A[0]&&(h[0]=["L",A[1],A[2]]);h=u.concat(h);h.length&&h.push(["Z"]);d=d.call(this,x,!1,e);h.xMap=u.xMap;this.areaPath=h;return d};e.prototype.getStackPoints=function(b){var d=this,e=[],f=[],
v=this.xAxis,u=this.yAxis,n=u.stacking.stacks[this.stackKey],D={},E=u.series,m=E.length,c=u.options.reversedStacks?1:-1,g=E.indexOf(d);b=b||this.points;if(this.options.stacking){for(var a=0;a<b.length;a++)b[a].leftNull=b[a].rightNull=void 0,D[b[a].x]=b[a];x(n,function(a,c){null!==a.total&&f.push(c)});f.sort(function(a,c){return a-c});var h=E.map(function(a){return a.visible});f.forEach(function(a,b){var k=0,l,r;if(D[a]&&!D[a].isNull)e.push(D[a]),[-1,1].forEach(function(e){var k=1===e?"rightNull":
"leftNull",q=0,t=n[f[b+e]];if(t)for(var p=g;0<=p&&p<m;){var v=E[p].index;l=t.points[v];l||(v===d.index?D[a][k]=!0:h[p]&&(r=n[a].points[v])&&(q-=r[1]-r[0]));p+=c}D[a][1===e?"rightCliff":"leftCliff"]=q});else{for(var q=g;0<=q&&q<m;){if(l=n[a].points[E[q].index]){k=l[1];break}q+=c}k=w(k,0);k=u.translate(k,0,1,0,1);e.push({isNull:!0,plotX:v.translate(a,0,0,0,1),x:a,plotY:k,yBottom:k})}})}return e};e.defaultOptions=B(C.defaultOptions,{threshold:0});return e}(C);e(z.prototype,{singleStacks:!1,drawLegendSymbol:b.drawRectangle});
I.registerSeriesType("area",z);"";return z});O(e,"Series/Spline/SplineSeries.js",[e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b){var D=this&&this.__extends||function(){var b=function(e,x){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var f in e)e.hasOwnProperty(f)&&(b[f]=e[f])};return b(e,x)};return function(e,x){function w(){this.constructor=e}b(e,x);e.prototype=null===x?Object.create(x):(w.prototype=x.prototype,
new w)}}(),z=e.seriesTypes.line,H=b.merge,G=b.pick;b=function(b){function e(){var e=null!==b&&b.apply(this,arguments)||this;e.data=void 0;e.options=void 0;e.points=void 0;return e}D(e,b);e.prototype.getPointSpline=function(b,e,v){var f=e.plotX||0,d=e.plotY||0,q=b[v-1];v=b[v+1];if(q&&!q.isNull&&!1!==q.doCurve&&!e.isCliff&&v&&!v.isNull&&!1!==v.doCurve&&!e.isCliff){b=q.plotY||0;var k=v.plotX||0;v=v.plotY||0;var l=0;var w=(1.5*f+(q.plotX||0))/2.5;var u=(1.5*d+b)/2.5;k=(1.5*f+k)/2.5;var n=(1.5*d+v)/2.5;
k!==w&&(l=(n-u)*(k-f)/(k-w)+d-n);u+=l;n+=l;u>b&&u>d?(u=Math.max(b,d),n=2*d-u):u<b&&u<d&&(u=Math.min(b,d),n=2*d-u);n>v&&n>d?(n=Math.max(v,d),u=2*d-n):n<v&&n<d&&(n=Math.min(v,d),u=2*d-n);e.rightContX=k;e.rightContY=n}e=["C",G(q.rightContX,q.plotX,0),G(q.rightContY,q.plotY,0),G(w,f,0),G(u,d,0),f,d];q.rightContX=q.rightContY=void 0;return e};e.defaultOptions=H(z.defaultOptions);return e}(z);e.registerSeriesType("spline",b);"";return b});O(e,"Series/AreaSpline/AreaSplineSeries.js",[e["Series/Area/AreaSeries.js"],
e["Series/Spline/SplineSeries.js"],e["Mixins/LegendSymbol.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z,H){var D=this&&this.__extends||function(){var b=function(e,f){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var d in e)e.hasOwnProperty(d)&&(b[d]=e[d])};return b(e,f)};return function(e,f){function d(){this.constructor=e}b(e,f);e.prototype=null===f?Object.create(f):(d.prototype=f.prototype,new d)}}(),C=
e.prototype,B=H.extend,x=H.merge;H=function(w){function v(){var b=null!==w&&w.apply(this,arguments)||this;b.data=void 0;b.points=void 0;b.options=void 0;return b}D(v,w);v.defaultOptions=x(b.defaultOptions,e.defaultOptions);return v}(b);B(H.prototype,{getGraphPath:C.getGraphPath,getStackPoints:C.getStackPoints,drawGraph:C.drawGraph,drawLegendSymbol:I.drawRectangle});z.registerSeriesType("areaspline",H);"";return H});O(e,"Series/Column/ColumnSeries.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Color/Color.js"],
e["Core/Globals.js"],e["Mixins/LegendSymbol.js"],e["Core/Color/Palette.js"],e["Core/Series/Series.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C,B){var x=this&&this.__extends||function(){var c=function(b,a){c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,c){a.__proto__=c}||function(a,c){for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b])};return c(b,a)};return function(b,a){function d(){this.constructor=b}c(b,a);b.prototype=null===a?Object.create(a):
(d.prototype=a.prototype,new d)}}(),w=e.animObject,v=b.parse,f=I.hasTouch;e=I.noop;var d=B.clamp,q=B.css,k=B.defined,l=B.extend,D=B.fireEvent,u=B.isArray,n=B.isNumber,J=B.merge,E=B.pick,m=B.objectEach;B=function(c){function b(){var a=null!==c&&c.apply(this,arguments)||this;a.borderWidth=void 0;a.data=void 0;a.group=void 0;a.options=void 0;a.points=void 0;return a}x(b,c);b.prototype.animate=function(a){var c=this,b=this.yAxis,e=c.options,g=this.chart.inverted,f={},k=g?"translateX":"translateY";if(a)f.scaleY=
.001,a=d(b.toPixels(e.threshold),b.pos,b.pos+b.len),g?f.translateX=a-b.len:f.translateY=a,c.clipBox&&c.setClip(),c.group.attr(f);else{var m=Number(c.group.attr(k));c.group.animate({scaleY:1},l(w(c.options.animation),{step:function(a,d){c.group&&(f[k]=m+d.pos*(b.pos-m),c.group.attr(f))}}))}};b.prototype.init=function(a,b){c.prototype.init.apply(this,arguments);var d=this;a=d.chart;a.hasRendered&&a.series.forEach(function(a){a.type===d.type&&(a.isDirty=!0)})};b.prototype.getColumnMetrics=function(){var a=
this,c=a.options,b=a.xAxis,d=a.yAxis,e=b.options.reversedStacks;e=b.reversed&&!e||!b.reversed&&e;var g,f={},k=0;!1===c.grouping?k=1:a.chart.series.forEach(function(c){var b=c.yAxis,e=c.options;if(c.type===a.type&&(c.visible||!a.chart.options.chart.ignoreHiddenSeries)&&d.len===b.len&&d.pos===b.pos){if(e.stacking&&"group"!==e.stacking){g=c.stackKey;"undefined"===typeof f[g]&&(f[g]=k++);var h=f[g]}else!1!==e.grouping&&(h=k++);c.columnIndex=h}});var m=Math.min(Math.abs(b.transA)*(b.ordinal&&b.ordinal.slope||
c.pointRange||b.closestPointRange||b.tickInterval||1),b.len),l=m*c.groupPadding,n=(m-2*l)/(k||1);c=Math.min(c.maxPointWidth||b.len,E(c.pointWidth,n*(1-2*c.pointPadding)));a.columnMetrics={width:c,offset:(n-c)/2+(l+((a.columnIndex||0)+(e?1:0))*n-m/2)*(e?-1:1),paddedWidth:n,columnCount:k};return a.columnMetrics};b.prototype.crispCol=function(a,c,b,d){var e=this.chart,h=this.borderWidth,g=-(h%2?.5:0);h=h%2?.5:1;e.inverted&&e.renderer.isVML&&(h+=1);this.options.crisp&&(b=Math.round(a+b)+g,a=Math.round(a)+
g,b-=a);d=Math.round(c+d)+h;g=.5>=Math.abs(c)&&.5<d;c=Math.round(c)+h;d-=c;g&&d&&(--c,d+=1);return{x:a,y:c,width:b,height:d}};b.prototype.adjustForMissingColumns=function(a,c,b,d){var e=this,h=this.options.stacking;if(!b.isNull&&1<d.columnCount){var g=0,f=0;m(this.yAxis.stacking&&this.yAxis.stacking.stacks,function(a){if("number"===typeof b.x&&(a=a[b.x.toString()])){var c=a.points[e.index],d=a.total;h?(c&&(g=f),a.hasValidPoints&&f++):u(c)&&(g=c[1],f=d||0)}});a=(b.plotX||0)+((f-1)*d.paddedWidth+c)/
2-c-g*d.paddedWidth}return a};b.prototype.translate=function(){var a=this,c=a.chart,b=a.options,e=a.dense=2>a.closestPointRange*a.xAxis.transA;e=a.borderWidth=E(b.borderWidth,e?0:1);var g=a.xAxis,f=a.yAxis,m=b.threshold,l=a.translatedThreshold=f.getThreshold(m),q=E(b.minPointLength,5),v=a.getColumnMetrics(),u=v.width,t=a.barW=Math.max(u,1+2*e),p=a.pointXOffset=v.offset,w=a.dataMin,x=a.dataMax;c.inverted&&(l-=.5);b.pointPadding&&(t=Math.ceil(t));G.prototype.translate.apply(a);a.points.forEach(function(e){var h=
E(e.yBottom,l),r=999+Math.abs(h),y=u,A=e.plotX||0;r=d(e.plotY,-r,f.len+r);A+=p;var D=t,B=Math.min(r,h),z=Math.max(r,h)-B;if(q&&Math.abs(z)<q){z=q;var C=!f.reversed&&!e.negative||f.reversed&&e.negative;n(m)&&n(x)&&e.y===m&&x<=m&&(f.min||0)<m&&(w!==x||(f.max||0)<=m)&&(C=!C);B=Math.abs(B-l)>q?h-q:l-(C?q:0)}k(e.options.pointWidth)&&(y=D=Math.ceil(e.options.pointWidth),A-=Math.round((y-u)/2));b.centerInCategory&&(A=a.adjustForMissingColumns(A,y,e,v));e.barX=A;e.pointWidth=y;e.tooltipPos=c.inverted?[d(f.len+
f.pos-c.plotLeft-r,f.pos-c.plotLeft,f.len+f.pos-c.plotLeft),g.len+g.pos-c.plotTop-A-D/2,z]:[g.left-c.plotLeft+A+D/2,d(r+f.pos-c.plotTop,f.pos-c.plotTop,f.len+f.pos-c.plotTop),z];e.shapeType=a.pointClass.prototype.shapeType||"rect";e.shapeArgs=a.crispCol.apply(a,e.isNull?[A,l,D,0]:[A,B,D,z])})};b.prototype.drawGraph=function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")};b.prototype.pointAttribs=function(a,c){var b=this.options,d=this.pointAttrToOptions||{};var e=d.stroke||
"borderColor";var h=d["stroke-width"]||"borderWidth",g=a&&a.color||this.color,f=a&&a[e]||b[e]||g,k=a&&a[h]||b[h]||this[h]||0;d=a&&a.options.dashStyle||b.dashStyle;var m=E(a&&a.opacity,b.opacity,1);if(a&&this.zones.length){var l=a.getZone();g=a.options.color||l&&(l.color||a.nonZonedColor)||this.color;l&&(f=l.borderColor||f,d=l.dashStyle||d,k=l.borderWidth||k)}c&&a&&(a=J(b.states[c],a.options.states&&a.options.states[c]||{}),c=a.brightness,g=a.color||"undefined"!==typeof c&&v(g).brighten(a.brightness).get()||
g,f=a[e]||f,k=a[h]||k,d=a.dashStyle||d,m=E(a.opacity,m));e={fill:g,stroke:f,"stroke-width":k,opacity:m};d&&(e.dashstyle=d);return e};b.prototype.drawPoints=function(){var a=this,c=this.chart,b=a.options,d=c.renderer,e=b.animationLimit||250,g;a.points.forEach(function(h){var f=h.graphic,k=!!f,m=f&&c.pointCount<e?"animate":"attr";if(n(h.plotY)&&null!==h.y){g=h.shapeArgs;f&&h.hasNewShapeType()&&(f=f.destroy());a.enabledDataSorting&&(h.startXPos=a.xAxis.reversed?-(g?g.width||0:0):a.xAxis.width);f||(h.graphic=
f=d[h.shapeType](g).add(h.group||a.group))&&a.enabledDataSorting&&c.hasRendered&&c.pointCount<e&&(f.attr({x:h.startXPos}),k=!0,m="animate");if(f&&k)f[m](J(g));if(b.borderRadius)f[m]({r:b.borderRadius});c.styledMode||f[m](a.pointAttribs(h,h.selected&&"select")).shadow(!1!==h.allowShadow&&b.shadow,null,b.stacking&&!b.borderRadius);f&&(f.addClass(h.getClassName(),!0),f.attr({visibility:h.visible?"inherit":"hidden"}))}else f&&(h.graphic=f.destroy())})};b.prototype.drawTracker=function(){var a=this,c=
a.chart,b=c.pointer,d=function(a){var c=b.getPointFromEvent(a);"undefined"!==typeof c&&(b.isDirectTouch=!0,c.onMouseOver(a))},e;a.points.forEach(function(a){e=u(a.dataLabels)?a.dataLabels:a.dataLabel?[a.dataLabel]:[];a.graphic&&(a.graphic.element.point=a);e.forEach(function(c){c.div?c.div.point=a:c.element.point=a})});a._hasTracking||(a.trackerGroups.forEach(function(e){if(a[e]){a[e].addClass("highcharts-tracker").on("mouseover",d).on("mouseout",function(a){b.onTrackerMouseOut(a)});if(f)a[e].on("touchstart",
d);!c.styledMode&&a.options.cursor&&a[e].css(q).css({cursor:a.options.cursor})}}),a._hasTracking=!0);D(this,"afterDrawTracker")};b.prototype.remove=function(){var a=this,c=a.chart;c.hasRendered&&c.series.forEach(function(c){c.type===a.type&&(c.isDirty=!0)});G.prototype.remove.apply(a,arguments)};b.defaultOptions=J(G.defaultOptions,{borderRadius:0,centerInCategory:!1,groupPadding:.2,marker:null,pointPadding:.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{halo:!1,brightness:.1},
select:{color:H.neutralColor20,borderColor:H.neutralColor100}},dataLabels:{align:void 0,verticalAlign:void 0,y:void 0},startFromThreshold:!0,stickyTracking:!1,tooltip:{distance:6},threshold:0,borderColor:H.backgroundColor});return b}(G);l(B.prototype,{cropShoulder:0,directTouch:!0,drawLegendSymbol:z.drawRectangle,getSymbol:e,negStacks:!0,trackerGroups:["group","dataLabelsGroup"]});C.registerSeriesType("column",B);"";"";return B});O(e,"Series/Bar/BarSeries.js",[e["Series/Column/ColumnSeries.js"],e["Core/Series/SeriesRegistry.js"],
e["Core/Utilities.js"]],function(e,b,I){var D=this&&this.__extends||function(){var b=function(e,x){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var f in e)e.hasOwnProperty(f)&&(b[f]=e[f])};return b(e,x)};return function(e,x){function w(){this.constructor=e}b(e,x);e.prototype=null===x?Object.create(x):(w.prototype=x.prototype,new w)}}(),H=I.extend,G=I.merge;I=function(b){function B(){var e=null!==b&&b.apply(this,arguments)||this;e.data=void 0;
e.options=void 0;e.points=void 0;return e}D(B,b);B.defaultOptions=G(e.defaultOptions,{});return B}(e);H(I.prototype,{inverted:!0});b.registerSeriesType("bar",I);"";return I});O(e,"Series/Scatter/ScatterSeries.js",[e["Series/Column/ColumnSeries.js"],e["Series/Line/LineSeries.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z){var D=this&&this.__extends||function(){var b=function(e,v){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,d){b.__proto__=d}||
function(b,d){for(var e in d)d.hasOwnProperty(e)&&(b[e]=d[e])};return b(e,v)};return function(e,v){function f(){this.constructor=e}b(e,v);e.prototype=null===v?Object.create(v):(f.prototype=v.prototype,new f)}}(),G=z.addEvent,C=z.extend,B=z.merge;z=function(e){function w(){var b=null!==e&&e.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;return b}D(w,e);w.prototype.applyJitter=function(){var b=this,e=this.options.jitter,d=this.points.length;e&&this.points.forEach(function(f,
k){["x","y"].forEach(function(l,q){var v="plot"+l.toUpperCase();if(e[l]&&!f.isNull){var n=b[l+"Axis"];var w=e[l]*n.transA;if(n&&!n.isLog){var E=Math.max(0,f[v]-w);n=Math.min(n.len,f[v]+w);q=1E4*Math.sin(k+q*d);f[v]=E+(n-E)*(q-Math.floor(q));"x"===l&&(f.clientX=f.plotX)}}})})};w.prototype.drawGraph=function(){(this.options.lineWidth||0===this.options.lineWidth&&this.graph&&this.graph.strokeWidth())&&e.prototype.drawGraph.call(this)};w.defaultOptions=B(b.defaultOptions,{lineWidth:0,findNearestPointBy:"xy",
jitter:{x:0,y:0},marker:{enabled:!0},tooltip:{headerFormat:'<span style="color:{point.color}">\u25cf</span> <span style="font-size: 10px"> {series.name}</span><br/>',pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"}});return w}(b);C(z.prototype,{drawTracker:e.prototype.drawTracker,sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1});G(z,"afterTranslate",function(){this.applyJitter()});I.registerSeriesType("scatter",
z);"";return z});O(e,"Mixins/CenteredSeries.js",[e["Core/Globals.js"],e["Core/Series/Series.js"],e["Core/Utilities.js"]],function(e,b,I){var D=I.isNumber,H=I.pick,G=I.relativeLength,C=e.deg2rad;return e.CenteredSeriesMixin={getCenter:function(){var e=this.options,D=this.chart,w=2*(e.slicedOffset||0),v=D.plotWidth-2*w,f=D.plotHeight-2*w,d=e.center,q=Math.min(v,f),k=e.size,l=e.innerSize||0;"string"===typeof k&&(k=parseFloat(k));"string"===typeof l&&(l=parseFloat(l));e=[H(d[0],"50%"),H(d[1],"50%"),H(k&&
0>k?void 0:e.size,"100%"),H(l&&0>l?void 0:e.innerSize||0,"0%")];!D.angular||this instanceof b||(e[3]=0);for(d=0;4>d;++d)k=e[d],D=2>d||2===d&&/%$/.test(k),e[d]=G(k,[v,f,q,e[2]][d])+(D?w:0);e[3]>e[2]&&(e[3]=e[2]);return e},getStartAndEndRadians:function(b,e){b=D(b)?b:0;e=D(e)&&e>b&&360>e-b?e:b+360;return{start:C*(b+-90),end:C*(e+-90)}}}});O(e,"Series/Pie/PiePoint.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/Series/Point.js"],e["Core/Utilities.js"]],function(e,b,I){var D=this&&this.__extends||
function(){var b=function(e,d){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,d){b.__proto__=d}||function(b,d){for(var e in d)d.hasOwnProperty(e)&&(b[e]=d[e])};return b(e,d)};return function(e,d){function f(){this.constructor=e}b(e,d);e.prototype=null===d?Object.create(d):(f.prototype=d.prototype,new f)}}(),H=e.setAnimation,G=I.addEvent,C=I.defined;e=I.extend;var B=I.isNumber,x=I.pick,w=I.relativeLength;I=function(e){function f(){var b=null!==e&&e.apply(this,arguments)||this;
b.labelDistance=void 0;b.options=void 0;b.series=void 0;return b}D(f,e);f.prototype.getConnectorPath=function(){var b=this.labelPosition,e=this.series.options.dataLabels,f=e.connectorShape,l=this.connectorShapes;l[f]&&(f=l[f]);return f.call(this,{x:b.final.x,y:b.final.y,alignment:b.alignment},b.connectorPosition,e)};f.prototype.getTranslate=function(){return this.sliced?this.slicedTranslation:{translateX:0,translateY:0}};f.prototype.haloPath=function(b){var d=this.shapeArgs;return this.sliced||!this.visible?
[]:this.series.chart.renderer.symbols.arc(d.x,d.y,d.r+b,d.r+b,{innerR:d.r-1,start:d.start,end:d.end})};f.prototype.init=function(){b.prototype.init.apply(this,arguments);var d=this;d.name=x(d.name,"Slice");var e=function(b){d.slice("select"===b.type)};G(d,"select",e);G(d,"unselect",e);return d};f.prototype.isValid=function(){return B(this.y)&&0<=this.y};f.prototype.setVisible=function(b,e){var d=this,f=d.series,q=f.chart,v=f.options.ignoreHiddenPoint;e=x(e,v);b!==d.visible&&(d.visible=d.options.visible=
b="undefined"===typeof b?!d.visible:b,f.options.data[f.data.indexOf(d)]=d.options,["graphic","dataLabel","connector","shadowGroup"].forEach(function(e){if(d[e])d[e][b?"show":"hide"](b)}),d.legendItem&&q.legend.colorizeItem(d,b),b||"hover"!==d.state||d.setState(""),v&&(f.isDirty=!0),e&&q.redraw())};f.prototype.slice=function(b,e,f){var d=this.series;H(f,d.chart);x(e,!0);this.sliced=this.options.sliced=C(b)?b:!this.sliced;d.options.data[d.data.indexOf(this)]=this.options;this.graphic&&this.graphic.animate(this.getTranslate());
this.shadowGroup&&this.shadowGroup.animate(this.getTranslate())};return f}(b);e(I.prototype,{connectorShapes:{fixedOffset:function(b,e,d){var f=e.breakAt;e=e.touchingSliceAt;return[["M",b.x,b.y],d.softConnector?["C",b.x+("left"===b.alignment?-5:5),b.y,2*f.x-e.x,2*f.y-e.y,f.x,f.y]:["L",f.x,f.y],["L",e.x,e.y]]},straight:function(b,e){e=e.touchingSliceAt;return[["M",b.x,b.y],["L",e.x,e.y]]},crookedLine:function(b,e,d){e=e.touchingSliceAt;var f=this.series,k=f.center[0],l=f.chart.plotWidth,v=f.chart.plotLeft;
f=b.alignment;var u=this.shapeArgs.r;d=w(d.crookDistance,1);l="left"===f?k+u+(l+v-k-u)*(1-d):v+(k-u)*d;d=["L",l,b.y];k=!0;if("left"===f?l>b.x||l<e.x:l<b.x||l>e.x)k=!1;b=[["M",b.x,b.y]];k&&b.push(d);b.push(["L",e.x,e.y]);return b}}});return I});O(e,"Series/Pie/PieSeries.js",[e["Mixins/CenteredSeries.js"],e["Series/Column/ColumnSeries.js"],e["Core/Globals.js"],e["Mixins/LegendSymbol.js"],e["Core/Color/Palette.js"],e["Series/Pie/PiePoint.js"],e["Core/Series/Series.js"],e["Core/Series/SeriesRegistry.js"],
e["Core/Renderer/SVG/SVGRenderer.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C,B,x,w){var v=this&&this.__extends||function(){var b=function(d,e){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,c){b.__proto__=c}||function(b,c){for(var d in c)c.hasOwnProperty(d)&&(b[d]=c[d])};return b(d,e)};return function(d,e){function f(){this.constructor=d}b(d,e);d.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)}}(),f=e.getStartAndEndRadians;I=I.noop;var d=w.clamp,q=
w.extend,k=w.fireEvent,l=w.merge,D=w.pick,u=w.relativeLength;w=function(b){function e(){var d=null!==b&&b.apply(this,arguments)||this;d.center=void 0;d.data=void 0;d.maxLabelDistance=void 0;d.options=void 0;d.points=void 0;return d}v(e,b);e.prototype.animate=function(b){var d=this,c=d.points,e=d.startAngleRad;b||c.forEach(function(a){var c=a.graphic,b=a.shapeArgs;c&&b&&(c.attr({r:D(a.startR,d.center&&d.center[3]/2),start:e,end:e}),c.animate({r:b.r,start:b.start,end:b.end},d.options.animation))})};
e.prototype.drawEmpty=function(){var b=this.startAngleRad,d=this.endAngleRad,c=this.options;if(0===this.total&&this.center){var e=this.center[0];var a=this.center[1];this.graph||(this.graph=this.chart.renderer.arc(e,a,this.center[1]/2,0,b,d).addClass("highcharts-empty-series").add(this.group));this.graph.attr({d:x.prototype.symbols.arc(e,a,this.center[2]/2,0,{start:b,end:d,innerR:this.center[3]/2})});this.chart.styledMode||this.graph.attr({"stroke-width":c.borderWidth,fill:c.fillColor||"none",stroke:c.color||
H.neutralColor20})}else this.graph&&(this.graph=this.graph.destroy())};e.prototype.drawPoints=function(){var b=this.chart.renderer;this.points.forEach(function(d){d.graphic&&d.hasNewShapeType()&&(d.graphic=d.graphic.destroy());d.graphic||(d.graphic=b[d.shapeType](d.shapeArgs).add(d.series.group),d.delayedRendering=!0)})};e.prototype.generatePoints=function(){b.prototype.generatePoints.call(this);this.updateTotals()};e.prototype.getX=function(b,e,c){var g=this.center,a=this.radii?this.radii[c.index]||
0:g[2]/2;b=Math.asin(d((b-g[1])/(a+c.labelDistance),-1,1));return g[0]+(e?-1:1)*Math.cos(b)*(a+c.labelDistance)+(0<c.labelDistance?(e?-1:1)*this.options.dataLabels.padding:0)};e.prototype.hasData=function(){return!!this.processedXData.length};e.prototype.redrawPoints=function(){var b=this,d=b.chart,c=d.renderer,e,a,h,f,k=b.options.shadow;this.drawEmpty();!k||b.shadowGroup||d.styledMode||(b.shadowGroup=c.g("shadow").attr({zIndex:-1}).add(b.group));b.points.forEach(function(g){var m={};a=g.graphic;
if(!g.isNull&&a){var r=void 0;f=g.shapeArgs;e=g.getTranslate();d.styledMode||(r=g.shadowGroup,k&&!r&&(r=g.shadowGroup=c.g("shadow").add(b.shadowGroup)),r&&r.attr(e),h=b.pointAttribs(g,g.selected&&"select"));g.delayedRendering?(a.setRadialReference(b.center).attr(f).attr(e),d.styledMode||a.attr(h).attr({"stroke-linejoin":"round"}).shadow(k,r),g.delayedRendering=!1):(a.setRadialReference(b.center),d.styledMode||l(!0,m,h),l(!0,m,f,e),a.animate(m));a.attr({visibility:g.visible?"inherit":"hidden"});a.addClass(g.getClassName(),
!0)}else a&&(g.graphic=a.destroy())})};e.prototype.sortByAngle=function(b,d){b.sort(function(c,b){return"undefined"!==typeof c.angle&&(b.angle-c.angle)*d})};e.prototype.translate=function(b){this.generatePoints();var d=0,c=this.options,e=c.slicedOffset,a=e+(c.borderWidth||0),h=f(c.startAngle,c.endAngle),l=this.startAngleRad=h.start;h=(this.endAngleRad=h.end)-l;var n=this.points,q=c.dataLabels.distance;c=c.ignoreHiddenPoint;var v,w=n.length;b||(this.center=b=this.getCenter());for(v=0;v<w;v++){var x=
n[v];var E=l+d*h;!x.isValid()||c&&!x.visible||(d+=x.percentage/100);var z=l+d*h;var B={x:b[0],y:b[1],r:b[2]/2,innerR:b[3]/2,start:Math.round(1E3*E)/1E3,end:Math.round(1E3*z)/1E3};x.shapeType="arc";x.shapeArgs=B;x.labelDistance=D(x.options.dataLabels&&x.options.dataLabels.distance,q);x.labelDistance=u(x.labelDistance,B.r);this.maxLabelDistance=Math.max(this.maxLabelDistance||0,x.labelDistance);z=(z+E)/2;z>1.5*Math.PI?z-=2*Math.PI:z<-Math.PI/2&&(z+=2*Math.PI);x.slicedTranslation={translateX:Math.round(Math.cos(z)*
e),translateY:Math.round(Math.sin(z)*e)};B=Math.cos(z)*b[2]/2;var t=Math.sin(z)*b[2]/2;x.tooltipPos=[b[0]+.7*B,b[1]+.7*t];x.half=z<-Math.PI/2||z>Math.PI/2?1:0;x.angle=z;E=Math.min(a,x.labelDistance/5);x.labelPosition={natural:{x:b[0]+B+Math.cos(z)*x.labelDistance,y:b[1]+t+Math.sin(z)*x.labelDistance},"final":{},alignment:0>x.labelDistance?"center":x.half?"right":"left",connectorPosition:{breakAt:{x:b[0]+B+Math.cos(z)*E,y:b[1]+t+Math.sin(z)*E},touchingSliceAt:{x:b[0]+B,y:b[1]+t}}}}k(this,"afterTranslate")};
e.prototype.updateTotals=function(){var b,d=0,c=this.points,e=c.length,a=this.options.ignoreHiddenPoint;for(b=0;b<e;b++){var h=c[b];!h.isValid()||a&&!h.visible||(d+=h.y)}this.total=d;for(b=0;b<e;b++)h=c[b],h.percentage=0<d&&(h.visible||!a)?h.y/d*100:0,h.total=d};e.defaultOptions=l(C.defaultOptions,{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{allowOverlap:!0,connectorPadding:5,connectorShape:"fixedOffset",crookDistance:"70%",distance:30,enabled:!0,formatter:function(){return this.point.isNull?
void 0:this.point.name},softConnector:!0,x:0},fillColor:void 0,ignoreHiddenPoint:!0,inactiveOtherPoints:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:H.backgroundColor,borderWidth:1,lineWidth:void 0,states:{hover:{brightness:.1}}});return e}(C);q(w.prototype,{axisTypes:[],directTouch:!0,drawGraph:void 0,drawLegendSymbol:z.drawRectangle,drawTracker:b.prototype.drawTracker,getCenter:e.getCenter,getSymbol:I,isCartesian:!1,
noSharedTooltip:!0,pointAttribs:b.prototype.pointAttribs,pointClass:G,requireSorting:!1,searchPoint:I,trackerGroups:["group","dataLabelsGroup"]});B.registerSeriesType("pie",w);"";return w});O(e,"Core/Series/DataLabels.js",[e["Core/Animation/AnimationUtilities.js"],e["Core/FormatUtilities.js"],e["Core/Globals.js"],e["Core/Color/Palette.js"],e["Core/Series/Series.js"],e["Core/Series/SeriesRegistry.js"],e["Core/Utilities.js"]],function(e,b,I,z,H,G,C){var D=e.getDeferredAnimation,x=b.format;e=I.noop;
G=G.seriesTypes;var w=C.arrayMax,v=C.clamp,f=C.defined,d=C.extend,q=C.fireEvent,k=C.isArray,l=C.merge,N=C.objectEach,u=C.pick,n=C.relativeLength,J=C.splat,E=C.stableSort;"";I.distribute=function(b,c,d){function a(a,c){return a.target-c.target}var e,g=!0,f=b,k=[];var l=0;var m=f.reducedLen||c;for(e=b.length;e--;)l+=b[e].size;if(l>m){E(b,function(a,c){return(c.rank||0)-(a.rank||0)});for(l=e=0;l<=m;)l+=b[e].size,e++;k=b.splice(e-1,b.length)}E(b,a);for(b=b.map(function(a){return{size:a.size,targets:[a.target],
align:u(a.align,.5)}});g;){for(e=b.length;e--;)g=b[e],l=(Math.min.apply(0,g.targets)+Math.max.apply(0,g.targets))/2,g.pos=v(l-g.size*g.align,0,c-g.size);e=b.length;for(g=!1;e--;)0<e&&b[e-1].pos+b[e-1].size>b[e].pos&&(b[e-1].size+=b[e].size,b[e-1].targets=b[e-1].targets.concat(b[e].targets),b[e-1].align=.5,b[e-1].pos+b[e-1].size>c&&(b[e-1].pos=c-b[e-1].size),b.splice(e,1),g=!0)}f.push.apply(f,k);e=0;b.some(function(a){var b=0;if(a.targets.some(function(){f[e].pos=a.pos+b;if("undefined"!==typeof d&&
Math.abs(f[e].pos-f[e].target)>d)return f.slice(0,e+1).forEach(function(a){delete a.pos}),f.reducedLen=(f.reducedLen||c)-.1*c,f.reducedLen>.1*c&&I.distribute(f,c,d),!0;b+=f[e].size;e++}))return!0});E(f,a)};H.prototype.drawDataLabels=function(){function b(a,c){var b=c.filter;return b?(c=b.operator,a=a[b.property],b=b.value,">"===c&&a>b||"<"===c&&a<b||">="===c&&a>=b||"<="===c&&a<=b||"=="===c&&a==b||"==="===c&&a===b?!0:!1):!0}function c(a,c){var b=[],d;if(k(a)&&!k(c))b=a.map(function(a){return l(a,c)});
else if(k(c)&&!k(a))b=c.map(function(c){return l(a,c)});else if(k(a)||k(c))for(d=Math.max(a.length,c.length);d--;)b[d]=l(a[d],c[d]);else b=l(a,c);return b}var d=this,a=d.chart,e=d.options,r=e.dataLabels,n=d.points,v,w=d.hasRendered||0,E=r.animation;E=r.defer?D(a,E,d):{defer:0,duration:0};var B=a.renderer;r=c(c(a.options.plotOptions&&a.options.plotOptions.series&&a.options.plotOptions.series.dataLabels,a.options.plotOptions&&a.options.plotOptions[d.type]&&a.options.plotOptions[d.type].dataLabels),
r);q(this,"drawDataLabels");if(k(r)||r.enabled||d._hasPointLabels){var C=d.plotGroup("dataLabelsGroup","data-labels",w?"inherit":"hidden",r.zIndex||6);C.attr({opacity:+w});!w&&(w=d.dataLabelsGroup)&&(d.visible&&C.show(!0),w[e.animation?"animate":"attr"]({opacity:1},E));n.forEach(function(g){v=J(c(r,g.dlOptions||g.options&&g.options.dataLabels));v.forEach(function(c,h){var k=c.enabled&&(!g.isNull||g.dataLabelOnNull)&&b(g,c),l=g.dataLabels?g.dataLabels[h]:g.dataLabel,m=g.connectors?g.connectors[h]:
g.connector,r=u(c.distance,g.labelDistance),n=!l;if(k){var q=g.getLabelConfig();var t=u(c[g.formatPrefix+"Format"],c.format);q=f(t)?x(t,q,a):(c[g.formatPrefix+"Formatter"]||c.formatter).call(q,c);t=c.style;var v=c.rotation;a.styledMode||(t.color=u(c.color,t.color,d.color,z.neutralColor100),"contrast"===t.color?(g.contrastColor=B.getContrast(g.color||d.color),t.color=!f(r)&&c.inside||0>r||e.stacking?g.contrastColor:z.neutralColor100):delete g.contrastColor,e.cursor&&(t.cursor=e.cursor));var w={r:c.borderRadius||
0,rotation:v,padding:c.padding,zIndex:1};a.styledMode||(w.fill=c.backgroundColor,w.stroke=c.borderColor,w["stroke-width"]=c.borderWidth);N(w,function(a,c){"undefined"===typeof a&&delete w[c]})}!l||k&&f(q)?k&&f(q)&&(l?w.text=q:(g.dataLabels=g.dataLabels||[],l=g.dataLabels[h]=v?B.text(q,0,-9999,c.useHTML).addClass("highcharts-data-label"):B.label(q,0,-9999,c.shape,null,null,c.useHTML,null,"data-label"),h||(g.dataLabel=l),l.addClass(" highcharts-data-label-color-"+g.colorIndex+" "+(c.className||"")+
(c.useHTML?" highcharts-tracker":""))),l.options=c,l.attr(w),a.styledMode||l.css(t).shadow(c.shadow),l.added||l.add(C),c.textPath&&!c.useHTML&&(l.setTextPath(g.getDataLabelPath&&g.getDataLabelPath(l)||g.graphic,c.textPath),g.dataLabelPath&&!c.textPath.enabled&&(g.dataLabelPath=g.dataLabelPath.destroy())),d.alignDataLabel(g,l,c,null,n)):(g.dataLabel=g.dataLabel&&g.dataLabel.destroy(),g.dataLabels&&(1===g.dataLabels.length?delete g.dataLabels:delete g.dataLabels[h]),h||delete g.dataLabel,m&&(g.connector=
g.connector.destroy(),g.connectors&&(1===g.connectors.length?delete g.connectors:delete g.connectors[h])))})})}q(this,"afterDrawDataLabels")};H.prototype.alignDataLabel=function(b,c,e,a,f){var g=this,h=this.chart,k=this.isCartesian&&h.inverted,l=this.enabledDataSorting,m=u(b.dlBox&&b.dlBox.centerX,b.plotX,-9999),n=u(b.plotY,-9999),q=c.getBBox(),v=e.rotation,w=e.align,t=h.isInsidePlot(m,Math.round(n),{inverted:k,paneCoordinates:!0,series:g}),p="justify"===u(e.overflow,l?"none":"justify"),D=this.visible&&
!1!==b.visible&&(b.series.forceDL||l&&!p||t||u(e.inside,!!this.options.stacking)&&a&&h.isInsidePlot(m,k?a.x+1:a.y+a.height-1,{inverted:k,paneCoordinates:!0,series:g}));var x=function(a){l&&g.xAxis&&!p&&g.setDataLabelStartPos(b,c,f,t,a)};if(D){var z=h.renderer.fontMetrics(h.styledMode?void 0:e.style.fontSize,c).b;a=d({x:k?this.yAxis.len-n:m,y:Math.round(k?this.xAxis.len-m:n),width:0,height:0},a);d(e,{width:q.width,height:q.height});v?(p=!1,m=h.renderer.rotCorr(z,v),m={x:a.x+(e.x||0)+a.width/2+m.x,
y:a.y+(e.y||0)+{top:0,middle:.5,bottom:1}[e.verticalAlign]*a.height},x(m),c[f?"attr":"animate"](m).attr({align:w}),x=(v+720)%360,x=180<x&&360>x,"left"===w?m.y-=x?q.height:0:"center"===w?(m.x-=q.width/2,m.y-=q.height/2):"right"===w&&(m.x-=q.width,m.y-=x?0:q.height),c.placed=!0,c.alignAttr=m):(x(a),c.align(e,void 0,a),m=c.alignAttr);p&&0<=a.height?this.justifyDataLabel(c,e,m,q,a,f):u(e.crop,!0)&&(D=h.isInsidePlot(m.x,m.y,{paneCoordinates:!0,series:g})&&h.isInsidePlot(m.x+q.width,m.y+q.height,{paneCoordinates:!0,
series:g}));if(e.shape&&!v)c[f?"attr":"animate"]({anchorX:k?h.plotWidth-b.plotY:b.plotX,anchorY:k?h.plotHeight-b.plotX:b.plotY})}f&&l&&(c.placed=!1);D||l&&!p||(c.hide(!0),c.placed=!1)};H.prototype.setDataLabelStartPos=function(b,c,d,a,e){var g=this.chart,f=g.inverted,h=this.xAxis,k=h.reversed,l=f?c.height/2:c.width/2;b=(b=b.pointWidth)?b/2:0;h=f?e.x:k?-l-b:h.width-l+b;e=f?k?this.yAxis.height-l+b:-l-b:e.y;c.startXPos=h;c.startYPos=e;a?"hidden"===c.visibility&&(c.show(),c.attr({opacity:0}).animate({opacity:1})):
c.attr({opacity:1}).animate({opacity:0},void 0,c.hide);g.hasRendered&&(d&&c.attr({x:c.startXPos,y:c.startYPos}),c.placed=!0)};H.prototype.justifyDataLabel=function(b,c,d,a,e,f){var g=this.chart,h=c.align,k=c.verticalAlign,l=b.box?0:b.padding||0,m=c.x;m=void 0===m?0:m;var n=c.y;var r=void 0===n?0:n;n=(d.x||0)+l;if(0>n){"right"===h&&0<=m?(c.align="left",c.inside=!0):m-=n;var q=!0}n=(d.x||0)+a.width-l;n>g.plotWidth&&("left"===h&&0>=m?(c.align="right",c.inside=!0):m+=g.plotWidth-n,q=!0);n=d.y+l;0>n&&
("bottom"===k&&0<=r?(c.verticalAlign="top",c.inside=!0):r-=n,q=!0);n=(d.y||0)+a.height-l;n>g.plotHeight&&("top"===k&&0>=r?(c.verticalAlign="bottom",c.inside=!0):r+=g.plotHeight-n,q=!0);q&&(c.x=m,c.y=r,b.placed=!f,b.align(c,void 0,e));return q};G.pie&&(G.pie.prototype.dataLabelPositioners={radialDistributionY:function(b){return b.top+b.distributeBox.pos},radialDistributionX:function(b,c,d,a){return b.getX(d<c.top+2||d>c.bottom-2?a:d,c.half,c)},justify:function(b,c,d){return d[0]+(b.half?-1:1)*(c+b.labelDistance)},
alignToPlotEdges:function(b,c,d,a){b=b.getBBox().width;return c?b+a:d-b-a},alignToConnectors:function(b,c,d,a){var e=0,g;b.forEach(function(a){g=a.dataLabel.getBBox().width;g>e&&(e=g)});return c?e+a:d-e-a}},G.pie.prototype.drawDataLabels=function(){var b=this,c=b.data,d,a=b.chart,e=b.options.dataLabels||{},k=e.connectorPadding,n,q=a.plotWidth,v=a.plotHeight,x=a.plotLeft,D=Math.round(a.chartWidth/3),E,B=b.center,C=B[2]/2,t=B[1],p,G,J,N,F=[[],[]],O,K,T,X,U=[0,0,0,0],W=b.dataLabelPositioners,Y;b.visible&&
(e.enabled||b._hasPointLabels)&&(c.forEach(function(a){a.dataLabel&&a.visible&&a.dataLabel.shortened&&(a.dataLabel.attr({width:"auto"}).css({width:"auto",textOverflow:"clip"}),a.dataLabel.shortened=!1)}),H.prototype.drawDataLabels.apply(b),c.forEach(function(a){a.dataLabel&&(a.visible?(F[a.half].push(a),a.dataLabel._pos=null,!f(e.style.width)&&!f(a.options.dataLabels&&a.options.dataLabels.style&&a.options.dataLabels.style.width)&&a.dataLabel.getBBox().width>D&&(a.dataLabel.css({width:Math.round(.7*
D)+"px"}),a.dataLabel.shortened=!0)):(a.dataLabel=a.dataLabel.destroy(),a.dataLabels&&1===a.dataLabels.length&&delete a.dataLabels))}),F.forEach(function(c,g){var h=c.length,l=[],m;if(h){b.sortByAngle(c,g-.5);if(0<b.maxLabelDistance){var n=Math.max(0,t-C-b.maxLabelDistance);var r=Math.min(t+C+b.maxLabelDistance,a.plotHeight);c.forEach(function(b){0<b.labelDistance&&b.dataLabel&&(b.top=Math.max(0,t-C-b.labelDistance),b.bottom=Math.min(t+C+b.labelDistance,a.plotHeight),m=b.dataLabel.getBBox().height||
21,b.distributeBox={target:b.labelPosition.natural.y-b.top+m/2,size:m,rank:b.y},l.push(b.distributeBox))});n=r+m-n;I.distribute(l,n,n/5)}for(X=0;X<h;X++){d=c[X];J=d.labelPosition;p=d.dataLabel;T=!1===d.visible?"hidden":"inherit";K=n=J.natural.y;l&&f(d.distributeBox)&&("undefined"===typeof d.distributeBox.pos?T="hidden":(N=d.distributeBox.size,K=W.radialDistributionY(d)));delete d.positionIndex;if(e.justify)O=W.justify(d,C,B);else switch(e.alignTo){case "connectors":O=W.alignToConnectors(c,g,q,x);
break;case "plotEdges":O=W.alignToPlotEdges(p,g,q,x);break;default:O=W.radialDistributionX(b,d,K,n)}p._attr={visibility:T,align:J.alignment};Y=d.options.dataLabels||{};p._pos={x:O+u(Y.x,e.x)+({left:k,right:-k}[J.alignment]||0),y:K+u(Y.y,e.y)-10};J.final.x=O;J.final.y=K;u(e.crop,!0)&&(G=p.getBBox().width,n=null,O-G<k&&1===g?(n=Math.round(G-O+k),U[3]=Math.max(n,U[3])):O+G>q-k&&0===g&&(n=Math.round(O+G-q+k),U[1]=Math.max(n,U[1])),0>K-N/2?U[0]=Math.max(Math.round(-K+N/2),U[0]):K+N/2>v&&(U[2]=Math.max(Math.round(K+
N/2-v),U[2])),p.sideOverflow=n)}}}),0===w(U)||this.verifyDataLabelOverflow(U))&&(this.placeDataLabels(),this.points.forEach(function(c){Y=l(e,c.options.dataLabels);if(n=u(Y.connectorWidth,1)){var d;E=c.connector;if((p=c.dataLabel)&&p._pos&&c.visible&&0<c.labelDistance){T=p._attr.visibility;if(d=!E)c.connector=E=a.renderer.path().addClass("highcharts-data-label-connector  highcharts-color-"+c.colorIndex+(c.className?" "+c.className:"")).add(b.dataLabelsGroup),a.styledMode||E.attr({"stroke-width":n,
stroke:Y.connectorColor||c.color||z.neutralColor60});E[d?"attr":"animate"]({d:c.getConnectorPath()});E.attr("visibility",T)}else E&&(c.connector=E.destroy())}}))},G.pie.prototype.placeDataLabels=function(){this.points.forEach(function(b){var c=b.dataLabel,d;c&&b.visible&&((d=c._pos)?(c.sideOverflow&&(c._attr.width=Math.max(c.getBBox().width-c.sideOverflow,0),c.css({width:c._attr.width+"px",textOverflow:(this.options.dataLabels.style||{}).textOverflow||"ellipsis"}),c.shortened=!0),c.attr(c._attr),
c[c.moved?"animate":"attr"](d),c.moved=!0):c&&c.attr({y:-9999}));delete b.distributeBox},this)},G.pie.prototype.alignDataLabel=e,G.pie.prototype.verifyDataLabelOverflow=function(b){var c=this.center,d=this.options,a=d.center,e=d.minSize||80,f=null!==d.size;if(!f){if(null!==a[0])var k=Math.max(c[2]-Math.max(b[1],b[3]),e);else k=Math.max(c[2]-b[1]-b[3],e),c[0]+=(b[3]-b[1])/2;null!==a[1]?k=v(k,e,c[2]-Math.max(b[0],b[2])):(k=v(k,e,c[2]-b[0]-b[2]),c[1]+=(b[0]-b[2])/2);k<c[2]?(c[2]=k,c[3]=Math.min(n(d.innerSize||
0,k),k),this.translate(c),this.drawDataLabels&&this.drawDataLabels()):f=!0}return f});G.column&&(G.column.prototype.alignDataLabel=function(b,c,d,a,e){var f=this.chart.inverted,g=b.series,h=b.dlBox||b.shapeArgs,k=u(b.below,b.plotY>u(this.translatedThreshold,g.yAxis.len)),m=u(d.inside,!!this.options.stacking);h&&(a=l(h),0>a.y&&(a.height+=a.y,a.y=0),h=a.y+a.height-g.yAxis.len,0<h&&h<a.height&&(a.height-=h),f&&(a={x:g.yAxis.len-a.y-a.height,y:g.xAxis.len-a.x-a.width,width:a.height,height:a.width}),m||
(f?(a.x+=k?0:a.width,a.width=0):(a.y+=k?a.height:0,a.height=0)));d.align=u(d.align,!f||m?"center":k?"right":"left");d.verticalAlign=u(d.verticalAlign,f||m?"middle":k?"top":"bottom");H.prototype.alignDataLabel.call(this,b,c,d,a,e);d.inside&&b.contrastColor&&c.css({color:b.contrastColor})})});O(e,"Extensions/OverlappingDataLabels.js",[e["Core/Chart/Chart.js"],e["Core/Utilities.js"]],function(e,b){function D(b,e){var f=!1;if(b){var d=b.newOpacity;b.oldOpacity!==d&&(b.alignAttr&&b.placed?(b[d?"removeClass":
"addClass"]("highcharts-data-label-hidden"),f=!0,b.alignAttr.opacity=d,b[b.isOld?"animate":"attr"](b.alignAttr,null,function(){e.styledMode||b.css({pointerEvents:d?"auto":"none"});b.visibility=d?"inherit":"hidden"}),H(e,"afterHideOverlappingLabel")):b.attr({opacity:d}));b.isOld=!0}return f}var z=b.addEvent,H=b.fireEvent,G=b.isArray,C=b.isNumber,B=b.objectEach,x=b.pick;z(e,"render",function(){var b=this,e=[];(this.labelCollectors||[]).forEach(function(b){e=e.concat(b())});(this.yAxis||[]).forEach(function(b){b.stacking&&
b.options.stackLabels&&!b.options.stackLabels.allowOverlap&&B(b.stacking.stacks,function(b){B(b,function(b){e.push(b.label)})})});(this.series||[]).forEach(function(f){var d=f.options.dataLabels;f.visible&&(!1!==d.enabled||f._hasPointLabels)&&(d=function(d){return d.forEach(function(d){d.visible&&(G(d.dataLabels)?d.dataLabels:d.dataLabel?[d.dataLabel]:[]).forEach(function(f){var k=f.options;f.labelrank=x(k.labelrank,d.labelrank,d.shapeArgs&&d.shapeArgs.height);k.allowOverlap?(f.oldOpacity=f.opacity,
f.newOpacity=1,D(f,b)):e.push(f)})})},d(f.nodes||[]),d(f.points))});this.hideOverlappingLabels(e)});e.prototype.hideOverlappingLabels=function(b){var e=this,f=b.length,d=e.renderer,q,k,l,w=!1;var u=function(b){var e,c=b.box?0:b.padding||0,f=e=0,a;if(b&&(!b.alignAttr||b.placed)){var h=b.alignAttr||{x:b.attr("x"),y:b.attr("y")};var k=b.parentGroup;b.width||(e=b.getBBox(),b.width=e.width,b.height=e.height,e=d.fontMetrics(null,b.element).h);var l=b.width-2*c;(a={left:"0",center:"0.5",right:"1"}[b.alignValue])?
f=+a*l:C(b.x)&&Math.round(b.x)!==b.translateX&&(f=b.x-b.translateX);return{x:h.x+(k.translateX||0)+c-(f||0),y:h.y+(k.translateY||0)+c-e,width:b.width-2*c,height:b.height-2*c}}};for(k=0;k<f;k++)if(q=b[k])q.oldOpacity=q.opacity,q.newOpacity=1,q.absoluteBox=u(q);b.sort(function(b,d){return(d.labelrank||0)-(b.labelrank||0)});for(k=0;k<f;k++){var n=(u=b[k])&&u.absoluteBox;for(q=k+1;q<f;++q){var x=(l=b[q])&&l.absoluteBox;!n||!x||u===l||0===u.newOpacity||0===l.newOpacity||x.x>=n.x+n.width||x.x+x.width<=
n.x||x.y>=n.y+n.height||x.y+x.height<=n.y||((u.labelrank<l.labelrank?u:l).newOpacity=0)}}b.forEach(function(b){D(b,e)&&(w=!0)});w&&H(e,"afterHideAllOverlappingLabels")}});O(e,"Core/Responsive.js",[e["Core/Chart/Chart.js"],e["Core/Utilities.js"]],function(e,b){var D=b.find,z=b.isArray,H=b.isObject,G=b.merge,C=b.objectEach,B=b.pick,x=b.splat,w=b.uniqueKey;e.prototype.setResponsive=function(b,e){var d=this.options.responsive,f=[],k=this.currentResponsive;!e&&d&&d.rules&&d.rules.forEach(function(b){"undefined"===
typeof b._id&&(b._id=w());this.matchResponsiveRule(b,f)},this);e=G.apply(0,f.map(function(b){return D(d.rules,function(d){return d._id===b}).chartOptions}));e.isResponsiveOptions=!0;f=f.toString()||void 0;f!==(k&&k.ruleIds)&&(k&&this.update(k.undoOptions,b,!0),f?(k=this.currentOptions(e),k.isResponsiveOptions=!0,this.currentResponsive={ruleIds:f,mergedOptions:e,undoOptions:k},this.update(e,b,!0)):this.currentResponsive=void 0)};e.prototype.matchResponsiveRule=function(b,e){var d=b.condition;(d.callback||
function(){return this.chartWidth<=B(d.maxWidth,Number.MAX_VALUE)&&this.chartHeight<=B(d.maxHeight,Number.MAX_VALUE)&&this.chartWidth>=B(d.minWidth,0)&&this.chartHeight>=B(d.minHeight,0)}).call(this)&&e.push(b._id)};e.prototype.currentOptions=function(b){function e(b,f,q,u){var k;C(b,function(b,l){if(!u&&-1<d.collectionsWithUpdate.indexOf(l)&&f[l])for(b=x(b),q[l]=[],k=0;k<Math.max(b.length,f[l].length);k++)f[l][k]&&(void 0===b[k]?q[l][k]=f[l][k]:(q[l][k]={},e(b[k],f[l][k],q[l][k],u+1)));else H(b)?
(q[l]=z(b)?[]:{},e(b,f[l]||{},q[l],u+1)):q[l]="undefined"===typeof f[l]?null:f[l]})}var d=this,q={};e(b,this.options,q,0);return q}});O(e,"masters/highcharts.src.js",[e["Core/Globals.js"],e["Core/Utilities.js"],e["Core/Options.js"],e["Core/Animation/Fx.js"],e["Core/Animation/AnimationUtilities.js"],e["Core/Renderer/HTML/AST.js"],e["Core/FormatUtilities.js"],e["Core/Renderer/SVG/SVGElement.js"],e["Core/Series/Series.js"]],function(e,b,I,z,H,G,C,B,x){e.animate=H.animate;e.animObject=H.animObject;e.getDeferredAnimation=
H.getDeferredAnimation;e.setAnimation=H.setAnimation;e.stop=H.stop;e.timers=z.timers;e.AST=G;e.Fx=z;e.Series=x;e.SVGElement=B;e.dateFormat=C.dateFormat;e.format=C.format;e.numberFormat=C.numberFormat;e.defaultOptions=I.defaultOptions;e.getOptions=I.getOptions;e.time=I.defaultTime;e.setOptions=I.setOptions;e.addEvent=b.addEvent;e.arrayMax=b.arrayMax;e.arrayMin=b.arrayMin;e.attr=b.attr;e.clearTimeout=b.clearTimeout;e.correctFloat=b.correctFloat;e.createElement=b.createElement;e.css=b.css;e.defined=
b.defined;e.destroyObjectProperties=b.destroyObjectProperties;e.discardElement=b.discardElement;e.erase=b.erase;e.error=b.error;e.extend=b.extend;e.extendClass=b.extendClass;e.find=b.find;e.fireEvent=b.fireEvent;e.getMagnitude=b.getMagnitude;e.getStyle=b.getStyle;e.inArray=b.inArray;e.isArray=b.isArray;e.isClass=b.isClass;e.isDOMElement=b.isDOMElement;e.isFunction=b.isFunction;e.isNumber=b.isNumber;e.isObject=b.isObject;e.isString=b.isString;e.keys=b.keys;e.merge=b.merge;e.normalizeTickInterval=b.normalizeTickInterval;
e.objectEach=b.objectEach;e.offset=b.offset;e.pad=b.pad;e.pick=b.pick;e.pInt=b.pInt;e.relativeLength=b.relativeLength;e.removeEvent=b.removeEvent;e.splat=b.splat;e.stableSort=b.stableSort;e.syncTimeout=b.syncTimeout;e.timeUnits=b.timeUnits;e.uniqueKey=b.uniqueKey;e.useSerialIds=b.useSerialIds;e.wrap=b.wrap;return e});e["masters/highcharts.src.js"]._modules=e;return e["masters/highcharts.src.js"]});
//# sourceMappingURL=/assets/highcharts-9.1.0/highcharts.js-da62b941a2191f34dddb50066e5fff53a94feece02af8bdeb697a91bf08c0415.map
//!
;
/*
 Highcharts JS v9.1.0 (2021-05-03)

 Exporting module

 (c) 2010-2021 Torstein Honsi

 License: www.highcharts.com/license
*/
(function(c){"object"===typeof module&&module.exports?(c["default"]=c,module.exports=c):"function"===typeof define&&define.amd?define("highcharts/modules/exporting",["highcharts"],function(q){c(q);c.Highcharts=q;return c}):c("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(c){function q(c,m,h,k){c.hasOwnProperty(m)||(c[m]=k.apply(null,h))}c=c?c._modules:{};q(c,"Extensions/FullScreen.js",[c["Core/Chart/Chart.js"],c["Core/Globals.js"],c["Core/Renderer/HTML/AST.js"],c["Core/Utilities.js"]],
function(c,m,h,k){var n=k.addEvent;k=function(){function c(e){this.chart=e;this.isOpen=!1;e=e.renderTo;this.browserProps||("function"===typeof e.requestFullscreen?this.browserProps={fullscreenChange:"fullscreenchange",requestFullscreen:"requestFullscreen",exitFullscreen:"exitFullscreen"}:e.mozRequestFullScreen?this.browserProps={fullscreenChange:"mozfullscreenchange",requestFullscreen:"mozRequestFullScreen",exitFullscreen:"mozCancelFullScreen"}:e.webkitRequestFullScreen?this.browserProps={fullscreenChange:"webkitfullscreenchange",
requestFullscreen:"webkitRequestFullScreen",exitFullscreen:"webkitExitFullscreen"}:e.msRequestFullscreen&&(this.browserProps={fullscreenChange:"MSFullscreenChange",requestFullscreen:"msRequestFullscreen",exitFullscreen:"msExitFullscreen"}))}c.prototype.close=function(){var e=this.chart,c=e.options.chart;if(this.isOpen&&this.browserProps&&e.container.ownerDocument instanceof Document)e.container.ownerDocument[this.browserProps.exitFullscreen]();this.unbindFullscreenEvent&&(this.unbindFullscreenEvent=
this.unbindFullscreenEvent());e.setSize(this.origWidth,this.origHeight,!1);this.origHeight=this.origWidth=void 0;c.width=this.origWidthOption;c.height=this.origHeightOption;this.origHeightOption=this.origWidthOption=void 0;this.isOpen=!1;this.setButtonText()};c.prototype.open=function(){var e=this,c=e.chart,h=c.options.chart;h&&(e.origWidthOption=h.width,e.origHeightOption=h.height);e.origWidth=c.chartWidth;e.origHeight=c.chartHeight;if(e.browserProps){var k=n(c.container.ownerDocument,e.browserProps.fullscreenChange,
function(){e.isOpen?(e.isOpen=!1,e.close()):(c.setSize(null,null,!1),e.isOpen=!0,e.setButtonText())}),m=n(c,"destroy",k);e.unbindFullscreenEvent=function(){k();m()};if(h=c.renderTo[e.browserProps.requestFullscreen]())h["catch"](function(){alert("Full screen is not supported inside a frame.")})}};c.prototype.setButtonText=function(){var e=this.chart,c=e.exportDivElements,k=e.options.exporting,m=k&&k.buttons&&k.buttons.contextButton.menuItems;e=e.options.lang;k&&k.menuItemDefinitions&&e&&e.exitFullscreen&&
e.viewFullscreen&&m&&c&&c.length&&h.setElementHTML(c[m.indexOf("viewFullscreen")],this.isOpen?e.exitFullscreen:k.menuItemDefinitions.viewFullscreen.text||e.viewFullscreen)};c.prototype.toggle=function(){this.isOpen?this.close():this.open()};return c}();m.Fullscreen=k;n(c,"beforeRender",function(){this.fullscreen=new m.Fullscreen(this)});return m.Fullscreen});q(c,"Mixins/Navigation.js",[],function(){return{initUpdate:function(c){c.navigation||(c.navigation={updates:[],update:function(c,h){this.updates.forEach(function(k){k.update.call(k.context,
c,h)})}})},addUpdate:function(c,m){m.navigation||this.initUpdate(m);m.navigation.updates.push({update:c,context:m})}}});q(c,"Extensions/Exporting.js",[c["Core/Chart/Chart.js"],c["Mixins/Navigation.js"],c["Core/Globals.js"],c["Core/Options.js"],c["Core/Color/Palette.js"],c["Core/Renderer/SVG/SVGRenderer.js"],c["Core/Utilities.js"]],function(c,m,h,k,n,q,e){var z=h.doc,G=h.isTouchDevice,B=h.win;k=k.defaultOptions;var x=e.addEvent,r=e.css,y=e.createElement,E=e.discardElement,A=e.extend,H=e.find,D=e.fireEvent,
I=e.isObject,p=e.merge,F=e.objectEach,t=e.pick,J=e.removeEvent,K=e.uniqueKey;A(k.lang,{viewFullscreen:"View in full screen",exitFullscreen:"Exit from full screen",printChart:"Print chart",downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image",contextButtonTitle:"Chart context menu"});k.navigation||(k.navigation={});p(!0,k.navigation,{buttonOptions:{theme:{},symbolSize:14,symbolX:12.5,symbolY:10.5,align:"right",
buttonSpacing:3,height:22,verticalAlign:"top",width:24}});p(!0,k.navigation,{menuStyle:{border:"1px solid "+n.neutralColor40,background:n.backgroundColor,padding:"5px 0"},menuItemStyle:{padding:"0.5em 1em",color:n.neutralColor80,background:"none",fontSize:G?"14px":"11px",transition:"background 250ms, color 250ms"},menuItemHoverStyle:{background:n.highlightColor80,color:n.backgroundColor},buttonOptions:{symbolFill:n.neutralColor60,symbolStroke:n.neutralColor60,symbolStrokeWidth:3,theme:{padding:5}}});
k.exporting={type:"image/png",url:"https://export.highcharts.com/",printMaxWidth:780,scale:2,buttons:{contextButton:{className:"highcharts-contextbutton",menuClassName:"highcharts-contextmenu",symbol:"menu",titleKey:"contextButtonTitle",menuItems:"viewFullscreen printChart separator downloadPNG downloadJPEG downloadPDF downloadSVG".split(" ")}},menuItemDefinitions:{viewFullscreen:{textKey:"viewFullscreen",onclick:function(){this.fullscreen.toggle()}},printChart:{textKey:"printChart",onclick:function(){this.print()}},
separator:{separator:!0},downloadPNG:{textKey:"downloadPNG",onclick:function(){this.exportChart()}},downloadJPEG:{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}},downloadPDF:{textKey:"downloadPDF",onclick:function(){this.exportChart({type:"application/pdf"})}},downloadSVG:{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}}};h.post=function(a,b,f){var d=y("form",p({method:"post",action:a,enctype:"multipart/form-data"},f),{display:"none"},
z.body);F(b,function(a,b){y("input",{type:"hidden",name:b,value:a},null,d)});d.submit();E(d)};h.isSafari&&h.win.matchMedia("print").addListener(function(a){h.printingChart&&(a.matches?h.printingChart.beforePrint():h.printingChart.afterPrint())});A(c.prototype,{sanitizeSVG:function(a,b){var f=a.indexOf("</svg>")+6,d=a.substr(f);a=a.substr(0,f);b&&b.exporting&&b.exporting.allowHTML&&d&&(d='<foreignObject x="0" y="0" width="'+b.chart.width+'" height="'+b.chart.height+'"><body xmlns="http://www.w3.org/1999/xhtml">'+
d.replace(/(<(?:img|br).*?(?=>))>/g,"$1 />")+"</body></foreignObject>",a=a.replace("</svg>",d+"</svg>"));a=a.replace(/zIndex="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/url\(("|&quot;)(.*?)("|&quot;);?\)/g,"url($2)").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ (|NS[0-9]+:)href=/g," xlink:href=").replace(/\n/," ").replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g,
'$1="rgb($2)" $1-opacity="$3"').replace(/&nbsp;/g,"\u00a0").replace(/&shy;/g,"\u00ad");this.ieSanitizeSVG&&(a=this.ieSanitizeSVG(a));return a},getChartHTML:function(){this.styledMode&&this.inlineStyles();return this.container.innerHTML},getSVG:function(a){var b,f=p(this.options,a);f.plotOptions=p(this.userOptions.plotOptions,a&&a.plotOptions);f.time=p(this.userOptions.time,a&&a.time);var d=y("div",null,{position:"absolute",top:"-9999em",width:this.chartWidth+"px",height:this.chartHeight+"px"},z.body);
var e=this.renderTo.style.width;var u=this.renderTo.style.height;e=f.exporting.sourceWidth||f.chart.width||/px$/.test(e)&&parseInt(e,10)||(f.isGantt?800:600);u=f.exporting.sourceHeight||f.chart.height||/px$/.test(u)&&parseInt(u,10)||400;A(f.chart,{animation:!1,renderTo:d,forExport:!0,renderer:"SVGRenderer",width:e,height:u});f.exporting.enabled=!1;delete f.data;f.series=[];this.series.forEach(function(a){b=p(a.userOptions,{animation:!1,enableMouseTracking:!1,showCheckbox:!1,visible:a.visible});b.isInternal||
f.series.push(b)});var h={};this.axes.forEach(function(a){a.userOptions.internalKey||(a.userOptions.internalKey=K());a.options.isInternal||(h[a.coll]||(h[a.coll]=!0,f[a.coll]=[]),f[a.coll].push(p(a.userOptions,{visible:a.visible})))});var g=new c(f,this.callback);a&&["xAxis","yAxis","series"].forEach(function(b){var d={};a[b]&&(d[b]=a[b],g.update(d))});this.axes.forEach(function(a){var b=H(g.axes,function(b){return b.options.internalKey===a.userOptions.internalKey}),d=a.getExtremes(),f=d.userMin;
d=d.userMax;b&&("undefined"!==typeof f&&f!==b.min||"undefined"!==typeof d&&d!==b.max)&&b.setExtremes(f,d,!0,!1)});e=g.getChartHTML();D(this,"getSVG",{chartCopy:g});e=this.sanitizeSVG(e,f);f=null;g.destroy();E(d);return e},getSVGForExport:function(a,b){var f=this.options.exporting;return this.getSVG(p({chart:{borderRadius:0}},f.chartOptions,b,{exporting:{sourceWidth:a&&a.sourceWidth||f.sourceWidth,sourceHeight:a&&a.sourceHeight||f.sourceHeight}}))},getFilename:function(){var a=this.userOptions.title&&
this.userOptions.title.text,b=this.options.exporting.filename;if(b)return b.replace(/\//g,"-");"string"===typeof a&&(b=a.toLowerCase().replace(/<\/?[^>]+(>|$)/g,"").replace(/[\s_]+/g,"-").replace(/[^a-z0-9\-]/g,"").replace(/^[\-]+/g,"").replace(/[\-]+/g,"-").substr(0,24).replace(/[\-]+$/g,""));if(!b||5>b.length)b="chart";return b},exportChart:function(a,b){b=this.getSVGForExport(a,b);a=p(this.options.exporting,a);h.post(a.url,{filename:a.filename?a.filename.replace(/\//g,"-"):this.getFilename(),type:a.type,
width:a.width||0,scale:a.scale,svg:b},a.formAttributes)},moveContainers:function(a){(this.fixedDiv?[this.fixedDiv,this.scrollingContainer]:[this.container]).forEach(function(b){a.appendChild(b)})},beforePrint:function(){var a=z.body,b=this.options.exporting.printMaxWidth,f={childNodes:a.childNodes,origDisplay:[],resetParams:void 0};this.isPrinting=!0;this.pointer.reset(null,0);D(this,"beforePrint");b&&this.chartWidth>b&&(f.resetParams=[this.options.chart.width,void 0,!1],this.setSize(b,void 0,!1));
[].forEach.call(f.childNodes,function(a,b){1===a.nodeType&&(f.origDisplay[b]=a.style.display,a.style.display="none")});this.moveContainers(a);this.printReverseInfo=f},afterPrint:function(){if(this.printReverseInfo){var a=this.printReverseInfo.childNodes,b=this.printReverseInfo.origDisplay,f=this.printReverseInfo.resetParams;this.moveContainers(this.renderTo);[].forEach.call(a,function(a,f){1===a.nodeType&&(a.style.display=b[f]||"")});this.isPrinting=!1;f&&this.setSize.apply(this,f);delete this.printReverseInfo;
delete h.printingChart;D(this,"afterPrint")}},print:function(){var a=this;a.isPrinting||(h.printingChart=a,h.isSafari||a.beforePrint(),setTimeout(function(){B.focus();B.print();h.isSafari||setTimeout(function(){a.afterPrint()},1E3)},1))},contextMenu:function(a,b,f,d,c,h,k){var g=this,u=g.options.navigation,m=g.chartWidth,C=g.chartHeight,v="cache-"+a,l=g[v],w=Math.max(c,h);if(!l){g.exportContextMenu=g[v]=l=y("div",{className:a},{position:"absolute",zIndex:1E3,padding:w+"px",pointerEvents:"auto"},g.fixedDiv||
g.container);var p=y("ul",{className:"highcharts-menu"},{listStyle:"none",margin:0,padding:0},l);g.styledMode||r(p,A({MozBoxShadow:"3px 3px 10px #888",WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},u.menuStyle));l.hideMenu=function(){r(l,{display:"none"});k&&k.setState(0);g.openMenu=!1;r(g.renderTo,{overflow:"hidden"});r(g.container,{overflow:"hidden"});e.clearTimeout(l.hideTimer);D(g,"exportMenuHidden")};g.exportEvents.push(x(l,"mouseleave",function(){l.hideTimer=B.setTimeout(l.hideMenu,
500)}),x(l,"mouseenter",function(){e.clearTimeout(l.hideTimer)}),x(z,"mouseup",function(b){g.pointer.inClass(b.target,a)||l.hideMenu()}),x(l,"click",function(){g.openMenu&&l.hideMenu()}));b.forEach(function(a){"string"===typeof a&&(a=g.options.exporting.menuItemDefinitions[a]);if(I(a,!0)){var b=void 0;a.separator?b=y("hr",null,null,p):("viewData"===a.textKey&&g.isDataTableVisible&&(a.textKey="hideData"),b=y("li",{className:"highcharts-menu-item",onclick:function(b){b&&b.stopPropagation();l.hideMenu();
a.onclick&&a.onclick.apply(g,arguments)}},null,p),b.appendChild(z.createTextNode(a.text||g.options.lang[a.textKey])),g.styledMode||(b.onmouseover=function(){r(this,u.menuItemHoverStyle)},b.onmouseout=function(){r(this,u.menuItemStyle)},r(b,A({cursor:"pointer"},u.menuItemStyle))));g.exportDivElements.push(b)}});g.exportDivElements.push(p,l);g.exportMenuWidth=l.offsetWidth;g.exportMenuHeight=l.offsetHeight}b={display:"block"};f+g.exportMenuWidth>m?b.right=m-f-c-w+"px":b.left=f-w+"px";d+h+g.exportMenuHeight>
C&&"top"!==k.alignOptions.verticalAlign?b.bottom=C-d-w+"px":b.top=d+h-w+"px";r(l,b);r(g.renderTo,{overflow:""});r(g.container,{overflow:""});g.openMenu=!0;D(g,"exportMenuShown")},addButton:function(a){var b=this,f=b.renderer,d=p(b.options.navigation.buttonOptions,a),c=d.onclick,e=d.menuItems,h=d.symbolSize||12;b.btnCount||(b.btnCount=0);b.exportDivElements||(b.exportDivElements=[],b.exportSVGElements=[]);if(!1!==d.enabled&&d.theme){var g=d.theme,k=g.states,m=k&&k.hover;k=k&&k.select;var C;b.styledMode||
(g.fill=t(g.fill,n.backgroundColor),g.stroke=t(g.stroke,"none"));delete g.states;c?C=function(a){a&&a.stopPropagation();c.call(b,a)}:e&&(C=function(a){a&&a.stopPropagation();b.contextMenu(v.menuClassName,e,v.translateX,v.translateY,v.width,v.height,v);v.setState(2)});d.text&&d.symbol?g.paddingLeft=t(g.paddingLeft,30):d.text||A(g,{width:d.width,height:d.height,padding:0});b.styledMode||(g["stroke-linecap"]="round",g.fill=t(g.fill,n.backgroundColor),g.stroke=t(g.stroke,"none"));var v=f.button(d.text,
0,0,C,g,m,k).addClass(a.className).attr({title:t(b.options.lang[d._titleKey||d.titleKey],"")});v.menuClassName=a.menuClassName||"highcharts-menu-"+b.btnCount++;if(d.symbol){var l=f.symbol(d.symbol,d.symbolX-h/2,d.symbolY-h/2,h,h,{width:h,height:h}).addClass("highcharts-button-symbol").attr({zIndex:1}).add(v);b.styledMode||l.attr({stroke:d.symbolStroke,fill:d.symbolFill,"stroke-width":d.symbolStrokeWidth||1})}v.add(b.exportingGroup).align(A(d,{width:v.width,x:t(d.x,b.buttonOffset)}),!0,"spacingBox");
b.buttonOffset+=(v.width+d.buttonSpacing)*("right"===d.align?-1:1);b.exportSVGElements.push(v,l)}},destroyExport:function(a){var b=a?a.target:this;a=b.exportSVGElements;var f=b.exportDivElements,d=b.exportEvents,c;a&&(a.forEach(function(a,d){a&&(a.onclick=a.ontouchstart=null,c="cache-"+a.menuClassName,b[c]&&delete b[c],b.exportSVGElements[d]=a.destroy())}),a.length=0);b.exportingGroup&&(b.exportingGroup.destroy(),delete b.exportingGroup);f&&(f.forEach(function(a,d){e.clearTimeout(a.hideTimer);J(a,
"mouseleave");b.exportDivElements[d]=a.onmouseout=a.onmouseover=a.ontouchstart=a.onclick=null;E(a)}),f.length=0);d&&(d.forEach(function(a){a()}),d.length=0)}});q.prototype.inlineToAttributes="fill stroke strokeLinecap strokeLinejoin strokeWidth textAnchor x y".split(" ");q.prototype.inlineBlacklist=[/-/,/^(clipPath|cssText|d|height|width)$/,/^font$/,/[lL]ogical(Width|Height)$/,/perspective/,/TapHighlightColor/,/^transition/,/^length$/];q.prototype.unstyledElements=["clipPath","defs","desc"];c.prototype.inlineStyles=
function(){function a(a){return a.replace(/([A-Z])/g,function(a,b){return"-"+b.toLowerCase()})}function b(c){function f(b,f){w=r=!1;if(k){for(t=k.length;t--&&!r;)r=k[t].test(f);w=!r}"transform"===f&&"none"===b&&(w=!0);for(t=e.length;t--&&!w;)w=e[t].test(f)||"function"===typeof b;w||z[f]===b&&"svg"!==c.nodeName||g[c.nodeName][f]===b||(d&&-1===d.indexOf(f)?l+=a(f)+":"+b+";":b&&c.setAttribute(a(f),b))}var l="",w,r,t;if(1===c.nodeType&&-1===m.indexOf(c.nodeName)){var u=B.getComputedStyle(c,null);var z=
"svg"===c.nodeName?{}:B.getComputedStyle(c.parentNode,null);if(!g[c.nodeName]){n=q.getElementsByTagName("svg")[0];var x=q.createElementNS(c.namespaceURI,c.nodeName);n.appendChild(x);g[c.nodeName]=p(B.getComputedStyle(x,null));"text"===c.nodeName&&delete g.text.fill;n.removeChild(x)}if(h.isFirefox||h.isMS)for(var y in u)f(u[y],y);else F(u,f);l&&(u=c.getAttribute("style"),c.setAttribute("style",(u?u+";":"")+l));"svg"===c.nodeName&&c.setAttribute("stroke-width","1px");"text"!==c.nodeName&&[].forEach.call(c.children||
c.childNodes,b)}}var c=this.renderer,d=c.inlineToAttributes,e=c.inlineBlacklist,k=c.inlineWhitelist,m=c.unstyledElements,g={},n;c=z.createElement("iframe");r(c,{width:"1px",height:"1px",visibility:"hidden"});z.body.appendChild(c);var q=c.contentWindow.document;q.open();q.write('<svg xmlns="http://www.w3.org/2000/svg"></svg>');q.close();b(this.container.querySelector("svg"));n.parentNode.removeChild(n);c.parentNode.removeChild(c)};h.Renderer.prototype.symbols.menu=function(a,b,c,d){return[["M",a,b+
2.5],["L",a+c,b+2.5],["M",a,b+d/2+.5],["L",a+c,b+d/2+.5],["M",a,b+d-1.5],["L",a+c,b+d-1.5]]};h.Renderer.prototype.symbols.menuball=function(a,b,c,d){a=[];d=d/3-2;return a=a.concat(this.circle(c-d,b,d,d),this.circle(c-d,b+d+4,d,d),this.circle(c-d,b+2*(d+4),d,d))};c.prototype.renderExporting=function(){var a=this,b=a.options.exporting,c=b.buttons,d=a.isDirtyExporting||!a.exportSVGElements;a.buttonOffset=0;a.isDirtyExporting&&a.destroyExport();d&&!1!==b.enabled&&(a.exportEvents=[],a.exportingGroup=a.exportingGroup||
a.renderer.g("exporting-group").attr({zIndex:3}).add(),F(c,function(b){a.addButton(b)}),a.isDirtyExporting=!1)};x(c,"init",function(){var a=this;a.exporting={update:function(b,c){a.isDirtyExporting=!0;p(!0,a.options.exporting,b);t(c,!0)&&a.redraw()}};m.addUpdate(function(b,c){a.isDirtyExporting=!0;p(!0,a.options.navigation,b);t(c,!0)&&a.redraw()},a)});c.prototype.callbacks.push(function(a){a.renderExporting();x(a,"redraw",a.renderExporting);x(a,"destroy",a.destroyExport)})});q(c,"masters/modules/exporting.src.js",
[],function(){})});
//# sourceMappingURL=/assets/highcharts-9.1.0/modules/exporting.js-81484a0deb539824cf071576741d4ab8d714409b6dad9cca01a4b4d401ec64c6.map
//!
;
/*
 Highcharts JS v9.1.0 (2021-05-03)

 Client side exporting module

 (c) 2015-2021 Torstein Honsi / Oystein Moseng

 License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/offline-exporting",["highcharts","highcharts/modules/exporting"],function(d){a(d);a.Highcharts=d;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function d(a,b,D,d){a.hasOwnProperty(b)||(a[b]=d.apply(null,D))}a=a?a._modules:{};d(a,"Extensions/DownloadURL.js",[a["Core/Globals.js"]],function(a){var b=a.win,d=b.document,
z=b.URL||b.webkitURL||b,l=a.dataURLtoBlob=function(a){if((a=a.replace(/filename=.*;/,"").match(/data:([^;]*)(;base64)?,([0-9A-Za-z+/]+)/))&&3<a.length&&b.atob&&b.ArrayBuffer&&b.Uint8Array&&b.Blob&&z.createObjectURL){var A=b.atob(a[3]),d=new b.ArrayBuffer(A.length);d=new b.Uint8Array(d);for(var k=0;k<d.length;++k)d[k]=A.charCodeAt(k);a=new b.Blob([d],{type:a[1]});return z.createObjectURL(a)}};a=a.downloadURL=function(a,q){var w=b.navigator,k=d.createElement("a");if("string"===typeof a||a instanceof
String||!w.msSaveOrOpenBlob){a=""+a;if(/Edge\/\d+/.test(w.userAgent)||2E6<a.length)if(a=l(a)||"",!a)throw Error("Failed to convert to blob");if("undefined"!==typeof k.download)k.href=a,k.download=q,d.body.appendChild(k),k.click(),d.body.removeChild(k);else try{var n=b.open(a,"chart");if("undefined"===typeof n||null===n)throw Error("Failed to open window");}catch(h){b.location.href=a}}else w.msSaveOrOpenBlob(a,q)};return{dataURLtoBlob:l,downloadURL:a}});d(a,"Extensions/OfflineExporting.js",[a["Core/Chart/Chart.js"],
a["Core/Globals.js"],a["Core/Options.js"],a["Core/Renderer/SVG/SVGRenderer.js"],a["Core/Utilities.js"],a["Extensions/DownloadURL.js"]],function(a,b,d,z,l,A){function q(a,b){var f=y.getElementsByTagName("head")[0],c=y.createElement("script");c.type="text/javascript";c.src=a;c.onload=b;c.onerror=function(){E("Error loading script "+a)};f.appendChild(c)}function w(a){var e=h.navigator.userAgent;e=-1<e.indexOf("WebKit")&&0>e.indexOf("Chrome");try{if(!e&&!b.isFirefox)return F.createObjectURL(new h.Blob([a],
{type:"image/svg+xml;charset-utf-16"}))}catch(f){}return"data:image/svg+xml;charset=UTF-8,"+encodeURIComponent(a)}function k(a,b,f,c,d,u,k,m,r){var g=new h.Image,e=function(){setTimeout(function(){var e=y.createElement("canvas"),u=e.getContext&&e.getContext("2d");try{if(u){e.height=g.height*c;e.width=g.width*c;u.drawImage(g,0,0,e.width,e.height);try{var x=e.toDataURL(b);d(x,b,f,c)}catch(H){p(a,b,f,c)}}else k(a,b,f,c)}finally{r&&r(a,b,f,c)}},K)},G=function(){m(a,b,f,c);r&&r(a,b,f,c)};var p=function(){g=
new h.Image;p=u;g.crossOrigin="Anonymous";g.onload=e;g.onerror=G;g.src=a};g.onload=e;g.onerror=G;g.src=a}function n(a,b,f,c){function d(a,b){var c=a.width.baseVal.value+2*b;b=a.height.baseVal.value+2*b;c=new h.jsPDF(b>c?"p":"l","pt",[c,b]);[].forEach.call(a.querySelectorAll('*[visibility="hidden"]'),function(a){a.parentNode.removeChild(a)});b=a.querySelectorAll("linearGradient");for(var f=0;f<b.length;f++)for(var e=b[f].querySelectorAll("stop"),d=0;d<e.length&&"0"===e[d].getAttribute("offset")&&"0"===
e[d+1].getAttribute("offset");)e[d].remove(),d++;[].forEach.call(a.querySelectorAll("tspan"),function(a){"\u200b"===a.textContent&&(a.textContent=" ",a.setAttribute("dx",-5))});h.svg2pdf(a,c,{removeInvalid:!0});return c.output("datauristring")}function e(){r.innerHTML=a;var b=r.getElementsByTagName("text"),e;[].forEach.call(b,function(a){["font-family","font-size"].forEach(function(b){for(var c=a;c&&c!==r;){if(c.style[b]){a.style[b]=c.style[b];break}c=c.parentNode}});a.style["font-family"]=a.style["font-family"]&&
a.style["font-family"].split(" ").splice(-1);e=a.getElementsByTagName("title");[].forEach.call(e,function(b){a.removeChild(b)})});b=d(r.firstChild,0);try{C(b,B),c&&c()}catch(L){f(L)}}var l=!0,m=b.libURL||I().exporting.libURL,r=y.createElement("div"),g=b.type||"image/png",B=(b.filename||"chart")+"."+("image/svg+xml"===g?"svg":g.split("/")[1]),n=b.scale||1;m="/"!==m.slice(-1)?m+"/":m;if("image/svg+xml"===g)try{if("undefined"!==typeof h.navigator.msSaveOrOpenBlob){var p=new MSBlobBuilder;p.append(a);
var t=p.getBlob("image/svg+xml")}else t=w(a);C(t,B);c&&c()}catch(x){f(x)}else if("application/pdf"===g)h.jsPDF&&h.svg2pdf?e():(l=!0,q(m+"jspdf.js",function(){q(m+"svg2pdf.js",function(){e()})}));else{t=w(a);var v=function(){try{F.revokeObjectURL(t)}catch(x){}};k(t,g,{},n,function(a){try{C(a,B),c&&c()}catch(H){f(H)}},function(){var b=y.createElement("canvas"),e=b.getContext("2d"),d=a.match(/^<svg[^>]*width\s*=\s*"?(\d+)"?[^>]*>/)[1]*n,u=a.match(/^<svg[^>]*height\s*=\s*"?(\d+)"?[^>]*>/)[1]*n,k=function(){e.drawSvg(a,
0,0,d,u);try{C(h.navigator.msSaveOrOpenBlob?b.msToBlob():b.toDataURL(g),B),c&&c()}catch(M){f(M)}finally{v()}};b.width=d;b.height=u;h.canvg?k():(l=!0,q(m+"rgbcolor.js",function(){q(m+"canvg.js",function(){k()})}))},f,f,function(){l&&v()})}}var h=b.win,y=b.doc,I=d.getOptions,D=l.addEvent,E=l.error,N=l.extend,O=l.fireEvent,J=l.merge,C=A.downloadURL,F=h.URL||h.webkitURL||h,K=b.isMS?150:0;b.CanVGRenderer={};a.prototype.getSVGForLocalExport=function(a,b,f,c){var d=this,e=0,h,m,l,g,n=function(){e===p.length&&
c(d.sanitizeSVG(h.innerHTML,m))},q=function(a,b,c){++e;c.imageElement.setAttributeNS("http://www.w3.org/1999/xlink","href",a);n()};d.unbindGetSVG=D(d,"getSVG",function(a){m=a.chartCopy.options;h=a.chartCopy.container.cloneNode(!0)});d.getSVGForExport(a,b);var p=h.getElementsByTagName("image");try{if(!p.length){c(d.sanitizeSVG(h.innerHTML,m));return}var t=0;for(l=p.length;t<l;++t){var v=p[t];(g=v.getAttributeNS("http://www.w3.org/1999/xlink","href"))?k(g,"image/png",{imageElement:v},a.scale,q,f,f,
f):(++e,v.parentNode.removeChild(v),n())}}catch(x){f(x)}d.unbindGetSVG()};a.prototype.exportChartLocal=function(a,d){var f=this,c=J(f.options.exporting,a),e=function(a){!1===c.fallbackToExportServer?c.error?c.error(c,a):E(28,!0):f.exportChart(c)};a=function(){return[].some.call(f.container.getElementsByTagName("image"),function(a){a=a.getAttribute("href");return""!==a&&0!==a.indexOf("data:")})};b.isMS&&f.styledMode&&(z.prototype.inlineWhitelist=[/^blockSize/,/^border/,/^caretColor/,/^color/,/^columnRule/,
/^columnRuleColor/,/^cssFloat/,/^cursor/,/^fill$/,/^fillOpacity/,/^font/,/^inlineSize/,/^length/,/^lineHeight/,/^opacity/,/^outline/,/^parentRule/,/^rx$/,/^ry$/,/^stroke/,/^textAlign/,/^textAnchor/,/^textDecoration/,/^transform/,/^vectorEffect/,/^visibility/,/^x$/,/^y$/]);b.isMS&&("application/pdf"===c.type||f.container.getElementsByTagName("image").length&&"image/svg+xml"!==c.type)||"application/pdf"===c.type&&a()?e("Image type not supported for this chart/browser."):f.getSVGForLocalExport(c,d||
{},e,function(a){-1<a.indexOf("<foreignObject")&&"image/svg+xml"!==c.type?e("Image type not supportedfor charts with embedded HTML"):n(a,N({filename:f.getFilename()},c),e,function(){return O(f,"exportChartLocalSuccess")})})};J(!0,I().exporting,{libURL:"https://code.highcharts.com/9.1.0/lib/",menuItemDefinitions:{downloadPNG:{textKey:"downloadPNG",onclick:function(){this.exportChartLocal()}},downloadJPEG:{textKey:"downloadJPEG",onclick:function(){this.exportChartLocal({type:"image/jpeg"})}},downloadSVG:{textKey:"downloadSVG",
onclick:function(){this.exportChartLocal({type:"image/svg+xml"})}},downloadPDF:{textKey:"downloadPDF",onclick:function(){this.exportChartLocal({type:"application/pdf"})}}}});b.downloadSVGLocal=n});d(a,"masters/modules/offline-exporting.src.js",[],function(){})});
//# sourceMappingURL=/assets/highcharts-9.1.0/modules/offline-exporting.js-27bd31b85fb208f8f94e304106835dcd84acfb31d7b7458b025ed0fbacd82d33.map
//!
;
/**



 */;
;(function($) {
    if( $ === undefined ) {
        throw new Error( 'jQuery is required.' );
    }

    var HighChartBase = function() {
        this.properties = {};
    };
    Backstop.HighChartBase = HighChartBase;
    HighChartBase.prototype = {
        retrieveData: function() {
            var self = this;
            $.ajax({
                type: 'GET',
                url: this.properties.dataPath,
                async: false,
                complete: function(xrh) {
                    self.data = jQuery.parseJSON(xrh.responseText).rows;
                }
            });
        },

        format: function(i, decimal, format, currencySymbol) {
          var fixed;
          if(!currencySymbol) {
              currencySymbol = this.properties.defaultCurrencySymbol;
          }
          if(!format) {
              format = this.properties.format;
          }
          if(format == "MONEY") {
              if(!decimal && decimal !== 0) {
                  decimal = 2;
              }
              fixed = i.toFixed(decimal);
              var splitFixed = ('' + fixed).split('.');
              var integerPart = splitFixed[0];
              var digits = integerPart.length - 3;
              for( ; digits > 0; digits -=3 ) {
                  integerPart = integerPart.slice(0, digits) + ',' + integerPart.slice(digits);
              }
              return currencySymbol + integerPart + (decimal === 0 ? "" : ("." + splitFixed[1]));
          } else if(format == "PERCENTAGE") {
              if(!decimal  && decimal !== 0) {
                  decimal = 2;
              }
              var percentagized = i*100;
              fixed = percentagized.toFixed(decimal);
              return fixed + "%";
          } else {
              return '' + i;
          }
        }
    };

}(window.jQuery));
;(function($) {
  var Backstop = window.Backstop || {};

  if ( $ === undefined ) {
    throw new Error( 'jQuery is required.' );
  }

  if ( window.Backstop === undefined ) {
    window.Backstop = Backstop;
  }

  $.fn.createGrowthAssetChart = function (options) {
    var defaults = {
      divId: $(this).attr('id'),
      title: '',
      subTitle: '',
      width: null,
      height: 600,
      format: 'MONEY',
      yTitle: '',
      y2Title: '',
      defaultCurrencySymbol: '$'
    };
    var growthAssetChart = new Backstop.HighGrowthAssetChart($.extend( defaults, options));
    growthAssetChart.render();
  };

  var HighGrowthAssetChart = function( properties ) {
    if (!properties.dataPath  || !properties.xLabelsField || !properties.ySeriesField || !properties.y2SeriesField ) {
      throw 'Missing necessary information for growth-asset chart.';
    }
    this.properties = properties;
  };

  Backstop.HighGrowthAssetChart = HighGrowthAssetChart;
  HighGrowthAssetChart.prototype = new Backstop.HighChartBase();
  HighGrowthAssetChart.prototype.render = function() {
    var self = this;
    if ( !self.xLabels || !self.ySeries || !self.y2Series) {
      self.processData();
    }

    var xLength = self.xLabels.length;
    var xStep = xLength < 36 ? 6 : xLength < 60 ? 12 : xLength < 324 ? 24 : 48;
    var chart = new Highcharts.Chart({
      chart: { renderTo: self.properties.divId, zoomType: 'xy' },
      credits: { enabled: false },
      lang:  { contextButtonTitle: I18n.t('charts.export_chart') },
      title: { text: self.properties.title },
      subtitle: { text: self.properties.subTitle },
      xAxis: [{ categories: self.xLabels, labels: { step: xStep, y: 20 } }],
      yAxis: [
        {
          title: {
            text: self.properties.y2Title,
            style: { color: '#4572A7' }
          },
          labels: {
            formatter: function() { return self.format(this.value, 0, 'MONEY'); },
            style: { color: '#4572A7' }
          }
        },
        {
          title: {
            text: self.properties.yTitle,
            style: { color: '#89A54E' }
          },
          labels: {
            formatter: function() { return self.format(this.value, 0, 'MONEY'); },
            style: { color: '#89A54E' }
          },
          opposite: true
        }
      ],
      tooltip: {
        formatter: function() {
          if (this.series.name == 'AUM') {
            return this.x + ': ' + self.format(this.y) + ' (mm)';
          } else {
            return this.x + ': ' + self.format(this.y);
          }
        }
      },
      legend: {
        layout: 'vertical',
        align: 'left',
        x: 75,
        verticalAlign: 'top',
        y: 50,
        floating: true,
        backgroundColor: '#FFFFFF'
      },
      exporting:  {
        fallbackToExportServer: false
      },
      series: [
        {
          name: self.properties.yTitle,
          color: '#89A54E',
          type: 'area',
          yAxis: 1,
          data: self.ySeries,
          marker: { enabled: false },
          lineWidth: 1
        },
        {
          name: self.properties.y2Title,
          color: '#4572A7',
          type: 'line',
          yAxis: 0,
          data: self.y2Series,
          marker: { enabled: false },
          lineWidth: 3
        }
      ]
    });
  };

  HighGrowthAssetChart.prototype.processData = function() {
    var self = this;
    if (!self.data) {
      self.retrieveData();
    }
    self.xLabels = this.data[self.properties.xLabelsField];
    self.ySeries = this.data[self.properties.ySeriesField];
    self.y2Series = this.data[self.properties.y2SeriesField];
  };
}(window.jQuery));
;(function($) {
  var Backstop = window.Backstop || {};

  if ( $ === undefined ) {
    throw new Error( 'jQuery is required.' );
  }

  if ( window.Backstop === undefined ) {
    window.Backstop = Backstop;
  }

  $.fn.createHistogramChart = function (options) {
    var defaults = {
      divId: $(this).attr('id'),
      title: '',
      yTitle: '',
      colors: Highcharts.getOptions().colors,
      xSeries: null, // This must be an evenly distributed array! i.e. [1,2,3,4] NOT [1,3,4,5]
      width: null,
      height: 600,
      seriesField: 'returns',
      multiSeriesField: 'multiSeries',
      seriesTitle: '',
      defaultCurrencySymbol: '$',
      fontFamily: 'inherit !important',
      borderRadius: '0',
      backgroundColor: 'white',
      plotBackgroundColor: 'white',
      xAxisColor: '#666',
      yAxisColor: '#666',
      labelColor: Highcharts.getOptions().colors[0],
      yTitleColor: Highcharts.getOptions().colors[0],
      legendColor: Highcharts.getOptions().colors[0]
    };
    var histogramChart = new Backstop.HighHistogramChart($.extend( defaults, options));
    histogramChart.render();
  };

  var HighHistogramChart = function( properties ) {
    if (!properties.dataPath  || !properties.xSeries || !properties.seriesField ) {
      throw 'Missing necessary information for histogram chart.';
    }
    this.properties = properties;
  };

  Backstop.HighHistogramChart = HighHistogramChart;

  HighHistogramChart.prototype = new Backstop.HighChartBase();

  HighHistogramChart.prototype.render = function() {
    var self = this;
    if ( !self.xLabels || !self.seriesData ) {
      self.processData();
    }

    var series = [{
      name: self.properties.seriesTitle,
      color: self.properties.colors[0],
      data: self.seriesData
    }].concat(self.benchmarkTransformedData);

    var chart = new Highcharts.Chart({
      chart: {
        renderTo: self.properties.divId,
        type: 'column',
        height: self.properties.height,
        width: self.properties.width,
        borderRadius: self.properties.borderRadius,
        backgroundColor: self.properties.backgroundColor,
        plotBackgroundColor: self.properties.plotBackgroundColor,
        style: {
          fontFamily: self.properties.fontFamily
        }
      },

      credits: { enabled: false },
      title: {
        text: self.properties.title,
        style: {
          color: self.properties.labelColor
        }
      },
      legend: {
        itemStyle: {
          color: self.properties.legendColor
        }
      },
      lang:  { contextButtonTitle: I18n.t('charts.export_chart') },
      xAxis: {
        categories: self.xLabels,
        labels: {
          rotation: -90,
          align: 'right',
          style: {
            color: self.properties.xAxisColor
          }
        }
      },
      yAxis: {
        min: 0,
        title: {
          text: self.properties.yTitle,
          style: {
            color: self.properties.yTitleColor
          }
        },
        labels: {
          style: {
            color: self.properties.yAxisColor
          }
        }
      },
      tooltip: {
        formatter: function() {
          return this.x + ': ' + this.y + ' mth(s)';
        }
      },
      plotOptions: {
        column: {
          pointPadding: 0.1,
          borderWidth: 0
        }
      },
      exporting:  {
        fallbackToExportServer: false
      },
      series: series
    });
  };

  HighHistogramChart.prototype.processData = function() {
    var self = this;
    self.xLabels = [];
    if (self.properties.xSeries.length < 1 ) {
      throw new Error('You must have at least one x category.');
    }
    self.seriesData = [0, 0];
    self.xLabels.push(self.properties.xSeries[0] + ' and below');
    for (var i = 0; i < self.properties.xSeries.length - 1; i++) {
      self.xLabels.push(
        self.properties.xSeries[i] + ' to ' +
        self.properties.xSeries[i + 1]
      );
      self.seriesData.push(0);
    }
    self.xLabels.push(self.properties.xSeries[i] + ' and up');

    if (!self.data) {
      self.retrieveData();
    }

    var multiple = self.properties.xSeries.length == 1 ? 0 :
        self.properties.xSeries[1] - self.properties.xSeries[0];
    var offset = 0 - self.properties.xSeries[0];

    jQuery.each(self.data[self.properties.seriesField], function(i, d) {
      i = (d / multiple) * 100;   // This was spiked for returns, thus the *100
      i = i + (offset / multiple) + 1;
      i = Math.floor(i);
      i = i < 0 ? 0 : i > self.seriesData.length - 1 ? self.seriesData.length - 1 : i;
      self.seriesData[i]++;
    });

    self.benchmarkTransformedData = [];
    jQuery.each(self.data[self.properties.multiSeriesField], function(indexOfBenchmark, benchmarkMap) {
      transformedBenchmarkMap = [];
      transformedBenchmarkMap['name'] = benchmarkMap['title'];
      transformedBenchmarkMap['color'] = self.properties.colors[indexOfBenchmark + 1];
      transformedBenchmarkMap['data'] = new Array(self.properties.xSeries.length + 1).fill(0);
      jQuery.each(benchmarkMap['returnData'], function(dataIndex, value) {
        dataIndex = (value / multiple) * 100;   // This was spiked for returns, thus the *100
        dataIndex = dataIndex + (offset / multiple) + 1;
        dataIndex = Math.floor(dataIndex);
        lastIndex = self.seriesData.length - 1
         if(dataIndex < 0){
           dataIndex = 0;
         }
         if(dataIndex > lastIndex){
           dataIndex = lastIndex
         }
        transformedBenchmarkMap['data'][dataIndex]++;
      });
      self.benchmarkTransformedData.push(transformedBenchmarkMap)
    });
  };
}(window.jQuery));
/*
Make a line chart with sensible defaults.
Functionality is added to the jquery $ object when this file is loaded.
Basic Usage:

  $('#some_div_to_put_the_chart_in').createLineChart(
    [{
      name: 'Line Name',
      data: 'line_data_identifier'
    }],
    {
      dataPath: '<%= path_to_json_data, format: 'json' -%>',
      title: 'Graph Name',
      xLabelsField: 'x_axis_label_identifier',
      seriesField: 'line_data_identifier',
      seriesTitle: 'Line Name'
    }
  );

The first parameter should be an array with one hash per line on the graph,
including the display name and data identifier for that line.  Other
line-specific options for Highcharts may be passed along here as well,
otherwise sensible defaults will be automatically set.

The second parameter is a hash of graph-level parameters to pass along to Highcharts.
The dataPath key is required.  Json returned by this path should be of the form:

  {
    'rows' => {
      'line_data_identifier' => [data_point_1, data_point_2...],
      'x_axis_label_identifier' => [label_1, label_2...],
    }
  }

When using multiple lines on a single graph, in addition to listing these
fields in the input array, you need to set "multiSeriesField" for the second
input and "thirdSeriesField" for the third.  Not sure if a 4th line is
supported???  There is clearly some redundancy in the input parameters.
This should be fixed.  By someone.  Eventually.
*/
;(function($) {
  var Backstop = window.Backstop || {};

  if ( $ === undefined ) {
    throw new Error( 'jQuery is required.' );
  }

  if ( window.Backstop === undefined ) {
    window.Backstop = Backstop;
  }

  $.fn.createLineChart = function (series, options) {
    if ( series === undefined ) {
      throw new Error( 'series is required.' );
    }
    var defaults = {
      divId: $(this).attr('id'),
      title: '',
      yTitle: '',
      colors: Highcharts.getOptions().colors,
      width: null,
      height: 350,
      format: 'MONEY',
      borderColor: '#cdcccc',
      borderRadius: 1,
      defaultCurrencySymbol: '',
      fontFamily: 'inherit !important',
      backgroundColor: 'white',
      plotBackgroundColor: 'white',
      xAxisColor: '#666',
      yAxisColor: '#666',
      labelColor: Highcharts.getOptions().colors[0],
      yTitleColor: Highcharts.getOptions().colors[0],
      legendColor: Highcharts.getOptions().colors[0],
      subTitleColor: Highcharts.getOptions().colors[0],
      markersEnabled: false
    };
    var lineChart = new Backstop.HighLineChart(
      $.extend(defaults, options)
    );
    lineChart.render(series);
  };

  var HighLineChart = function( properties ) {
    if (!properties.dataPath  || !properties.xLabelsField || !properties.seriesField ) {
      throw 'Missing necessary information for returns chart.';
    }
    this.properties = properties;
  };

  Backstop.HighLineChart = HighLineChart;

  HighLineChart.prototype = new Backstop.HighChartBase();

  HighLineChart.prototype.render = function(series) {
    var self = this;
    if ( !self.xLabels || !self.seriesData ) {
      self.processData();
    }

    var colorindex = 0;
    series.forEach(function (dataline) {
      $.extend(dataline, {
        type: 'line',
        color: self.properties.colors[colorindex],
        marker: { enabled: self.properties.markersEnabled },
        lineWidth: 3,
        data: self.data[dataline.data],
      });
      colorindex = colorindex + 1;
    });
    $.extend(series[0], {
      backgroundColor: self.properties.backgroundColor,
      borderWidth: self.properties.borderWidth,
      borderColor: self.properties.borderColor,
      borderRadius: self.properties.borderRadius
    });

    var xLength = self.xLabels.length;
    var numberOfMonthsBetweenLabels = xLength < 36 ? 6 : xLength < 60 ? 12 : xLength < 324 ? 24 : 48;
    var chart = new Highcharts.Chart({
      chart: {
        renderTo: self.properties.divId,
        zoomType: 'xy',
        height: self.properties.height,
        width: self.properties.width,
        backgroundColor: self.properties.backgroundColor,
        plotBackgroundColor: self.properties.plotBackgroundColor,
        style: {
          fontFamily: self.properties.fontFamily
        }
      },
      credits: { enabled: false },
      lang:  { contextButtonTitle: I18n.t('charts.export_chart') },
      title: {
        text: self.properties.title,
        style: {
          color: self.properties.labelColor
        }
      },
      subtitle: {
        text: self.xLabels[0] + ' - ' + self.xLabels[xLength - 1],
        style: {
          color: self.properties.subTitleColor
        }
      },
      xAxis: [{
        categories: self.xLabels,
        labels: {
          step: numberOfMonthsBetweenLabels,
          rotation: -45,
          y: 40,
          style: {
            color: self.properties.xAxisColor
          }
        }
      }],
      yAxis: [{
        min: null,
        labels: {
          formatter: function() {
            return self.format(this.value, 0);
          } ,
          style: {
            color: self.properties.yAxisColor
          }
        },
        title: {
          text: self.properties.yTitle,
          style: {
            color: self.properties.yTitleColor
          }
        }
      }],
      tooltip: { formatter: function() { return this.x + ': ' + self.format(this.y); } },
      legend: {
        layout: 'vertical',
        align: 'left',
        x: 60,
        verticalAlign: 'top',
        y: -10,
        floating: true,
        backgroundColor: 'none',
        borderWidth: 0,
        itemStyle: {
          color: self.properties.legendColor
        }
      },
      exporting:  {
        fallbackToExportServer: false,
        chartOptions: {
          legend: {
            x: 0,
            y: -10,
            floating: true,
          }
        }
      },
      series: series

    });
  };

  HighLineChart.prototype.processData = function() {
    var self = this;
    if (!self.data) {
      self.retrieveData();
    }

    self.xLabels = self.data[self.properties.xLabelsField];
    self.seriesData = self.data[self.properties.seriesField];
  };

}(window.jQuery));
;(function($) {
  var Backstop = window.Backstop || {};

  if ( $ === undefined ) {
    throw new Error( 'jQuery is required.' );
  }

  if ( window.Backstop === undefined ) {
    window.Backstop = Backstop;
  }

  $.fn.createPieChart = function (options) {
    var defaults = {
      divId: $(this).attr('id'),
      title: '',
      colors: Highcharts.getOptions().colors,
      chartPercentageField: null,
      format: 'MONEY',
      sizeInner: '75%',
      sizeOuter: '75%',
      distanceInner: -30,
      distanceOuter: 30,
      colorInner: 'white',
      colorOuter: 'grey',
      labelFunction: function() {},
      width: null,
      height: 600,
      borderRadius: 0,
      defaultCurrencySymbol: '$',
      style: { fontFamily: 'inherit !important' },
      tooltip: {
        formatter: function() {
          return '<b>' + this.point.name + '</b>: ' +  self.format(this.point.value);
        }
      }
    };
    var pieChart = new Backstop.HighPieChart($.extend( defaults, options));
    pieChart.render();
  };

  var HighPieChart = function( properties ) {
    if (!properties.dataPath || !properties.seriesCategories || !properties.dataField) {
      throw 'Missing necessary information for pie chart.';
    }
    this.properties = properties;
    this.properties.seriesCategories = this.properties.seriesCategories.split(',');
    if (!this.properties.chartPercentageField) {
      this.properties.chartPercentageField = properties.dataField;
    }
  };

  Backstop.HighPieChart = HighPieChart;

  HighPieChart.prototype = new Backstop.HighChartBase();

  HighPieChart.prototype.render = function() {
    var self = this;
    self.resolveLevelData();
    var series = [];
    series.push({
      name: self.properties.seriesCategories[0],
      data: self.levelOneData,
      size: self.properties.sizeInner,
      dataLabels: {
        formatter: self.properties.labelFunction,
        color: self.properties.colorInner,
        distance: self.properties.distanceInner
      }
    });
    var twoLevels = this.properties.seriesCategories.length > 1;
    if (twoLevels) {
      series.push({
        name: self.properties.seriesCategories[0],
        data: self.levelTwoData,
        innerSize: self.properties.sizeOuter,
        dataLabels: {
          formatter: function() {
            // Display only if larger than 1
            return this.point.value > 1 ? '<b>' + this.point.name + '</b><br/>' + self.format(this.point.value) : null;
          },
          color: self.properties.colorOuter,
          distance: self.properties.distanceOuter
        }
      });
    }

    Highcharts.setOptions({
      chart: { style: self.properties.style },
      tooltip: self.properties.tooltip
    });

    var chart = new Highcharts.Chart({
      chart: {
        renderTo: self.properties.divId,
        type: 'pie',
        width: self.properties.width,
        height: self.properties.height,
        borderWidth: self.properties.borderWidth,
        borderColor: self.properties.borderColor,
        borderRadius: self.properties.borderRadius
      },
      credits: { enabled: false },
      title: { text: self.properties.title },
      lang:  { contextButtonTitle: I18n.t('charts.export_chart') },
      yAxis: { title: { text: self.properties.title } },
      plotOptions: { pie: { shadow: false } },
      // Hide the export buttons until we do this in house
      exporting: {
        fallbackToExportServer: false
      },
      series: series
    });
  };

  HighPieChart.prototype.processData = function() {
    var self = this;
    if (!self.data) {
      self.retrieveData();
    }
    self.sortData();

    self.processedData = [];
    var twoLevels = self.properties.seriesCategories.length > 1;
    var levelOneCatName = self.properties.seriesCategories[0];
    var levelTwoCatName = twoLevels ? self.properties.seriesCategories[1] : null;
    var colorIndex = 0;
    var currentCat;
    var currentPercentageSum;
    var currentSum;
    var levelTwo;

    jQuery.each(this.data, function(i, entry) {
      if (currentCat != entry[levelOneCatName]) {
        if (i > 0) {
          self.processedData.push({
            name: currentCat,
            y: currentPercentageSum,
            value: currentSum,
            color: self.properties.colors[colorIndex],
            levelTwo: twoLevels ? levelTwo : null
          });
          colorIndex = (colorIndex == (self.properties.colors.length - 1)) ? 0 : colorIndex + 1;
        }
        currentCat = entry[levelOneCatName];
        currentPercentageSum = self.checkFloat(entry[self.properties.chartPercentageField]);
        currentSum = self.checkFloat(entry[self.properties.dataField]);
        levelTwo = twoLevels ? {
          names: [entry[levelTwoCatName]],
          percentage: [self.checkFloat(entry[self.properties.chartPercentageField])],
          values: [self.checkFloat(entry[self.properties.dataField])]
        } : null;
      } else {
        currentPercentageSum += self.checkFloat(entry[self.properties.chartPercentageField]);
        currentSum += self.checkFloat(entry[self.properties.dataField]);
        if (twoLevels) {
          levelTwo.names.push(entry[levelTwoCatName]);
          levelTwo.percentage.push(self.checkFloat(entry[self.properties.chartPercentageField]));
          levelTwo.values.push(self.checkFloat(entry[self.properties.dataField]));
        }
      }
    });

    // This is to avoid two colors being next to each other...
    var firstDataWithValue;
    jQuery.each(self.processedData, function (i, d) {
      if (d.y > 0 && !firstDataWithValue) { firstDataWithValue = d; }
    });
    if (self.processedData.length > 1 &&
        firstDataWithValue &&
        self.properties.colors[colorIndex] == firstDataWithValue.color) {
      colorIndex++;
    }

    self.processedData.push({
      name: currentCat,
      y: currentPercentageSum,
      value: currentSum,
      color: self.properties.colors[colorIndex],
      levelTwo: twoLevels ? levelTwo : null
    });
  };

  HighPieChart.prototype.checkFloat = function(f) {
    return isNaN(parseFloat(f)) ? 0 : parseFloat(f);
  };

  HighPieChart.prototype.resolveLevelData = function() {
    var self = this;
    if (!self.processedData) {
      self.processData();
    }
    self.levelOneData = [];
    var twoLevels = self.properties.seriesCategories.length > 1;
    self.levelTwoData = twoLevels ? [] : null;

    for (var i = 0; i < self.processedData.length; i++) {
      thisData = self.processedData[i];
      self.levelOneData.push({
        name: thisData.name,
        y: thisData.y,
        value: thisData.value,
        color: thisData.color
      });

      if (twoLevels) {
        for (var j = 0; j < thisData.levelTwo.values.length; j++) {
          var brightness = 0.2 - (j / thisData.levelTwo.values.length) / 5 ;
          self.levelTwoData.push({
            name: thisData.levelTwo.names[j],
            y: thisData.levelTwo.percentage[j],
            value: thisData.levelTwo.values[j],
            color: Highcharts.Color(thisData.color).brighten(brightness).get()
          });
        }
      }
    }
  };

  HighPieChart.prototype.sortData = function() {
    var self = this;
    var sortFunction = function(a, b) {
      var cat1 = self.properties.seriesCategories[0];
      var cat2 = self.properties.seriesCategories[1];
      if (a[cat1] == b[cat1]) {
        if (a[cat2] == b[cat2]) {
          return 0;
        } else if (a[cat2] > b[cat2] || a[cat2] === null) {
          return 1;
        } else {
          return -1;
        }
      } else if ( a[cat1] > b[cat1] || a[cat1] === null) {
        return 1;
      } else {
        return -1;
      }
    };
    self.data = self.data.sort(sortFunction);
  };
}(window.jQuery));
;(function($) {
    var Backstop = window.Backstop || {};

    if( $ === undefined ) {
        throw new Error( 'jQuery is required.' );
    }

    if( window.Backstop === undefined ) {
        window.Backstop = Backstop;
    }

    $.fn.createReturnsChart = function (options) {
        var defaults = {
            divId: $(this).attr('id'),
            title: '',
            yTitle: '',
            colors: Highcharts.getOptions().colors,
            width: null,
            height: 600,
            format: "PERCENTAGE",
            seriesField: 'returns',
            multiSeriesTitle: 'title',
            multiSeriesData: 'data',
            seriesTitle: '',
            borderColor: '#cdcccc',
            borderRadius: 1,
            defaultCurrencySymbol: '',
            fontFamily:'inherit !important',
            backgroundColor: 'white',
            plotBackgroundColor: 'white',
            xAxisColor:'#666',
            yAxisColor:'#666',
            labelColor: Highcharts.getOptions().colors[0],
            yTitleColor: Highcharts.getOptions().colors[0],
            legendColor: Highcharts.getOptions().colors[0],
            subTitleColor: Highcharts.getOptions().colors[0],
            markersEnabled: false
        };
        var returnsChart = new Backstop.HighReturnsChart($.extend( defaults, options));
        returnsChart.render();
    };

    var HighReturnsChart = function( properties ) {
        if(!properties.dataPath  || !properties.xLabelsField || !properties.seriesField ) {
            throw "Missing necessary information for returns chart.";
        }
        this.properties = properties;
    };

    Backstop.HighReturnsChart = HighReturnsChart;

    HighReturnsChart.prototype = new Backstop.HighChartBase();

    HighReturnsChart.prototype.render = function() {
        var self = this;
        if( !self.xLabels || !self.seriesData ) {
            self.processData();
        }

        var series = [{
            name: self.properties.seriesTitle,
            color: self.properties.colors[0],
            type: 'line',
            data: self.seriesData,
            // pointStart: Date.UTC(2006, 2, 1),
            // pointInterval: 24 * 3600 * 1000 * 30,
            marker: { enabled: self.properties.markersEnabled },
            lineWidth: 3,
            backgroundColor: self.properties.backgroundColor,
            borderWidth: self.properties.borderWidth,
            borderColor: self.properties.borderColor,
            borderRadius: self.properties.borderRadius
        }];

        var colorIndex = 1;

        jQuery.each(self.additionalSeries, function(i,s) {
                    series.push({
                        name:s.title,
                        color: self.properties.colors[colorIndex],
                        type: 'line',
                        data:s.data,
                        marker: { enabled: false },
                        lineWidth: 3
                    });
                    colorIndex = (colorIndex == (self.properties.colors.length - 1)) ? 0 : colorIndex + 1;
                });

//        Highcharts.setOptions({
//          chart: { style: self.properties.style}
//        });

        var xLength = self.xLabels.length;
        var numberOfMonthsBetweenLabels = xLength < 36 ? 6 : xLength < 60 ? 12 : xLength < 324 ? 24 : 48;
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: self.properties.divId,
                zoomType: 'xy',
                height: self.properties.height,
                width: self.properties.width,
                backgroundColor: self.properties.backgroundColor,
                plotBackgroundColor: self.properties.plotBackgroundColor,
                style:{
                    fontFamily: self.properties.fontFamily
                }
            },
            credits: { enabled: false },
            lang:  { contextButtonTitle: I18n.t('charts.export_chart') },
            title: {
                text: self.properties.title,
                style:{
                    color: self.properties.labelColor
                }
            },
            subtitle: {
                text: self.xLabels[0] + " - " + self.xLabels[xLength - 1],
                style:{
                    color: self.properties.subTitleColor
                }
            },
            xAxis: [{
                // type: 'datetime'
                categories: self.xLabels,
                labels: {
                    step: numberOfMonthsBetweenLabels,
                    rotation: -45,
                    y: 40,
                    style:{
                        color: self.properties.xAxisColor
                    }
                }
            }],
            yAxis: [{
                labels: {
                    formatter: function() {
                        return self.format(this.value, 0);
                    } ,
                    style:{
                        color: self.properties.yAxisColor
                    }
                },
                title: {
                    text: self.properties.yTitle,
                    style:{
                        color: self.properties.yTitleColor
                    }
                }
            }],
            tooltip: { formatter: function() { return this.x +': '+ self.format(this.y); } },
            legend: {
                layout: 'vertical',
                align: 'left',
                x: 33,
                verticalAlign: 'top',
                y: -10,
                floating: true,
                backgroundColor: 'none',
                borderWidth: 0,
                itemStyle:{
                    color: self.properties.legendColor
                }
            },
            exporting:  {
                fallbackToExportServer: false,
                chartOptions: {
                    legend: {
                      x: 0,
                      y: -10,
                      floating: true,
                    }
                }
            },
            series: series

        });
    };

    HighReturnsChart.prototype.processData = function() {
        var self = this;
        if(!self.data) {
            self.retrieveData();
        }
        
        var isVami = self.properties.seriesField == 'value_of_1000';
        
        self.xLabels = self.data[self.properties.xLabelsField];
        self.seriesData = self.data[self.properties.seriesField];
        if ( isVami ) {
          self.xLabels.unshift( self.xLabels[0] );
          self.seriesData.unshift( 1000.00 );
        }
        self.additionalSeries = [];
        if(self.properties.multiSeriesField &&
                self.data[self.properties.multiSeriesField])  {
            jQuery.each(self.data[self.properties.multiSeriesField], function(i,s) {
                values = s[self.properties.multiSeriesData];
                if (isVami) {
                  values.unshift( 1000.00 );
                }
                self.additionalSeries.push({
                    title: s[self.properties.multiSeriesTitle],
                    data: values
                });
            });


        }
    };
    
}(window.jQuery));
//     Underscore.js 1.2.3
//     (c) 2009-2011 Jeremy Ashkenas, DocumentCloud Inc.
//     Underscore is freely distributable under the MIT license.
//     Portions of Underscore are inspired or borrowed from Prototype,
//     Oliver Steele's Functional, and John Resig's Micro-Templating.
//     For all details and documentation:
//     http://documentcloud.github.com/underscore

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var slice            = ArrayProto.slice,
      concat           = ArrayProto.concat,
      unshift          = ArrayProto.unshift,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) { return new wrapper(obj); };

  // Export the Underscore object for **Node.js** and **"CommonJS"**, with
  // backwards-compatibility for the old `require()` API. If we're not in
  // CommonJS, add `_` to the global object.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else if (typeof define === 'function' && define.amd) {
    // Register as a named module with AMD.
    define('underscore', function() {
      return _;
    });
  } else {
    // Exported as a string, for Closure Compiler "advanced" mode.
    root['_'] = _;
  }

  // Current version.
  _.VERSION = '1.2.3';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    return results;
  };

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError('Reduce of empty array with no initial value');
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var reversed = _.toArray(obj).reverse();
    if (context && !initial) iterator = _.bind(iterator, context);
    return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
    var result;
    any(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
    each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    each(obj, function(value, index, list) {
      if (!iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function(obj, target) {
    var found = false;
    if (obj == null) return found;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    found = any(obj, function(value) {
      return value === target;
    });
    return found;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    return _.map(obj, function(value) {
      return (method.call ? method || value : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, function(value){ return value[key]; });
  };

  // Return the maximum element or (element-based computation).
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return -Infinity;
    var result = {computed : -Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed >= result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return Infinity;
    var result = {computed : Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Shuffle an array.
  _.shuffle = function(obj) {
    var shuffled = [], rand;
    each(obj, function(value, index, list) {
      if (index == 0) {
        shuffled[0] = value;
      } else {
        rand = Math.floor(Math.random() * (index + 1));
        shuffled[index] = shuffled[rand];
        shuffled[rand] = value;
      }
    });
    return shuffled;
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, iterator, context) {
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value : value,
        criteria : iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }), 'value');
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = function(obj, val) {
    var result = {};
    var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
    each(obj, function(value, index) {
      var key = iterator(value, index);
      (result[key] || (result[key] = [])).push(value);
    });
    return result;
  };

  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator) {
    iterator || (iterator = _.identity);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >> 1;
      iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely convert anything iterable into a real, live array.
  _.toArray = function(iterable) {
    if (!iterable)                return [];
    if (iterable.toArray)         return iterable.toArray();
    if (_.isArray(iterable))      return slice.call(iterable);
    if (_.isArguments(iterable))  return slice.call(iterable);
    return _.values(iterable);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    return _.toArray(obj).length;
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head`. The **guard** check allows it to work
  // with `_.map`.
  _.first = _.head = function(array, n, guard) {
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

  // Returns everything but the last entry of the array. Especcialy useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if ((n != null) && !guard) {
      return slice.call(array, Math.max(array.length - n, 0));
    } else {
      return array[array.length - 1];
    }
  };

  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function(array, index, guard) {
    return slice.call(array, (index == null) || guard ? 1 : index);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, function(value){ return !!value; });
  };

  // Return a completely flattened version of an array.
  _.flatten = function(array, shallow) {
    return _.reduce(array, function(memo, value) {
      if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
      memo[memo.length] = value;
      return memo;
    }, []);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iterator) {
    var initial = iterator ? _.map(array, iterator) : array;
    var result = [];
    _.reduce(initial, function(memo, el, i) {
      if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
        memo[memo.length] = el;
        result[result.length] = array[i];
      }
      return memo;
    }, []);
    return result;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(_.flatten(arguments, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.indexOf(other, item) >= 0;
      });
    });
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = _.flatten(slice.call(arguments, 1));
    return _.filter(array, function(value){ return !_.include(rest, value); });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    var args = slice.call(arguments);
    var length = _.max(_.pluck(args, 'length'));
    var results = new Array(length);
    for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
    return results;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
      i = _.sortedIndex(array, item);
      return array[i] === item ? i : -1;
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item) {
    if (array == null) return -1;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
    var i = array.length;
    while (i--) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var len = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(len);

    while(idx < len) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Reusable constructor function for prototype setting.
  var ctor = function(){};

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function bind(func, context) {
    var bound, args;
    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length == 0) funcs = _.functions(obj);
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){ return func.apply(func, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
    var context, args, timeout, throttling, more;
    var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
    return function() {
      context = this; args = arguments;
      var later = function() {
        timeout = null;
        if (more) func.apply(context, args);
        whenDone();
      };
      if (!timeout) timeout = setTimeout(later, wait);
      if (throttling) {
        more = true;
      } else {
        func.apply(context, args);
      }
      whenDone();
      throttling = true;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds.
  _.debounce = function(func, wait) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        func.apply(context, args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      return memo = func.apply(this, arguments);
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return function() {
      var args = concat.apply([func], arguments);
      return wrapper.apply(this, args);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    if (times <= 0) return func();
    return function() {
      if (--times < 1) { return func.apply(this, arguments); }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    return _.map(obj, _.identity);
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        if (source[prop] !== void 0) obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        if (obj[prop] == null) obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Internal recursive comparison function.
  function eq(a, b, stack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
    if (a === b) return a !== 0 || 1 / a == 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a._chain) a = a._wrapped;
    if (b._chain) b = b._wrapped;
    // Invoke a custom `isEqual` method if one is provided.
    if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
    if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className != toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') return false;
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = stack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (stack[length] == a) return true;
    }
    // Add the first object to the stack of traversed objects.
    stack.push(a);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          // Ensure commutative equality for sparse arrays.
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
        }
      }
    } else {
      // Objects with different constructors are not equivalent.
      if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
      // Deep compare objects.
      for (var key in a) {
        if (hasOwnProperty.call(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (hasOwnProperty.call(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    stack.pop();
    return result;
  }

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b, []);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
    return true;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType == 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    return obj === Object(obj);
  };

  // Is a given variable an arguments object?
  _.isArguments = function(obj) {
    return toString.call(obj) == '[object Arguments]';
  };
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && hasOwnProperty.call(obj, 'callee'));
    };
  }

  // Is a given value a function?
  _.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

  // Is a given value a string?
  _.isString = function(obj) {
    return toString.call(obj) == '[object String]';
  };

  // Is a given value a number?
  _.isNumber = function(obj) {
    return toString.call(obj) == '[object Number]';
  };

  // Is the given value `NaN`?
  _.isNaN = function(obj) {
    // `NaN` is the only value for which `===` is not reflexive.
    return obj !== obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

  // Is a given value a date?
  _.isDate = function(obj) {
    return toString.call(obj) == '[object Date]';
  };

  // Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return toString.call(obj) == '[object RegExp]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  _.identity = function(value) {
    return value;
  };

  // Run a function **n** times.
  _.times = function (n, iterator, context) {
    for (var i = 0; i < n; i++) iterator.call(context, i);
  };

  // Escape a string for HTML interpolation.
  _.escape = function(string) {
    return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
  };

  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function(obj) {
    each(_.functions(obj), function(name){
      addToWrapper(name, _[name] = obj[name]);
    });
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = idCounter++;
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(str, data) {
    var c  = _.templateSettings;
    var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
      'with(obj||{}){__p.push(\'' +
      str.replace(/\\/g, '\\\\')
         .replace(/'/g, "\\'")
         .replace(c.escape, function(match, code) {
           return "',_.escape(" + code.replace(/\\'/g, "'") + "),'";
         })
         .replace(c.interpolate, function(match, code) {
           return "'," + code.replace(/\\'/g, "'") + ",'";
         })
         .replace(c.evaluate || null, function(match, code) {
           return "');" + code.replace(/\\'/g, "'")
                              .replace(/[\r\n\t]/g, ' ') + ";__p.push('";
         })
         .replace(/\r/g, '\\r')
         .replace(/\n/g, '\\n')
         .replace(/\t/g, '\\t')
         + "');}return __p.join('');";
    var func = new Function('obj', '_', tmpl);
    if (data) return func(data, _);
    return function(data) {
      return func.call(this, data, _);
    };
  };

  // The OOP Wrapper
  // ---------------

  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function(obj) { this._wrapped = obj; };

  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;

  // Helper function to continue chaining intermediate results.
  var result = function(obj, chain) {
    return chain ? _(obj).chain() : obj;
  };

  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function(name, func) {
    wrapper.prototype[name] = function() {
      var args = slice.call(arguments);
      unshift.call(args, this._wrapped);
      return result(func.apply(_, args), this._chain);
    };
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      method.apply(this._wrapped, arguments);
      return result(this._wrapped, this._chain);
    };
  });

  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      return result(method.apply(this._wrapped, arguments), this._chain);
    };
  });

  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function() {
    this._chain = true;
    return this;
  };

  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function() {
    return this._wrapped;
  };

}).call(this);
//     Backbone.js 0.5.3
//     (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://documentcloud.github.com/backbone

(function(){

  // Initial Setup
  // -------------

  // Save a reference to the global object.
  var root = this;

  // Save the previous value of the `Backbone` variable.
  var previousBackbone = root.Backbone;

  // The top-level namespace. All public Backbone classes and modules will
  // be attached to this. Exported for both CommonJS and the browser.
  var Backbone;
  if (typeof exports !== 'undefined') {
    Backbone = exports;
  } else {
    Backbone = root.Backbone = {};
  }

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '0.5.3';

  // Require Underscore, if we're on the server, and it's not already present.
  var _ = root._;
  if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._;

  // For Backbone's purposes, jQuery or Zepto owns the `$` variable.
  var $ = root.jQuery || root.Zepto;

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return this;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will
  // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
  // `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Backbone.Events
  // -----------------

  // A module that can be mixed in to *any object* in order to provide it with
  // custom events. You may `bind` or `unbind` a callback function to an event;
  // `trigger`-ing an event fires all callbacks in succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.bind('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  Backbone.Events = {

    // Bind an event, specified by a string name, `ev`, to a `callback` function.
    // Passing `"all"` will bind the callback to all events fired.
    bind : function(ev, callback, context) {
      var calls = this._callbacks || (this._callbacks = {});
      var list  = calls[ev] || (calls[ev] = []);
      list.push([callback, context]);
      return this;
    },

    // Remove one or many callbacks. If `callback` is null, removes all
    // callbacks for the event. If `ev` is null, removes all bound callbacks
    // for all events.
    unbind : function(ev, callback) {
      var calls;
      if (!ev) {
        this._callbacks = {};
      } else if (calls = this._callbacks) {
        if (!callback) {
          calls[ev] = [];
        } else {
          var list = calls[ev];
          if (!list) return this;
          for (var i = 0, l = list.length; i < l; i++) {
            if (list[i] && callback === list[i][0]) {
              list[i] = null;
              break;
            }
          }
        }
      }
      return this;
    },

    // Trigger an event, firing all bound callbacks. Callbacks are passed the
    // same arguments as `trigger` is, apart from the event name.
    // Listening for `"all"` passes the true event name as the first argument.
    trigger : function(eventName) {
      var list, calls, ev, callback, args;
      var both = 2;
      if (!(calls = this._callbacks)) return this;
      while (both--) {
        ev = both ? eventName : 'all';
        if (list = calls[ev]) {
          for (var i = 0, l = list.length; i < l; i++) {
            if (!(callback = list[i])) {
              list.splice(i, 1); i--; l--;
            } else {
              args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
              callback[0].apply(callback[1] || this, args);
            }
          }
        }
      }
      return this;
    }

  };

  // Backbone.Model
  // --------------

  // Create a new model, with defined attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  Backbone.Model = function(attributes, options) {
    var defaults;
    attributes || (attributes = {});
    if (defaults = this.defaults) {
      if (_.isFunction(defaults)) defaults = defaults.call(this);
      attributes = _.extend({}, defaults, attributes);
    }
    this.attributes = {};
    this._escapedAttributes = {};
    this.cid = _.uniqueId('c');
    this.set(attributes, {silent : true});
    this._changed = false;
    this._previousAttributes = _.clone(this.attributes);
    if (options && options.collection) this.collection = options.collection;
    this.initialize(attributes, options);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Backbone.Model.prototype, Backbone.Events, {

    // A snapshot of the model's previous attributes, taken immediately
    // after the last `"change"` event was fired.
    _previousAttributes : null,

    // Has the item been changed since the last `"change"` event?
    _changed : false,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute : 'id',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize : function(){},

    // Return a copy of the model's `attributes` object.
    toJSON : function() {
      return _.clone(this.attributes);
    },

    // Get the value of an attribute.
    get : function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape : function(attr) {
      var html;
      if (html = this._escapedAttributes[attr]) return html;
      var val = this.attributes[attr];
      return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val);
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has : function(attr) {
      return this.attributes[attr] != null;
    },

    // Set a hash of model attributes on the object, firing `"change"` unless you
    // choose to silence it.
    set : function(attrs, options) {

      // Extract attributes and options.
      options || (options = {});
      if (!attrs) return this;
      if (attrs.attributes) attrs = attrs.attributes;
      var now = this.attributes, escaped = this._escapedAttributes;

      // Run validation.
      if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;

      // Check for changes of `id`.
      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

      // We're about to start triggering change events.
      var alreadyChanging = this._changing;
      this._changing = true;

      // Update attributes.
      for (var attr in attrs) {
        var val = attrs[attr];
        if (!_.isEqual(now[attr], val)) {
          now[attr] = val;
          delete escaped[attr];
          this._changed = true;
          if (!options.silent) this.trigger('change:' + attr, this, val, options);
        }
      }

      // Fire the `"change"` event, if the model has been changed.
      if (!alreadyChanging && !options.silent && this._changed) this.change(options);
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"` unless you choose
    // to silence it. `unset` is a noop if the attribute doesn't exist.
    unset : function(attr, options) {
      if (!(attr in this.attributes)) return this;
      options || (options = {});
      var value = this.attributes[attr];

      // Run validation.
      var validObj = {};
      validObj[attr] = void 0;
      if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;

      // Remove the attribute.
      delete this.attributes[attr];
      delete this._escapedAttributes[attr];
      if (attr == this.idAttribute) delete this.id;
      this._changed = true;
      if (!options.silent) {
        this.trigger('change:' + attr, this, void 0, options);
        this.change(options);
      }
      return this;
    },

    // Clear all attributes on the model, firing `"change"` unless you choose
    // to silence it.
    clear : function(options) {
      options || (options = {});
      var attr;
      var old = this.attributes;

      // Run validation.
      var validObj = {};
      for (attr in old) validObj[attr] = void 0;
      if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;

      this.attributes = {};
      this._escapedAttributes = {};
      this._changed = true;
      if (!options.silent) {
        for (attr in old) {
          this.trigger('change:' + attr, this, void 0, options);
        }
        this.change(options);
      }
      return this;
    },

    // Fetch the model from the server. If the server's representation of the
    // model differs from its current attributes, they will be overriden,
    // triggering a `"change"` event.
    fetch : function(options) {
      options || (options = {});
      var model = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        if (!model.set(model.parse(resp, xhr), options)) return false;
        if (success) success(model, resp);
      };
      options.error = wrapError(options.error, model, options);
      return (this.sync || Backbone.sync).call(this, 'read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save : function(attrs, options) {
      options || (options = {});
      if (attrs && !this.set(attrs, options)) return false;
      var model = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        if (!model.set(model.parse(resp, xhr), options)) return false;
        if (success) success(model, resp, xhr);
      };
      options.error = wrapError(options.error, model, options);
      var method = this.isNew() ? 'create' : 'update';
      return (this.sync || Backbone.sync).call(this, method, this, options);
    },

    // Destroy this model on the server if it was already persisted. Upon success, the model is removed
    // from its collection, if it has one.
    destroy : function(options) {
      options || (options = {});
      if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        model.trigger('destroy', model, model.collection, options);
        if (success) success(model, resp);
      };
      options.error = wrapError(options.error, model, options);
      return (this.sync || Backbone.sync).call(this, 'delete', this, options);
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url : function() {
      var base = getUrl(this.collection) || this.urlRoot || urlError();
      if (this.isNew()) return base;
      return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse : function(resp, xhr) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone : function() {
      return new this.constructor(this);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew : function() {
      return this.id == null;
    },

    // Call this method to manually fire a `change` event for this model.
    // Calling this will cause all objects observing the model to update.
    change : function(options) {
      this.trigger('change', this, options);
      this._previousAttributes = _.clone(this.attributes);
      this._changed = false;
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged : function(attr) {
      if (attr) return this._previousAttributes[attr] != this.attributes[attr];
      return this._changed;
    },

    // Return an object containing all the attributes that have changed, or false
    // if there are no changed attributes. Useful for determining what parts of a
    // view need to be updated and/or what attributes need to be persisted to
    // the server.
    changedAttributes : function(now) {
      now || (now = this.attributes);
      var old = this._previousAttributes;
      var changed = false;
      for (var attr in now) {
        if (!_.isEqual(old[attr], now[attr])) {
          changed = changed || {};
          changed[attr] = now[attr];
        }
      }
      return changed;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous : function(attr) {
      if (!attr || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes : function() {
      return _.clone(this._previousAttributes);
    },

    // Run validation against a set of incoming attributes, returning `true`
    // if all is well. If a specific `error` callback has been passed,
    // call that instead of firing the general `"error"` event.
    _performValidation : function(attrs, options) {
      var error = this.validate(attrs);
      if (error) {
        if (options.error) {
          options.error(this, error, options);
        } else {
          this.trigger('error', this, error, options);
        }
        return false;
      }
      return true;
    }

  });

  // Backbone.Collection
  // -------------------

  // Provides a standard collection class for our sets of models, ordered
  // or unordered. If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  Backbone.Collection = function(models, options) {
    options || (options = {});
    if (options.comparator) this.comparator = options.comparator;
    _.bindAll(this, '_onModelEvent', '_removeReference');
    this._reset();
    if (models) this.reset(models, {silent: true});
    this.initialize.apply(this, arguments);
  };

  // Define the Collection's inheritable methods.
  _.extend(Backbone.Collection.prototype, Backbone.Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model : Backbone.Model,

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize : function(){},

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON : function() {
      return this.map(function(model){ return model.toJSON(); });
    },

    // Add a model, or list of models to the set. Pass **silent** to avoid
    // firing the `added` event for every new model.
    add : function(models, options) {
      if (_.isArray(models)) {
        for (var i = 0, l = models.length; i < l; i++) {
          this._add(models[i], options);
        }
      } else {
        this._add(models, options);
      }
      return this;
    },

    // Remove a model, or a list of models from the set. Pass silent to avoid
    // firing the `removed` event for every model removed.
    remove : function(models, options) {
      if (_.isArray(models)) {
        for (var i = 0, l = models.length; i < l; i++) {
          this._remove(models[i], options);
        }
      } else {
        this._remove(models, options);
      }
      return this;
    },

    // Get a model from the set by id.
    get : function(id) {
      if (id == null) return null;
      return this._byId[id.id != null ? id.id : id];
    },

    // Get a model from the set by client id.
    getByCid : function(cid) {
      return cid && this._byCid[cid.cid || cid];
    },

    // Get the model at the given index.
    at: function(index) {
      return this.models[index];
    },

    // Force the collection to re-sort itself. You don't need to call this under normal
    // circumstances, as the set will maintain sort order as each item is added.
    sort : function(options) {
      options || (options = {});
      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
      this.models = this.sortBy(this.comparator);
      if (!options.silent) this.trigger('reset', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck : function(attr) {
      return _.map(this.models, function(model){ return model.get(attr); });
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any `added` or `removed` events. Fires `reset` when finished.
    reset : function(models, options) {
      models  || (models = []);
      options || (options = {});
      this.each(this._removeReference);
      this._reset();
      this.add(models, {silent: true});
      if (!options.silent) this.trigger('reset', this, options);
      return this;
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `add: true` is passed, appends the
    // models to the collection instead of resetting.
    fetch : function(options) {
      options || (options = {});
      var collection = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
        if (success) success(collection, resp);
      };
      options.error = wrapError(options.error, collection, options);
      return (this.sync || Backbone.sync).call(this, 'read', this, options);
    },

    // Create a new instance of a model in this collection. After the model
    // has been created on the server, it will be added to the collection.
    // Returns the model, or 'false' if validation on a new model fails.
    create : function(model, options) {
      var coll = this;
      options || (options = {});
      model = this._prepareModel(model, options);
      if (!model) return false;
      var success = options.success;
      options.success = function(nextModel, resp, xhr) {
        coll.add(nextModel, options);
        if (success) success(nextModel, resp, xhr);
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse : function(resp, xhr) {
      return resp;
    },

    // Proxy to _'s chain. Can't be proxied the same way the rest of the
    // underscore methods are proxied because it relies on the underscore
    // constructor.
    chain: function () {
      return _(this.models).chain();
    },

    // Reset all internal state. Called when the collection is reset.
    _reset : function(options) {
      this.length = 0;
      this.models = [];
      this._byId  = {};
      this._byCid = {};
    },

    // Prepare a model to be added to this collection
    _prepareModel: function(model, options) {
      if (!(model instanceof Backbone.Model)) {
        var attrs = model;
        model = new this.model(attrs, {collection: this});
        if (model.validate && !model._performValidation(attrs, options)) model = false;
      } else if (!model.collection) {
        model.collection = this;
      }
      return model;
    },

    // Internal implementation of adding a single model to the set, updating
    // hash indexes for `id` and `cid` lookups.
    // Returns the model, or 'false' if validation on a new model fails.
    _add : function(model, options) {
      options || (options = {});
      model = this._prepareModel(model, options);
      if (!model) return false;
      var already = this.getByCid(model);
      if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
      this._byId[model.id] = model;
      this._byCid[model.cid] = model;
      var index = options.at != null ? options.at :
                  this.comparator ? this.sortedIndex(model, this.comparator) :
                  this.length;
      this.models.splice(index, 0, model);
      model.bind('all', this._onModelEvent);
      this.length++;
      if (!options.silent) model.trigger('add', model, this, options);
      return model;
    },

    // Internal implementation of removing a single model from the set, updating
    // hash indexes for `id` and `cid` lookups.
    _remove : function(model, options) {
      options || (options = {});
      model = this.getByCid(model) || this.get(model);
      if (!model) return null;
      delete this._byId[model.id];
      delete this._byCid[model.cid];
      this.models.splice(this.indexOf(model), 1);
      this.length--;
      if (!options.silent) model.trigger('remove', model, this, options);
      this._removeReference(model);
      return model;
    },

    // Internal method to remove a model's ties to a collection.
    _removeReference : function(model) {
      if (this == model.collection) {
        delete model.collection;
      }
      model.unbind('all', this._onModelEvent);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent : function(ev, model, collection, options) {
      if ((ev == 'add' || ev == 'remove') && collection != this) return;
      if (ev == 'destroy') {
        this._remove(model, options);
      }
      if (model && ev === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        this._byId[model.id] = model;
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Underscore methods that we want to implement on the Collection.
  var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
    'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
    'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
    'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy'];

  // Mix in each Underscore method as a proxy to `Collection#models`.
  _.each(methods, function(method) {
    Backbone.Collection.prototype[method] = function() {
      return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
    };
  });

  // Backbone.Router
  // -------------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var namedParam    = /:([\w\d]+)/g;
  var splatParam    = /\*([\w\d]+)/g;
  var escapeRegExp  = /[-[\]{}()+?.,\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Backbone.Router.prototype, Backbone.Events, {

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize : function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route : function(route, name, callback) {
      Backbone.history || (Backbone.history = new Backbone.History);
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      Backbone.history.route(route, _.bind(function(fragment) {
        var args = this._extractParameters(route, fragment);
        callback.apply(this, args);
        this.trigger.apply(this, ['route:' + name].concat(args));
      }, this));
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate : function(fragment, triggerRoute) {
      Backbone.history.navigate(fragment, triggerRoute);
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes : function() {
      if (!this.routes) return;
      var routes = [];
      for (var route in this.routes) {
        routes.unshift([route, this.routes[route]]);
      }
      for (var i = 0, l = routes.length; i < l; i++) {
        this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp : function(route) {
      route = route.replace(escapeRegExp, "\\$&")
                   .replace(namedParam, "([^\/]*)")
                   .replace(splatParam, "(.*?)");
      return new RegExp('^' + route + '$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted parameters.
    _extractParameters : function(route, fragment) {
      return route.exec(fragment).slice(1);
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on URL fragments. If the
  // browser does not support `onhashchange`, falls back to polling.
  Backbone.History = function() {
    this.handlers = [];
    _.bindAll(this, 'checkUrl');
  };

  // Cached regex for cleaning hashes.
  var hashStrip = /^#*/;

  // Cached regex for detecting MSIE.
  var isExplorer = /msie [\w.]+/;

  // Has the history handling already been started?
  var historyStarted = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(Backbone.History.prototype, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Get the cross-browser normalized URL fragment, either from the URL,
    // the hash, or the override.
    getFragment : function(fragment, forcePushState) {
      if (fragment == null) {
        if (this._hasPushState || forcePushState) {
          fragment = window.location.pathname;
          var search = window.location.search;
          if (search) fragment += search;
          if (fragment.indexOf(this.options.root) == 0) fragment = fragment.substr(this.options.root.length);
        } else {
          fragment = window.location.hash;
        }
      }
      return decodeURIComponent(fragment.replace(hashStrip, ''));
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start : function(options) {

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      if (historyStarted) throw new Error("Backbone.history has already been started");
      this.options          = _.extend({}, {root: '/'}, this.options, options);
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.options.pushState && window.history && window.history.pushState);
      var fragment          = this.getFragment();
      var docMode           = document.documentMode;
      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
      if (oldIE) {
        this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
        this.navigate(fragment);
      }

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._hasPushState) {
        $(window).bind('popstate', this.checkUrl);
      } else if ('onhashchange' in window && !oldIE) {
        $(window).bind('hashchange', this.checkUrl);
      } else {
        setInterval(this.checkUrl, this.interval);
      }

      // Determine if we need to change the base url, for a pushState link
      // opened by a non-pushState browser.
      this.fragment = fragment;
      historyStarted = true;
      var loc = window.location;
      var atRoot  = loc.pathname == this.options.root;
      if (this._wantsPushState && !this._hasPushState && !atRoot) {
        this.fragment = this.getFragment(null, true);
        window.location.replace(this.options.root + '#' + this.fragment);
        // Return immediately as browser will do redirect to new url
        return true;
      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
        this.fragment = loc.hash.replace(hashStrip, '');
        window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
      }

      if (!this.options.silent) {
        return this.loadUrl();
      }
    },

    // Add a route to be tested when the fragment changes. Routes added later may
    // override previous routes.
    route : function(route, callback) {
      this.handlers.unshift({route : route, callback : callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl : function(e) {
      var current = this.getFragment();
      if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
      if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl() || this.loadUrl(window.location.hash);
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl : function(fragmentOverride) {
      var fragment = this.fragment = this.getFragment(fragmentOverride);
      var matched = _.any(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
      return matched;
    },

    // Save a fragment into the hash history. You are responsible for properly
    // URL-encoding the fragment in advance. This does not trigger
    // a `hashchange` event.
    navigate : function(fragment, triggerRoute) {
      var frag = (fragment || '').replace(hashStrip, '');
      if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
      if (this._hasPushState) {
        var loc = window.location;
        if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
        this.fragment = frag;
        window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag);
      } else {
        window.location.hash = this.fragment = frag;
        if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
          this.iframe.document.open().close();
          this.iframe.location.hash = frag;
        }
      }
      if (triggerRoute) this.loadUrl(fragment);
    }

  });

  // Backbone.View
  // -------------

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this._configure(options || {});
    this._ensureElement();
    this.delegateEvents();
    this.initialize.apply(this, arguments);
  };

  // Element lookup, scoped to DOM elements within the current view.
  // This should be prefered to global lookups, if you're dealing with
  // a specific view.
  var selectorDelegate = function(selector) {
    return $(selector, this.el);
  };

  // Cached regex to split keys for `delegate`.
  var eventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be merged as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(Backbone.View.prototype, Backbone.Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName : 'div',

    // Attach the `selectorDelegate` function as the `$` property.
    $       : selectorDelegate,

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize : function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render : function() {
      return this;
    },

    // Remove this view from the DOM. Note that the view isn't present in the
    // DOM by default, so calling this method may be a no-op.
    remove : function() {
      $(this.el).remove();
      return this;
    },

    // For small amounts of DOM Elements, where a full-blown template isn't
    // needed, use **make** to manufacture elements, one at a time.
    //
    //     var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
    //
    make : function(tagName, attributes, content) {
      var el = document.createElement(tagName);
      if (attributes) $(el).attr(attributes);
      if (content) $(el).html(content);
      return el;
    },

    // Set callbacks, where `this.callbacks` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save'
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    // This only works for delegate-able events: not `focus`, `blur`, and
    // not `change`, `submit`, and `reset` in Internet Explorer.
    delegateEvents : function(events) {
      if (!(events || (events = this.events))) return;
      if (_.isFunction(events)) events = events.call(this);
      $(this.el).unbind('.delegateEvents' + this.cid);
      for (var key in events) {
        var method = this[events[key]];
        if (!method) throw new Error('Event "' + events[key] + '" does not exist');
        var match = key.match(eventSplitter);
        var eventName = match[1], selector = match[2];
        method = _.bind(method, this);
        eventName += '.delegateEvents' + this.cid;
        if (selector === '') {
          $(this.el).bind(eventName, method);
        } else {
          $(this.el).delegate(selector, eventName, method);
        }
      }
    },

    // Performs the initial configuration of a View with a set of options.
    // Keys with special meaning *(model, collection, id, className)*, are
    // attached directly to the view.
    _configure : function(options) {
      if (this.options) options = _.extend({}, this.options, options);
      for (var i = 0, l = viewOptions.length; i < l; i++) {
        var attr = viewOptions[i];
        if (options[attr]) this[attr] = options[attr];
      }
      this.options = options;
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` proeprties.
    _ensureElement : function() {
      if (!this.el) {
        var attrs = this.attributes || {};
        if (this.id) attrs.id = this.id;
        if (this.className) attrs['class'] = this.className;
        this.el = this.make(this.tagName, attrs);
      } else if (_.isString(this.el)) {
        this.el = $(this.el).get(0);
      }
    }

  });

  // The self-propagating extend function that Backbone classes use.
  var extend = function (protoProps, classProps) {
    var child = inherits(this, protoProps, classProps);
    child.extend = this.extend;
    return child;
  };

  // Set up inheritance for the model, collection, and view.
  Backbone.Model.extend = Backbone.Collection.extend =
    Backbone.Router.extend = Backbone.View.extend = extend;

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PATCH',
    'delete': 'DELETE',
    'read'  : 'GET'
  };

  // Backbone.sync
  // -------------

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, uses makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
  // `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default JSON-request options.
    var params = _.extend({
      type:         type,
      dataType:     'json'
    }, options);

    // Ensure that we have a URL.
    if (!params.url) {
      params.url = getUrl(model) || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!params.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(model.toJSON());
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (Backbone.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data        = params.data ? {model : params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (Backbone.emulateHTTP) {
      if (type === 'PUT' || type === 'DELETE') {
        if (Backbone.emulateJSON) params.data._method = type;
        params.type = 'POST';
        params.beforeSend = function(xhr) {
          xhr.setRequestHeader('X-HTTP-Method-Override', type);
        };
      }
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !Backbone.emulateJSON) {
      params.processData = false;
    }

    // Make the request.
    return $.ajax(params);
  };

  // Helpers
  // -------

  // Shared empty constructor function to aid in prototype-chain creation.
  var ctor = function(){};

  // Helper function to correctly set up the prototype chain, for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var inherits = function(parent, protoProps, staticProps) {
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call `super()`.
    if (protoProps && protoProps.hasOwnProperty('constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Inherit class (static) properties from parent.
    _.extend(child, parent);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Add static properties to the constructor function, if supplied.
    if (staticProps) _.extend(child, staticProps);

    // Correctly set child's `prototype.constructor`.
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Helper function to get a URL from a Model or Collection as a property
  // or as a function.
  var getUrl = function(object) {
    if (!(object && object.url)) return null;
    return _.isFunction(object.url) ? object.url() : object.url;
  };

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(onError, model, options) {
    return function(resp) {
      if (onError) {
        onError(model, resp, options);
      } else {
        model.trigger('error', model, resp, options);
      }
    };
  };

  // Helper function to escape a string for HTML rendering.
  var escapeHTML = function(string) {
    return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
  };

}).call(this);
/*



 */
 ;(function($) {
  'use strict';
  Backstop.Charts = (Backstop.Charts || {});
  var Charts = Backstop.Charts;

  Charts.Accounts = Backbone.Model.extend({
    url:  function() { return this.get( 'url' ); },
    save: function() { throw new Error( 'Attempt to mutate Chart model.' ); },
    title: function() { return 'Accounts'; },
    seriesData: function() {
      var fund_summary = {};
      var account_currency_symbol;
      _.map( this.get( 'rows' ), function( account, i ) {
        var product_name = account.product_name;
        if ( _.isUndefined( fund_summary[product_name] ) ) {
          fund_summary[product_name] = 0;
        }

        fund_summary[product_name] += Math.max(account.current_value_raw, 0);
        account_currency_symbol = account.current_value_currency_symbol;
      });

      var product_names = _.keys( fund_summary );
      var total = _.reduce(_.values( fund_summary ), function( memo, value ) {
        return memo + value;
      }, 0);

      var outer = _.map( this.get( 'rows' ), function( account, i ) {
        var brightness = i / product_names.length * 0.02;

        return {
          name:  account.name,
          currency_symbol: account.current_value_currency_symbol,
          y:     Math.max(account.current_value_raw / total, 0),
          value: Math.max(account.current_value_raw, 0),
          parentIndex: product_names.indexOf( account.product_name ),
          brightness:   brightness
        };
      });
      outer = outer.sort( function( a, b ) {
        return a.parentIndex - b.parentIndex;
      });

      var top = _.map(_.keys(fund_summary), function( product_name, i ) {
        var name  = product_name;
        var value = fund_summary[product_name];

        return {
          name:  name,
          y:     Math.max(value / total, 0),
          value: Math.max(value.toFixed( 2 ), 0),
          currency_symbol: account_currency_symbol
        };
      });

      return [top, outer];
    },

    parse: function( resp ) {
      return resp;
    }
  });
}(undefined));
/*



 */
;(function ($) {
  'use strict';
  Backstop.Charts = (Backstop.Charts || {});
  var Charts = Backstop.Charts;

  function participantsFrom( assetType, i ) {
    var series = [];

    _.each( assetType.participants, function( p, j ) {
      if (p.participants.length > 0) {
        series = series.concat( participantsFrom( p, i ) );
      } else {
        series.push({
          plain_name: p.name,
          name: p.name,
          y: Math.max(p.percent_of_group, 0),
          value: p.plain_amount,
          parentIndex: i,
          brightness: 0.2 - j / assetType.participants.length / 5
        });
      }
    });

    return series;
  }

  Charts.AssetGroupParticipantContributions = Backbone.Model.extend({
    url:  function() { return this.get( 'url' ); },
    save: function() { throw new Error( 'Attempt to mutate Chart model.' ); },
    title: function() { return 'Asset Type Contributions'; },

    seriesData: function() {
      var participant_series = [];
      var top_level_series = _.map( this.get( 'types' ), function( t, i ) {
        participant_series = participant_series.concat( participantsFrom( t, i ) );

        return {
          name: t.name,
          y: Math.max(t.percent_of_group, 0),
          value: t.plain_amount
        };
      });

      return [top_level_series, participant_series];
    },

    parse: function( resp ) {
      return resp.asset_group;
    }
  });
}(undefined));
/*



 */
;(function($) {
  'use strict';
  Backstop.Charts = (Backstop.Charts || {});
  var Charts = Backstop.Charts;

  Charts.Holdings = Backbone.Model.extend({
    url:  function() { return this.get( 'url' ); },
    save: function() { throw new Error( 'Attempt to mutate Chart model.' ); },
    title: function() { return 'Holdings'; },
    seriesData: function() {
      var inner_asset_type_summary = {};
      var inner_asset_type_currency_symbol;
      _.map( this.get( 'rows' ), function( holding, i ) {
        var type = holding.asset_type || holding.type;
        if ( _.isUndefined( inner_asset_type_summary[type] ) ) {
          inner_asset_type_summary[type] = 0;
        }

        inner_asset_type_summary[type] += Math.max(holding.value, 0);
        inner_asset_type_currency_symbol = holding.currency_symbol;
      });

      var types = _.keys( inner_asset_type_summary );
      var total = _.reduce(_.values( inner_asset_type_summary ), function( memo, value ) {
        return memo + value;
      }, 0);

      var outer = _.map( this.get( 'rows' ), function( holding, i ) {
        var brightness = i / types.length * 0.02;

        return {
          name:  holding.name,
          plain_name: holding.plain_name,
          currency_symbol: holding.currency_symbol,
          y:     Math.max(holding.value / total, 0),
          value: Math.max(holding.value, 0),
          parentIndex: types.indexOf( holding.asset_type || holding.type ),
          brightness:   brightness
        };
      });
      outer = outer.sort( function( a, b ) {
        return a.parentIndex - b.parentIndex;
      });

      var top = _.map(_.keys(inner_asset_type_summary), function( type, i ) {
        var name  = type;
        var value = inner_asset_type_summary[type];

        return {
          name:  name,
          y:     Math.max(value / total, 0),
          value: Math.max(value.toFixed( 2 ), 0),
          currency_symbol: inner_asset_type_currency_symbol
        };
      });

      return [top, outer];
    },

    parse: function( resp ) {
      return resp;
    }
  });
}(undefined));
/*



 */
// This is a data model that groups and totals rows with the same name for the
// outer and inner rings.
//
// In order to make use of this model, you need to have the following fields
// available on the rows:
//
// 'strategy' will be the inner circle
// 'sub-strategy' will be the outer circle
// 'current value (usd)' will be the field used for values (this needs to be a float or integer)
//
// Developer Note:  Variable names are currently specific to the use case this
// was developed for, but this can and should be genericized by
// making the above three field names configurable.
;(function($) {
  'use strict';
  Backstop.Charts = (Backstop.Charts || {});
  var Charts = Backstop.Charts;

  Charts.TwoTierTotal = Backbone.Model.extend({
    url:  function() { return this.get( 'url' ); },
    save: function() { throw new Error( 'Attempt to mutate Chart model.' ); },
    title: function() { return 'Holdings'; },
    construct_asset_type_summary: function() {
      var asset_type_summary = {};
      _.map( this.get( 'rows' ), function( holding, i ) {
        var strategy = holding.strategy;
        if ( _.isUndefined( asset_type_summary[strategy] ) ) {
          asset_type_summary[strategy] = {};
          asset_type_summary[strategy].total = 0;
        }

        if ( _.isUndefined( asset_type_summary[strategy][holding.sub_strategy] ) ) {
          asset_type_summary[strategy][holding.sub_strategy] = 0;
        }

        if ( holding.current_value_usd.match(/\(.*\)/) ) {
          holding.current_value_usd = '0';
        }

        asset_type_summary[strategy].total += Math.max(holding.current_value_usd, 0);
        asset_type_summary[strategy][holding.sub_strategy] += Math.max(holding.current_value_usd, 0);
      });
      return asset_type_summary;
    },
    construct_outer: function(asset_type_summary, currency_symbol) {
      var total = this.construct_total(asset_type_summary);
      var strategies = _.keys( asset_type_summary );

      var unsorted_outer = _.map( strategies, function( strategy, strategy_index ) {
        var sub_strategies = _.without( _.keys( asset_type_summary[strategy] ), 'total' );

        return _.map( sub_strategies, function( sub_strategy, sub_strategy_index ) {
          var brightness = (strategy_index + sub_strategy_index) / strategies.length * 0.25;
          return {
            name:  sub_strategy,
            plain_name: sub_strategy,
            currency_symbol: currency_symbol,
            y:     Math.max(asset_type_summary[strategy][sub_strategy] / total, 0),
            value: Math.max(asset_type_summary[strategy][sub_strategy], 0),
            parentIndex: strategies.indexOf( strategy ),
            brightness:   brightness
          };
        });
      });

      return _.flatten( unsorted_outer ).sort( function( a, b ) {
        return a.parentIndex - b.parentIndex;
      });
    },
    construct_total: function(asset_type_summary) {
      return _.reduce(_.values( asset_type_summary ), function( memo, value ) {
        return memo + value.total;
      }, 0);
    },
    contruct_inner: function(asset_type_summary, currency_symbol) {
      var total = this.construct_total(asset_type_summary);

      return _.map(_.keys(asset_type_summary), function( type, i ) {
        var name  = type;
        var value = asset_type_summary[type].total;

        return {
          name:  name,
          y:     Math.max(value / total, 0),
          value: Math.max(value.toFixed( 2 ), 0),
          currency_symbol: currency_symbol
        };
      });
    },
    seriesData: function() {
      var asset_type_summary = this.construct_asset_type_summary();
      var currency_symbol = '$';
      var outer = this.construct_outer(asset_type_summary, currency_symbol);
      var inner = this.contruct_inner(asset_type_summary, currency_symbol);

      return [inner, outer];
    },

    parse: function( resp ) {
      return resp;
    }
  });
}(undefined));
/*



 */
;(function($) {
  'use strict';
  Backstop.Charts = (Backstop.Charts || {});
  var Charts = Backstop.Charts;

  Backstop.Charts.innerDataDefaultTemplate = '<b>{{{name}}}</b>';
  Backstop.Charts.outerDataDefaultTemplate = '<b>{{{displayName}}}</b><br/>' +
                                             '{{{currencySymbol}}}{{{value}}}';
  Backstop.Charts.toolTipDefaultTemplate = '<b>{{{displayName}}}</b><br/>' +
                                           '{{{currencySymbol}}}{{{value}}}<br/>' +
                                           '{{{percentOfGroup}}}';

  function pointDataValues( point, y ) {
    var displayName;
    if ( 'plain_name' in point ) {
      if ( ( point.plain_name.length ) >= 40) {
        displayName =  ( point.plain_name ).substr( 0, 37 ) + '. . .';
      } else {
        displayName =  point.plain_name;
      }
    } else {
      displayName = point.name;
    }
    var currencySymbol = point.currency_symbol || '$';
    var value = point.value || y;
    var percentOfGroup = '' + ( y * 100 ).toFixed( 2 ) + '%';
    return {
      name: point.name,
      displayName: displayName,
      currencySymbol: currencySymbol,
      value: Highcharts.numberFormat( value, 2, '.', ',' ),
      percentOfGroup: percentOfGroup
    };
  }

  Charts.Pie = Backbone.View.extend({
    initialize: function( options ) {
      this.model.bind( 'all', this.render, this );
      this.targetId = options.targetId || 'pie-chart';
      this.title = options.title || '';
      this.width = parseInt( options.width ) || null;
      this.height = parseInt( options.height ) || null;
      this.colorInner = options.colorInner || 'white';
      this.colorOuter = options.colorOuter || 'grey';
      this.borderWidth = parseInt( options.borderWidth ) || 0;
      this.borderColor = options.borderColor || 'black';
      this.borderRadius = parseInt( options.borderRadius ) || 0;
      this.backgroundColor = options.backgroundColor || 'white';
      this.plotBackgroundColor = options.plotBackgroundColor || options.backgroundColor;
      this.fontFamily = options.fontFamily || 'inherit !important';
      this.colors = options.colors || Highcharts.getOptions().colors;
      this.innerDataTemplate = options.innerDataTemplate || Backstop.Charts.innerDataDefaultTemplate;
      this.outerDataTemplate = options.outerDataTemplate || Backstop.Charts.outerDataDefaultTemplate;
      this.toolTipTemplate = options.toolTipTemplate || Backstop.Charts.toolTipDefaultTemplate;
      this.innerRingOnly = options.innerRingOnly || false;
      this.innerLabelPosition = parseInt( options.innerLabelPosition ) || -30;
    },

    render: function() {
      var series = this.colorize( this.model.seriesData() );
      var $target = $('#' + this.targetId);

      Highcharts.setOptions({
        lang: { contextButtonTitle: I18n.t('charts.export_chart') }
      });
      var seriesHighchartOption;
      if (this.innerRingOnly === true) {
        seriesHighchartOption = [
          {
            data: series[0],
            size: '65%',
            dataLabels: {
              formatter: this.dataFormatter( this.innerDataTemplate, 0.01),
              color: this.colorInner,
              distance: this.innerLabelPosition
            }
          }];
      } else {
        seriesHighchartOption = [
          {
            data: series[0], size: '65%',
            dataLabels: {
              formatter: this.dataFormatter( this.innerDataTemplate ),
              color: this.colorInner,
              distance: this.innerLabelPosition
            }
          },
          {
            data: series[1],
            size: '80%',
            innerSize: '65%',
            dataLabels: {
              formatter: this.dataFormatter(this.outerDataTemplate, 0.01),
              color: this.colorOuter,
              distance: 30
            }
          }
        ];
      }


      this.chart = new Highcharts.Chart({
        chart: {
          renderTo: this.targetId,
          width:  this.width,
          height: this.height,
          type: 'pie',
          borderColor: this.borderColor,
          borderWidth: this.borderWidth,
          borderRadius: this.borderRadius,
          backgroundColor: this.backgroundColor,
          plotBackgroundColor: this.plotBackgroundColor,

          style: {
            fontFamily: this.fontFamily
          }
        },
        plotOptions: {
          pie: { shadow: false }
        },
        title: { text: this.title } ,
        yAxis:  { title: { text: this.title } },
        exporting:  {
          fallbackToExportServer: false
        },
        credits: { enabled: false },
        tooltip: {
          formatter: this.tooltipFormatter( this.toolTipTemplate )
        },
        series: seriesHighchartOption
      });
    },

    colorsByIndex: function( index ) {
      index = index % this.colors.length;
      return this.colors[ index ];
    },

    colorize: function( series ) {
      var self = this;
      var series_1 = series[0];
      var series_2 = series[1];
      var firstAndLastColorTheSame = series_1.length === (this.colors.length + 1);

      series_1 = _.map( series_1, function( d, i ) {
        // To avoid two of the same color next to each other
        var lastInSeries = i === (series_1.length - 1);
        var colorIndex = ( firstAndLastColorTheSame && lastInSeries ) ? i + 1 : i;
        d.color = self.colorsByIndex( colorIndex );
        return d;
      });

      series_2 = _.map( series_2, function( d, i ) {
        // To avoid two of the same color next to each other
        var lastInSeries = d.parentIndex == (series_1.length - 1);
        var colorIndex = ( firstAndLastColorTheSame && lastInSeries ) ? d.parentIndex + 1 : d.parentIndex;
        var baseColor = self.colorsByIndex( colorIndex );
        d.color = Highcharts.Color( baseColor ).brighten( d.brightness ).get();
        return d;
      });

      return [series_1, series_2];
    },

    dataFormatter: function( template, min ) {
      return function() {
        if ( this.y < ( min || 0.2 ) ) {
          return null;
        }
        return $.mustache( template, pointDataValues( this.point, this.y ) );
      };
    },

    tooltipFormatter: function( template ) {
      return function() {
        return $.mustache( template, pointDataValues( this.point, this.y ) );
      };
    }
  });

  $(function() {
    $('.js-pie-chart').each( function() {
      var $this = $(this);
      var modelType = $this.data('model');
      var url = $this.data('url');
      var targetId = $this.attr('id');
      var title = $this.data('title');
      var width = $this.data('width');
      var height = $this.data('height');
      var borderColor = $this.data('border-color');
      var colorInner = $this.data('color-inner');
      var colorOuter = $this.data('color-outer');
      var borderRadius = $this.data('border-radius');
      var backgroundColor = $this.data('background-color');
      var plotBackgroundColor = $this.data('plot-background-color');
      var fontFamily = $this.data('font-family');
      var innerDataTemplate = $this.data('inner-data-template');
      var outerDataTemplate = $this.data('outer-data-template');
      var toolTipTemplate = $this.data('tool-tip-template');
      var innerRingOnly = $this.data('inner-ring-only');
      var innerLabelPosition = $this.data('inner-label-position');



      var colors;
      if ($this.attr('data-colors')) {
        colors = $this.data('colors').split(',');
      }

      var model = new Backstop.Charts[modelType]({
        url: url
      });

      model.fetch();

      new Backstop.Charts.Pie({
        model: model,
        targetId: targetId,
        title: title,
        height: height,
        width: width,
        borderColor: borderColor,
        colorInner: colorInner,
        colorOuter: colorOuter,
        borderRadius: borderRadius,
        backgroundColor: backgroundColor,
        plotBackgroundColor: plotBackgroundColor,
        fontFamily: fontFamily,
        colors: colors,
        innerDataTemplate: innerDataTemplate,
        outerDataTemplate: outerDataTemplate,
        toolTipTemplate: toolTipTemplate,
        innerRingOnly: innerRingOnly,
        innerLabelPosition: innerLabelPosition
      });
    });
  });
}(window.jQuery));
/**
 * Backstop Charts Manifest
 *


 *

 */;
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: https://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
if ( !Array.prototype.forEach ) {

  Array.prototype.forEach = function forEach( callback, thisArg ) {

    var T, k;

    if ( this == null ) {
      throw new TypeError( "this is null or not defined" );
    }

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0; // Hack to convert O.length to a UInt32

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: https://es5.github.com/#x9.11
    if ( {}.toString.call(callback) !== "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if ( thisArg ) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k < len
    while( k < len ) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if ( Object.prototype.hasOwnProperty.call(O, k) ) {

        // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
        kValue = O[ k ];

        // ii. Call the Call internal method of callback with T as the this value and
        // argument list containing kValue, k, and O.
        callback.call( T, kValue, k, O );
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some)
{
  Array.prototype.some = function(fun /*, thisArg */)
  {
    'use strict';

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function')
      throw new TypeError();

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t && fun.call(thisArg, t[i], i, t))
        return true;
    }

    return false;
  };
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
if (!Array.prototype.map) {

  Array.prototype.map = function(callback/*, thisArg*/) {

    var T, A, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the |this| 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal 
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: https://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = arguments[1];
    }

    // 6. Let A be a new array created as if by the expression new Array(len) 
    //    where Array is the standard built-in constructor with that name and 
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal 
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal 
        //     method of callback with T as the this value and argument 
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
if (!Function.prototype.bind) (function(){
  var ArrayPrototypeSlice = Array.prototype.slice;
  Function.prototype.bind = function(otherThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var baseArgs= ArrayPrototypeSlice .call(arguments, 1),
        baseArgsLength = baseArgs.length,
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          baseArgs.length = baseArgsLength; // reset to default base arguments
          baseArgs.push.apply(baseArgs, arguments);
          return fToBind.apply(
                 fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
          );
        };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
})();

// Using UMD pattern from
// https://github.com/umdjs/umd#regular-module
// `returnExports.js` version
;(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(["i18n"], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    factory(require("i18n"));
  } else {
    // Browser globals (root is window)
    factory(root.I18n);
  }
}(this, function(I18n) {
  "use strict";

  I18n.translations = {"account-list":{},"ar":{},"black-river":{},"crestlineinvestors":{},"data-room":{},"de":{},"document-library":{},"eeadvisors":{},"en":{},"es":{},"florincourt":{},"fr":{},"gtispartners-pt":{},"hedgeserv":{},"it":{},"ja":{},"jasperridge":{},"juntocap":{},"km":{},"maltesecap":{},"mcp-am":{},"newharborcap":{},"nl":{},"omega-pt":{},"persq":{},"pl":{},"pt":{},"pt-BR":{},"pt-PT":{},"ro":{},"ru":{},"spanish":{"account_pretty_name":"Cuenta","accounts_pretty_name":"Cuentas","activerecord":{"attributes":{"form":{"send_to":"Email Recipient"},"group":{"identifier":"Name"},"owner":{"bcc_email_address":"Email address that recieves a copy of all emails sent from InvestorBridge","incoming_email_address":"Email from this site for you will be sent to","outgoing_email_address":"When this site sends email to users, the \"From\" address will be","outgoing_email_name":"When this site sends email to users, the \"From\" name will be"},"page":{"name":"Short URL","template":"Template File"},"user":{"identifier":"Email"}},"errors":{"messages":{"record_invalid":"Validation failed: %{errors}","restrict_dependent_destroy":{"has_many":"Cannot delete record because dependent %{record} exist","has_one":"Cannot delete record because a dependent %{record} exists"}},"models":{"account_value":{"attributes":{"investment_id":{"taken":"You cannot save more than one account value to the same account for the same period"}}},"document":{"attributes":{"filename":{"blank":"must be present for each Document"}}},"page":{"attributes":{"name":{"no_forward_slashes":"'%{name}' can not contan a forward slash.","no_route_clobber":"'%{name}' is already used by the system. Please choose another Short URL for the page.","not_just_numeric":"'%{name}' must contain non-numeric characters.","taken":"has already been taken. Please choose another name."},"title":{"taken":"has already been taken. Please choose another title."}}},"tag":{"attributes":{"display_name":{"taken":"More than one tag with the display name: '%{value}'"},"name":{"taken":"More than one tag with the name: '%{value}'"}}},"user_session":{"bad_login":"<br/>Combinación de correo electrónico y la contraseña no se ha encontrado.<br/><br/>\nSi sigues teniendo problemas para ingresar, por favor <a href='%{password_reset_url}'>cambiar su contraseña aquí</a>.<br/><br/>\n","inactive_login":"La cuenta de usuario no se ha activado todavía. Por favor, póngase en contacto con el administrador del sitio para obtener ayuda."}}},"models":{"fund":"Producto","hedge_fund":"Fondo de Cobertura"}},"asset_details":{"Asset Group Name":"Nombre de Ventaja","Benchmark A":"Punto de Referencia A","Benchmark A Name":"Nombre del Punto de Referencia A","Benchmark A Symbol":"Símbolo de Punto de Referencia A","Benchmark B":"Punto de Referencia B","Benchmark B Name":"Nombre del Punto de Referencia B","Benchmark B Symbol":"Símbolo de Punto de Referencia B","Benchmark C":"Punto de Referencia C","Benchmark C Name":"Nombre del Punto de Referencia C","Benchmark C Symbol":"Símbolo de Punto de Referencia C","Benchmark D":"Punto de Referencia D","Benchmark D Name":"Nombre del Punto de Referencia D","Benchmark D Symbol":"Símbolo de Punto de Referencia D","Benchmark E":"Punto de Referencia E","Benchmark E Name":"Nombre del Punto de Referencia E","Benchmark E Symbol":"Símbolo de Punto de Referencia E","Benchmark F":"Punto de Referencia F","Benchmark F Name":"Nombre del Punto de Referencia F","Benchmark G":"Punto de Referencia G","Benchmark G Name":"Nombre del Punto de Referencia G","Benchmark H":"Punto de Referencia H","Benchmark H Name":"Nombre del Punto de Referencia H","Currency Code":"Código de moneda","Current Month Compounded Return":"Mes Compuesto Retorno","Current Value":"Presente actual","LTD Compounded Return":"Vida hasta la fecha de retorno compuesta","LTD IRR":"Vida hasta la fecha la tasa interna de retorno","LTD Total Invested Over Period":"Vida hasta la fecha la inversión total durante el período","LTD Total Redeemed Over Period":"Vida al total de fecha redimidos durante el período","QTD Compounded Return":"Trimestre hasta la fecha de retorno compuesta","Risk Free Benchmark":"Punto de referencia libre de riesgo","YTD Compounded Return":"Año hasta la fecha de retorno compuesta"},"asset_type":"Tipo de Ventaja","assetgroup_pretty_name":"Ventaja","attachable":"Documentos","attachable_pretty_name":"Documento","attachable_types":{"Call":"Llamar","Document":"Documento","Email":"Email","Meeting":"Reunión","Note":"Nota"},"attachables":{"apply":"Aplicar","associated_with":"Asociado Con","attachments":"Acoplamiento","attendees":"Los Asistentes","clear":"Despejar","correspondence":"Correspondencia","date":"Date","direct_link":"enlace directo","effective_date":"Fecha","from":"Desde","hide_advanced":"Ocultar Avanzada","import_date":"Importe Fecha","imported_during":"Correspondencia importado durante los días más recientes %{calendar_days}.","imported_since":"importado desde","location":"Ubicación","recent":"Reciente","recent_correspondence":"Correspondencia reciente","search_by_association":"Buscar por Asociación","search_by_date":"Buscar por Fecha","set":"Fijarse","show_advanced":"Mostrar Avanzada","title":"Título","to":"Hasta","type":"Tipo","view_all_tags":"Ver Todos los Tipos de Correspondencia","viewed_by":"Visto por"},"author_pretty_name":"User","call_pretty_name":"Llamada","charts":{"distibution_title":"Distribution of Returns Chart","distribution_title":"Distribución de Gráficos Rentabilidad","export_chart":"Gráfico de Exportaciones","frequency":"Frecuencia (meses)","monthly_returns":"Devoluciones mensuales","value_of_1000":"Valor de las $1000","vami_title":"Valor Agregado Gráfico del índice mensual"},"configuration":{"branch":{"not_found":"A branch file was not found at:%{BRANCH_PATH}"},"revision":{"not_found":"A revision file was not found at:%{REVISION_PATH}"}},"date":{"abbr_day_names":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"abbr_month_names":[null,"ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"day_names":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"formats":{"default":"%Y-%m-%d","long":"%B %d, %Y","long_month_year":"%B %Y","short":"%b %d"},"month_names":[null,"enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"order":[["year","month","day"]]},"date_pretty":"Date","datetime":{"distance_in_words":{"about_x_hours":{"one":"about 1 hour","other":"about %{count} hours"},"about_x_months":{"one":"about 1 month","other":"about %{count} months"},"about_x_years":{"one":"about 1 year","other":"about %{count} years"},"almost_x_years":{"one":"almost 1 year","other":"almost %{count} years"},"half_a_minute":"half a minute","less_than_x_minutes":{"one":"less than a minute","other":"less than %{count} minutes"},"less_than_x_seconds":{"one":"less than 1 second","other":"less than %{count} seconds"},"over_x_years":{"one":"over 1 year","other":"over %{count} years"},"x_days":{"one":"1 day","other":"%{count} days"},"x_minutes":{"one":"1 minute","other":"%{count} minutes"},"x_months":{"one":"1 month","other":"%{count} months"},"x_seconds":{"one":"1 second","other":"%{count} seconds"}},"prompts":{"day":"Day","hour":"Hour","minute":"Minute","month":"Month","second":"Seconds","year":"Year"}},"devise":{"confirmations":{"confirmed":"Your account was successfully confirmed. You are now signed in.","send_instructions":"You will receive an email with instructions about how to confirm your account in a few minutes.","send_paranoid_instructions":"If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."},"failure":{"already_authenticated":"You are already signed in.","inactive":"Invalid email or password.","invalid":"Invalid email or password.","invalid_token":"Invalid authentication token.","last_attempt":"You have one more attempt before your account is locked.","locked":"Your account is locked.","not_found_in_database":"Invalid email or password.","timeout":"Your session expired, please sign in again to continue.","unauthenticated":"You need to sign in or sign up before continuing.","unconfirmed":"You have to confirm your account before continuing."},"mailer":{"confirmation_instructions":{"subject":"Confirmation instructions"},"email_changed":{"subject":"Email Changed"},"password_change":{"subject":"Password Changed"},"reset_password_instructions":{"subject":"Reset password instructions"},"unlock_instructions":{"subject":"Unlock Instructions"}},"omniauth_callbacks":{"failure":"Could not authenticate you from %{kind} because \"%{reason}\".","success":"Successfully authenticated from %{kind} account."},"passwords":{"no_token":"You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided.","send_instructions":"You will receive an email with instructions about how to reset your password in a few minutes.","send_paranoid_instructions":"If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.","updated":"Your password was changed successfully. You are now signed in.","updated_not_active":"Your password was changed successfully."},"registrations":{"destroyed":"Bye! Your account was successfully cancelled. We hope to see you again soon.","signed_up":"Welcome! You have signed up successfully.","signed_up_but_inactive":"You have signed up successfully. However, we could not sign you in because your account is not yet activated.","signed_up_but_locked":"You have signed up successfully. However, we could not sign you in because your account is locked.","signed_up_but_unconfirmed":"A message with a confirmation link has been sent to your email address. Please open the link to activate your account.","update_needs_confirmation":"You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address.","updated":"You updated your account successfully.","updated_but_not_signed_in":"Your account has been updated successfully, but since your password was changed, you need to sign in again."},"sessions":{"already_signed_out":"Signed out successfully.","locked":"Too many unsuccessful logins have been attempted for this username. The account has been temporarily disabled. If you have forgotten your password, please click \"Forgot your Password?\" to immediately reactivate your account.","signed_in":"Signed in successfully.","signed_out":"Signed out successfully."},"unlocks":{"send_instructions":"You will receive an email with instructions about how to unlock your account in a few minutes.","send_paranoid_instructions":"If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.","unlocked":"Your account has been unlocked successfully. Please sign in to continue."}},"drm":{"about_secure_pdf":"About Secure PDFs","about_secure_text":"Este sitio web utiliza un sistema de cifrado de archivos segura para controlar el acceso a ciertos documentos PDF. Para ver un archivo PDF cifrado debe iniciar sesión en el sitio web, y hay que abrirlo con Adobe Reader / Acrobat con el FileOpen plug-in instalado. El plug-in permite a los usuarios FileOpen para ver el PDF, pero limita la capacidad de guardar, imprimir o reenviar una copia legible del archivo.","adobe_link":"descargar Adobe Reader","adobe_text":"Si usted no tiene Adobe Reader / Acrobat, usted tendrá que","document_download":"Documento de Descarga","download_error":"Error(s) ocurrió descarga de este documento","fileopen_link":"descargar FileOpen","fileopen_text1":"Si usted no tiene el plug-in FileOpen,","fileopen_text2":"(Se le solicitará que instale el plug-in cuando se descarga el PDF seguro en primer lugar.)","if_clicking":"Si al hacer clic en el enlace de arriba no se abre el documento, haga clic en el enlace, guardar el documento en su computadora y abrirlo en Adobe Reader / Acrobat. Si continúa teniendo problemas, por favor, lea la configuración y solución de problemas más detalles a continuación.","if_not":"Si no se pruebe este","secure_document_download":"Descargar Documento Secure","start_download":"Empezar a Descargar","taken_to_document":"Usted será llevado a su documento breve"},"email":"Email","email_template":{"blank_template":"Blank Template","general_email":"General Email","password_reset":"Password Reset Email"},"errors":{"format":"%{attribute} %{message}","messages":{"accepted":"must be accepted","already_confirmed":"was already confirmed, please try signing in","blank":"can't be blank","confirmation":"doesn't match %{attribute}","confirmation_period_expired":"needs to be confirmed within %{period}, please request a new one","email":"is not a valid email address","empty":"can't be empty","equal_to":"must be equal to %{count}","even":"must be even","exclusion":"is reserved","expired":"has expired, please request a new one","greater_than":"must be greater than %{count}","greater_than_or_equal_to":"must be greater than or equal to %{count}","inclusion":"is not included in the list","invalid":"is invalid","less_than":"must be less than %{count}","less_than_or_equal_to":"must be less than or equal to %{count}","model_invalid":"Validation failed: %{errors}","not_a_number":"is not a number","not_an_integer":"must be an integer","not_found":"not found","not_locked":"was not locked","not_saved":{"one":"1 error prohibited this %{resource} from being saved:","other":"%{count} errors prohibited this %{resource} from being saved:"},"odd":"must be odd","other_than":"must be other than %{count}","present":"must be blank","required":"must exist","taken":"has already been taken","too_long":{"one":"is too long (maximum is 1 character)","other":"is too long (maximum is %{count} characters)"},"too_short":{"one":"is too short (minimum is 1 character)","other":"is too short (minimum is %{count} characters)"},"url":"is not a valid URL","wrong_length":{"one":"is the wrong length (should be 1 character)","other":"is the wrong length (should be %{count} characters)"}}},"excel_export":{"button_text":"Export to Excel","link_text":"Export to Excel"},"flash":{"actions":{"create":{"notice":"%{resource_name} was successfully created."},"destroy":{"alert":"%{resource_name} could not be destroyed.","notice":"%{resource_name} was successfully destroyed."},"update":{"notice":"%{resource_name} was successfully updated."}}},"formats":{"date":"%m-%d-%Y","datetime":"%m-%d-%Y %I:%M%p %Z","na":"N/A","time":"%I:%M%p"},"formsubmission_pretty_name":"Submitted Document","formsubmitted_pretty_name":"Documento Presentado","fund_details":{"Accepting New Investments":"Aceptando Nuevas Inversiones","Additional Investment":"Inversión Adicional","Clawback":"Clawback","Date Closed":"Fecha de cierre","Gate":"Entrada","Gate Percent":"Entrada Porcentaje","High Water Mark":"Cota máxima","High Water Terms":"Términos cota máxima","Hurdle Rate":"Tasa Hurdle","Hurdle Terms":"Términos Hurdle","Incentive Fee Percent":"Porcentaje Cuota de Incentivos","Inception Date":"Creación del fondo","Initial Lockup Months":"Initial Lockup Months","Ltd Compounded Return":"Primeros meses Lockup","Management Fee Percent":"Gestión Porcentaje Fee","Maximum Side Pocket Percent":"Porcentaje máximo bolsillo lateral","Minimum Investment":"La inversión mínima","Offering Memorandum Date":"Ofreciendo Fecha Memorando","Other Fees":"Otros Costos","Redemption Fee":"Comisión de reembolso","Redemption Notice":"Aviso redención","Redemptions":"Redención","Regional Focus":"Enfoque regional","Registration Type":"Registro de tipo","Sales Fee":"Cuota de ventas","Sector Industry":"Sector de la industria","Side Pocket":"Bolsillo lateral","Soft Lockup":"Bloqueo blando","Soft Lockup Months":"Mes suaves con bloqueo","Subscriptions":"Suscripciones","Us Taxable":"Estados Unidos Imponible","Use Of Leverage":"El uso de apalancamiento","Uses Leverage":"Utiliza apalancamiento","Ytd Compounded Return":"Retorno a la fecha mezclado"},"fund_pretty_name":"Fondos","fund_values_pretty_name":"Los valores de fondos","funds":{"fund_size":"Fund Size","regional_focus":"Regional Focus","vintage_year":"Vintage Year"},"funds_pretty_name":"Fondos","group_pretty_name":"Grupo","hedgefund_details":{"12 Month Rolling Compounded Return":"12 meses rodando retorno agravado","24 Month Largest Drawdown":"24 meses drawdown más grande","24 Month Rolling Compounded Return":"24 meses rodando retorno agravado","24 Month Standard Deviation":"24 meses desviación estándar","3 Month Rolling Compounded Return":"3 meses rodando retorno agravado","6 Month Rolling Compounded Return":"6 meses rodando retorno agravado","Asset Type":"Tipo de Ventaja","Backstop Id":"Backstopo Identificación","Benchmark A Name":"Nombre del Punto de Referencia A","Benchmark A Symbol":"Símbolo de Punto de Referencia A","Benchmark B Name":"Nombre del Punto de Referencia B","Benchmark B Symbol":"Símbolo de Punto de Referencia B","Currency":"Dinero corriente","Description":"Description","Firm AUM":"Sus activos bajo gestión","Fund Manager":"La administradora de fondos","Incentive Fee":"Cuota de incentivo","Inception Date":"Creación del fondo","Investment Details":"detalles de la inversión","Is Product?":"¿Es el producto?","Management Company":"Gestión de la empresa","Management Fee":"Honorarios de dirección","Manager Bio":"Gerente biografía","Tracked Since":"Desde orugas"},"hedgefund_pretty_name":"Fondo de Cobertura","hedgefundholding_pretty_name":"Hedge Fund Holding","helpers":{"select":{"prompt":"Please select"},"submit":{"create":"Create %{model}","submit":"Save %{model}","update":"Update %{model}"}},"holding_pretty_name":"Participación","holdings_pretty_name":"Participacións","home":{"jumbotron":{"blurb_html":"With a thought leader in real assets <br/>\ninvestment management in the Americas\n","explore":"Explore"}},"instructions":{"search_attachable":"Por favor, elija el tipo de documento que desea ver en el menú desplegable. Al hacer clic en el icono de la lupa en la superficie para documentos para abrir las opciones de búsqueda. Al hacer clic en el calendario de la tabla documento se abrirá un filtro de fecha."},"investment_details":{"Annualized IRR":"Tasa anualizada de rendimiento interno","Annualized Return":"Rentabilidad anualizada","Annualized Standard Deviation":"Desviación estándar anualizada","Average Monthly Gain":"Ganancia mensual promedio","Average Monthly Loss":"Pérdida mensual promedio","Current Month % Of Profitable Months":"% Mes de meses Rentables","Current Month Annualized Return":"Mes Actual Anualizado Retorno","Current Month Average Gain":"Mes en curso ganancia media","Current Month Average Loss":"Mes Pérdida promedio","Current Month IRR":"Mes Esta tasa interna de retorno","Earnings":"Ganancias","Gate":"Recaudación","Hedge Fund":"Fondo de Cobertura","Incentive Fee":"Cuota de incentivo","Investor Since":"Ya que los inversores","LTD Alpha":"Vida hasta la fecha Alfa","LTD Beta":"Vida hasta la fecha beta","LTD Compound":"Vida hasta la fecha suma","LTD Correlation":"La vida de correlación Fecha (r)","LTD Earnings":"Vida a fecha de ganancia","LTD Sharpe Ratio":"Vida hasta la fecha Ratio de Sharpe","LTD Sortino Ratio":"Vida hasta la fecha Ratio de Sortino","Last Valuation":"Última valoración","Management Fee":"Honorarios de dirección","Maximum Drawdown":"Máxima pérdida del período","Maximum Side Pocket":"Bolsillo lateral máximo","Percent of Portfolio":"Porcentaje de la cartera","Profitable Percentage":"Porcentaje rentable","QTD Return":"Trimestre hasta la fecha de retorno","Returns and Risk":"Rentabilidad y riesgo","Total Invested":"Total invertido","Total Redemptions":"Amortizaciones totales","Type":"Tipo","YTD Return":"Años a fecha de regreso"},"investment_pretty_name":"Cuenta","investments":{"10_year_annualized":"10 Años Anualizado","3_year_annualized":"3 Años Anualizado","5_year_annualized":"5 Años Anualizado","account_details":"detalles de la cuenta","account_documents":"Documentos de Cuenta","account_name":"Nombre de la Cuenta","account_values":"Cuenta los valores","accounts_in_fund":"Las cuentas en el Fondo","amount":"Cantidad","appreciation":"Plusvalía","asset_group_name":"Nombre del Ventaja","asset_group_values":"Asset Group Values","asset_types":"Tipos de Ventaja","aum":"Activos Administrados","aum_history":"Bienes en Historia de Gestión","aum_millions":"Los activos bajo gestión (en millones)","benchmark":"Punto de Referencia","breakdown_asset":"Distribución por Tipo de Bien","closing_value":"Closing Value","closing_vlaue":"Cerrando Valor","contributed_amount":"Monto de Contribución","currency":"Dinero Corriente","current_value":"Valor Actual","date_added":"Fecha Alta","date_removed":"Fecha Eliminado","denotes_estimate":"Denota un Estimado","denotes_partial":"Denota un período estimado parcial","details":"Detalles","end_date":"Fecha de Finalización","fees":"Honorarios","fund_name":"Nombre del Fondo","hedge_fund_name":"Nombre del Fondo","hedge_funds":"Fondo de Cobertura","historic_and_aum":"Devoluciones históricos y assests Administrados","historic_performance":"Rendimiento Histórico","holding_name":"Nobre de Participación","investment_values":"Los valores de inversión","investments_by_strategy":"Las inversiones de la estrategia","is_return_estimate":"Es el Regreso un Presupuesto","label_aum":"Assets Under Management (in millions)","label_return":"Returns","ltd":"Vida hasta la fecha","ltd_compounded":"Vida hasta la fecha mezclado","ltd_irr":"Ingresos Netos para el Mes","ltd_return":"Vida Hasta la Fecha de Regreso","ltd_total_redeemed":"Vida al total de fecha redimido","ltd_year_annualized":"La vida a Año Fecha Anualizado","management_company":"Management Company","most_recent_appreciation":"Reconocimiento Neto Más Reciente","most_recent_period":"Período más Reciente","most_recent_return":"Volver Reportado Más Reciente","mtd":"Mes a la Fecha","mtd_compounded":"Mes actual Compuesto","mtd_return":"Mes Fecha de regreso","net_appreciation":"Apreciación Net","net_income_for_month":"Net Income for Month","participant_name":"Nombre del Participante","participant_since":"Desde Participante","participant_type":"Participante Tipo","participants":"Participación","participants_for":"Los participantes de","percent_contribution":"Porcentaje de Contribución","percent_of_group":"Porcentaje del Grupo","performance":"Rendimiento","performance_snapshot":"Desempeño Instantánea","period":"Período","portfolio":"Cartera","portfolio_name":"Cartera de nombres de","private_equity_fund_name":"Private Equity Fund Name","private_equity_funds":"Private Equity Funds","product_name":"Nombre de Producto","prospect_type":"Perspectiva Tipo","prospective_funds":"Fondo prospectivo","qtd":"Trimestre hasta la fecha","qtd_compounded":"Trimestre hasta la fecha mezclado","related_funds":"Fondos Relacionados","reported_return":"Volver Reportado","return":"Regreso","return_history":"Volver Historia","start_date":"Fecha de Inicio","starting_value":"A Partir Valor","stop_date":"Detener Fecha","terms":"Condiciones","total_invested":"Total Invertido","transactions":"Transacciones","underlying_asset":"Activo Subyacente","underlying_type":"Tipo Subyacente","value_as_of":"Valor a partir del","values":"Valores","values_for_fund":"Los valores para el Fondo","values_for_hedge_fund":"Valores para el Fondo","values_for_pe_fund":"Valores para el Fondo","view_accounts":"Ver Cuentas","view_funds":"Ver Fundos","view_hf_details":"Para ver los detalles individuales de fondos de cobertura, haga clic en el nombre del fondo de cobertura","view_hf_holdings":"Ver Hedge Inversiones del Fondo","view_holdings":"Ver Inversiones","view_participants":"Ver participantes","view_pe_funds":"Ver Fundos","view_pe_holdings":"Ver Inversiones de Capital Privado","year":"Año","your_accounts":"Sus cuentas en","ytd":"Año a la Fecha","ytd_compounded":"Año hasta la fecha mezclado","ytd_return":"Retorno a la Fecha"},"long_detail_fields":{"hedge_fund":[],"investment":[]},"managedaccount_pretty_name":"Cuenta Administrado","managedholding_pretty_name":"Participación Administrado","meeting_pretty_name":"Encuentro","messages":{"about_to_lock":"Warning: The next unsuccessful login attempt with this username will temporarily disable the account for %{ban_time} minutes.","bad_login":"<br/>Email and Password combination was not found.<br/><br/>\nIf you continue to have problems logging in please <a href='%{password_reset_url}'>Reset Your Password Here</a><br/><br/>\n","click_to_download":"haga clic para descargar","config_updated":"Configuration updated!","doc_only_import_unavailable":"Documents & Activity import cannot be run until a full import has successfully completed. Please run a full import and try again.","download_problem":"There was a problem with your download. Please try again.","email_sent":"An email has been sent to that address with instructions on how to reset your password.","emails_sent_to":"Emails Were Sent to %{user_count} user(s)","forbidden":"Usted no tiene los permisos adecuados para ver esta página.","form_deleted":"Form on %{page_title} was successfully deleted.","form_disabled":"Form submissions are currently disabled.","form_errors":"Your Form was not saved because of these errors:","form_success":"Form on %{page_title} was successfully created.","form_updated":"Form on %{page_title} was successfully updated.","import_running":"Import already running. Can't run another.","inactive_login":"Your user account has not been activated yet. Please contact your site administrator for assistance.","investment_data_only_import_unavailable":"Investment Data import cannot be run until a full import has successfully completed. Please run a full import and try again.","logged_document":"You must be logged in to view this secure document.","login_banned":"Too many unsuccessful logins have been attempted for this username. The account has been temporarily disabled for %{ban_time} minutes. If you have forgotten your password, please click 'Forgot your Password?' to immediately reactivate your account.","login_required":"Por favor, identifíquese para acceder a la página solicitada.","login_warning":"Warning: The next unsuccessful login attempt with this username will temporarily disable the account for %{ban_time} minutes.","must_be_author":"You must be logged in as an author to view this page","no_permission":"You do not have the proper permissions to view that page.","not_activiated":"Your user account has not been activated yet. Please contact your site administrator for assistance.","password_blank":"Password must not be blank","password_success":"Password successfully updated.","please":"Por favor","pw_reset_expired":"Your password reset link has expired. Please contact your site administrator for assistance.","record_created":"%{record} was created successfully.","record_invalid":"%{record} was not valid.","record_updated":"%{record} was updated successfully.","requires_flash":"Esta página requiere Adobe Flash para cargar documentos.","sent_success":"Your message has been successfully sent.","server_timeout":"InvestorBridge was unable to connect to the background server. Please contact your Backstop Support.","unconfigured_import":"Backstop Import Is Not Configured. Please contact your administrator.","user_inactive":"Previewing is unavailable for inactive users.","user_only_import_unavailable":"User import cannot be run until a full import has successfully completed. Please run a full import and try again.","visibility_failure":"Visibility import failed.","visibility_import_timeout":"Visibility import timed out."},"models":{"account":{"placeholder":{"name":"[Account Name]"}},"document":{"to_s":"Title: %{title}.  Other_id (from Backstop): %{other_id}"}},"month":{"abbr_month_names":[null,"ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"month_names":[null,"enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},"name":"Nombre","navigation":{"admin_home":{"text":"Admin Home","tooltip":"Review Release Notes and Support Documents"},"edit_content":{"text":"Edit Content","tooltip":"Edit Page Content"},"footer":{"privacy_notice":"Privacy Notice","regulatory_information":"Regulatory Information","terms_of_use":"Terms of Use"},"header":{"asset_videos":"Asset Videos","brazil":"Brazil","contact":"Contact","firm":"Firm","firm_profile":"Firm Profile","gallery":"Gallery","income_investments":"Income Investments","infrastructure":"Infrastructure","news":"News","offices":"Offices","opportunity_zones":"Opportunity Zones","our_team":"Our Team","portfolio":"Portfolio","real_estate":"Real Estate","research":"Research","single_family_rental":"Single-Family Rental","strategies":"Strategies","sustainability":"Sustainability","united_states":"United States","us_residential":"US Residential"}},"none":"Ninguno","note_pretty_name":"Nota","number":{"currency":{"format":{"delimiter":",","format":"%u%n","precision":2,"separator":".","significant":false,"strip_insignificant_zeros":false,"unit":"$"}},"format":{"delimiter":",","precision":3,"round_mode":"default","separator":".","significant":false,"strip_insignificant_zeros":false},"human":{"decimal_units":{"format":"%n %u","units":{"billion":"Billion","million":"Million","quadrillion":"Quadrillion","thousand":"Thousand","trillion":"Trillion","unit":""}},"format":{"delimiter":"","precision":3,"significant":true,"strip_insignificant_zeros":true},"storage_units":{"format":"%n %u","units":{"byte":{"one":"Byte","other":"Bytes"},"eb":"EB","gb":"GB","kb":"KB","mb":"MB","pb":"PB","tb":"TB"}}},"nth":{"ordinalized":{},"ordinals":{}},"percentage":{"format":{"delimiter":"","format":"%n%"}},"precision":{"format":{"delimiter":""}}},"organization_pretty_name":"Management Company","parameter_filtering":{"mask":"[U_CAN_NOT_HAZ]"},"password":{"accept_our":"Aceptar la","confirm_password":"Confirme su contraseña","enter_pw":"Introduzca una nueva contraseña","enter_pw_text":"Introduzca una nueva contraseña aquí","fair_def":"Fair - contiene dos de los parámetros anteriores","forgot_password":"¿Olvidó su contraseña?","good_def":"Bueno - contiene cuatro de los parámetros anteriores","has_12":"Cuenta con más de 12 caracteres","has_6":"Cuenta con más de 6 caracteres","includes_lower":"Incluye letras minúscula","includes_numbers":"Inlcludes Números","includes_special":"Incluye caracteres especiales, como @ # $ % ^ & * ? ~ - ( )","includes_upper":"Incluye letras mayúsculas","medium_def":"Medio - contiene tres de los parámetros anteriores","minimum_strength":"El nivel mínimo de fuerza necesaria para la contraseña es","password":"Contraseña","password_confirmation":"Contraseña Confirmación","password_reset":"Restablecimiento de Contraseña","reset_instructions":"Por favor, introduzca su dirección de correo electrónico en el campo de abajo y haga clic en el botón Restablecer contraseña. Un mensaje de invitación nueva contraseña será enviada a su dirección de correo electrónico.","reset_password":"Restablecer contraseña","secure_def":"Asegure - contiene cinco de los parámetros anteriores","strength_indicator":"Este nivel es indicado por la marca en el medidor que aparece una vez que usted comience a escribir en el campo Nueva contraseña","strength_levels":"Los niveles de fuerza y los requisitos de cada uno son","submit":"Presentar","terms_of_use":"Condiciones de uso","user":"Usuario","very_secure_def":"Muy seguro - contiene los seis de los parámetros anteriores","weak_def":"Débil - contiene sólo uno de los parámetros anteriores","what_makes_pw_secure":"¿Qué hace que una contraseña más segura"},"private_equity_fund_pretty_name":"Private Equity Fund","privateequityfund_pretty_name":"Private Equity Fund","privateequityholding_pretty_name":"Private Equity Holding","product_pretty_name":"Producto","quarter":{"names":[null,"Q1","Q2","Q3","Q4"]},"recaptcha":{"errors":{"recaptcha_unavailable":"Captcha servicio está momentáneamente no disponible. Por favor, inténtelo de nuevo en unos minutos.","recaptcha_unreachable":"Oops, we failed to validate your reCAPTCHA response. Please try again.","verification_failed":"El valor de Captcha es incorrecta. Por favor, inténtelo de nuevo."}},"scheduled_tasks":{"type":{"doc_only":"Document Only Import","full_download":"Backstop Import","user_only":"User Only Import"}},"session":{"timeout":{"message":"You have been logged out due to session inactivity."}},"strategy":"Strategy","support":{"array":{"last_word_connector":", and ","two_words_connector":" and ","words_connector":", "}},"system_api":{"ip_regex":"^(192\\.168|127\\.0)\\.\\d+\\.\\d+$"},"time":{"am":"am","formats":{"default":"%a, %d %b %Y %H:%M:%S %z","long":"%B %d, %Y %H:%M","short":"%d %b %H:%M"},"pm":"pm"},"transactions":{"CALL":"Llamar","COMMITMENT":"Compromiso","DISTRIBUTION":"Distribución","PURCHASE":"Comprar","Purchase":"Comprar","REDEEM":"Redimir","Redemption":"Redemption","SUBSCRIPTION":"suscripción","Sale":"Venta","Subscription":"Suscripción","TRANSFER":"Transferir","TRANSFER_PURCHASE":"Transferir Comprar","TRANSFER_SALE":"Transferir Venta"},"user":{"back_to_top":"Volver arriba","login":"Client Login","logout":"Finalizar la Sesión","menu":"Carta","printed_by":"Impreso Por","welcome":"Bienvenido"},"user_pretty_name":"Usuario","will_paginate":{"container_aria_label":"Pagination","next_label":"Next &#8594;","page_aria_label":"Page %{page}","page_entries_info":{"multi_page":"Displaying %{model} %{from} - %{to} of %{count} in total","multi_page_html":"Displaying %{model} <b>%{from}&nbsp;-&nbsp;%{to}</b> of <b>%{count}</b> in total","single_page":{"one":"Displaying 1 %{model}","other":"Displaying all %{count} %{model}","zero":"No %{model} found"},"single_page_html":{"one":"Displaying <b>1</b> %{model}","other":"Displaying <b>all&nbsp;%{count}</b> %{model}","zero":"No %{model} found"}},"page_gap":"&hellip;","previous_label":"&#8592; Previous"},"year":"Año"},"stoltzusa":{},"tr":{},"vi":{},"zh-CN":{},"zh-TW":{}};
}));



var I18n = I18n || {};
I18n.translations = { "en": { "date": { "formats": { "default": "%Y-%m-%d", "short": "%b %d", "long": "%B %d, %Y", "long_month_year": "%B %Y" }, "day_names": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], "abbr_day_names": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "month_names": [null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "abbr_month_names": [null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "order": ["year", "month", "day"] }, "time": { "formats": { "default": "%a, %d %b %Y %H:%M:%S %z", "short": "%d %b %H:%M", "long": "%B %d, %Y %H:%M" }, "am": "am", "pm": "pm" }, "support": { "array": { "words_connector": ", ", "two_words_connector": " and ", "last_word_connector": ", and " } }, "errors": { "format": "%{attribute} %{message}", "messages": { "inclusion": "is not included in the list", "exclusion": "is reserved", "invalid": "is invalid", "confirmation": "doesn't match confirmation", "accepted": "must be accepted", "empty": "can't be empty", "blank": "can't be blank", "too_long": "is too long (maximum is %{count} characters)", "too_short": "is too short (minimum is %{count} characters)", "wrong_length": "is the wrong length (should be %{count} characters)", "not_a_number": "is not a number", "not_an_integer": "must be an integer", "greater_than": "must be greater than %{count}", "greater_than_or_equal_to": "must be greater than or equal to %{count}", "equal_to": "must be equal to %{count}", "less_than": "must be less than %{count}", "less_than_or_equal_to": "must be less than or equal to %{count}", "odd": "must be odd", "even": "must be even", "in_between": "must be in between %{min} and %{max}", "already_confirmed": "was already confirmed, please try signing in", "confirmation_period_expired": "needs to be confirmed within %{period}, please request a new one", "expired": "has expired, please request a new one", "not_found": "not found", "not_locked": "was not locked", "not_saved": { "one": "1 error prohibited this %{resource} from being saved:", "other": "%{count} errors prohibited this %{resource} from being saved:" } } }, "activerecord": { "errors": { "messages": { "taken": "has already been taken", "record_invalid": "Validation failed: %{errors}" }, "models": { "account_value": { "attributes": { "investment_id": { "taken": "You cannot save more than one account value to the same account for the same period" } } }, "document": { "attributes": { "filename": { "blank": "must be present for each Document" } } }, "page": { "attributes": { "title": { "taken": "has already been taken. Please choose another title." }, "name": { "taken": "has already been taken. Please choose another name.", "no_route_clobber": "'%{name}' is already used by the system. Please choose another Short URL for the page.", "not_just_numeric": "'%{name}' must contain non-numeric characters.", "no_forward_slashes": "'%{name}' can not contan a forward slash." } } } } }, "models": { "fund": "Product", "hedge_fund": "HedgeFund" }, "attributes": { "form": { "send_to": "Email Recipient" }, "group": { "identifier": "Name" }, "page": { "name": "Slug", "template": "Template File" }, "user": { "identifier": "Email" }, "owner": { "incoming_email_address": "Email from this site for you will be sent to", "outgoing_email_address": "When this site sends email to users, the \"From\" address will be", "outgoing_email_name": "When this site sends email to users, the \"From\" name will be", "bcc_email_address": "Email address that receives a copy of all emails sent from InvestorBridge" } } }, "number": { "format": { "separator": ".", "delimiter": ",", "precision": 3, "significant": false, "strip_insignificant_zeros": false }, "currency": { "format": { "format": "%u%n", "unit": "$", "separator": ".", "delimiter": ",", "precision": 2, "significant": false, "strip_insignificant_zeros": false } }, "percentage": { "format": { "delimiter": "" } }, "precision": { "format": { "delimiter": "" } }, "human": { "format": { "delimiter": "", "precision": 3, "significant": true, "strip_insignificant_zeros": true }, "storage_units": { "format": "%n %u", "units": { "byte": { "one": "Byte", "other": "Bytes" }, "kb": "KB", "mb": "MB", "gb": "GB", "tb": "TB" } }, "decimal_units": { "format": "%n %u", "units": { "unit": "", "thousand": "Thousand", "million": "Million", "billion": "Billion", "trillion": "Trillion", "quadrillion": "Quadrillion" } } } }, "datetime": { "distance_in_words": { "half_a_minute": "half a minute", "less_than_x_seconds": { "one": "less than 1 second", "other": "less than %{count} seconds" }, "x_seconds": { "one": "1 second", "other": "%{count} seconds" }, "less_than_x_minutes": { "one": "less than a minute", "other": "less than %{count} minutes" }, "x_minutes": { "one": "1 minute", "other": "%{count} minutes" }, "about_x_hours": { "one": "about 1 hour", "other": "about %{count} hours" }, "x_days": { "one": "1 day", "other": "%{count} days" }, "about_x_months": { "one": "about 1 month", "other": "about %{count} months" }, "x_months": { "one": "1 month", "other": "%{count} months" }, "about_x_years": { "one": "about 1 year", "other": "about %{count} years" }, "over_x_years": { "one": "over 1 year", "other": "over %{count} years" }, "almost_x_years": { "one": "almost 1 year", "other": "almost %{count} years" } }, "prompts": { "year": "Year", "month": "Month", "day": "Day", "hour": "Hour", "minute": "Minute", "second": "Seconds" } }, "helpers": { "select": { "prompt": "Please select" }, "submit": { "create": "Create %{model}", "update": "Update %{model}", "submit": "Save %{model}" }, "button": { "create": "Create %{model}", "update": "Update %{model}", "submit": "Save %{model}" } }, "will_paginate": { "previous_label": "&#8592; Previous", "next_label": "Next &#8594;", "page_gap": "&hellip;", "page_entries_info": { "single_page": { "zero": "No %{model} found", "one": "Displaying 1 %{model}", "other": "Displaying all %{count} %{model}" }, "single_page_html": { "zero": "No %{model} found", "one": "Displaying <b>1</b> %{model}", "other": "Displaying <b>all&nbsp;%{count}</b> %{model}" }, "multi_page": "Displaying %{model} %{from} - %{to} of %{count} in total", "multi_page_html": "Displaying %{model} <b>%{from}&nbsp;-&nbsp;%{to}</b> of <b>%{count}</b> in total" } }, "devise": { "confirmations": { "confirmed": "Your account was successfully confirmed. You are now signed in.", "send_instructions": "You will receive an email with instructions about how to confirm your account in a few minutes.", "send_paranoid_instructions": "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." }, "failure": { "already_authenticated": "You are already signed in.", "inactive": "Invalid email or password.", "invalid": "Invalid email or password.", "invalid_token": "Invalid authentication token.", "locked": "Your account is locked.", "not_found_in_database": "Invalid email or password.", "timeout": "Your session expired, please sign in again to continue.", "unauthenticated": "You need to sign in or sign up before continuing.", "unconfirmed": "You have to confirm your account before continuing." }, "mailer": { "confirmation_instructions": { "subject": "Confirmation instructions" }, "reset_password_instructions": { "subject": "Reset password instructions" }, "unlock_instructions": { "subject": "Unlock Instructions" } }, "omniauth_callbacks": { "failure": "Could not authenticate you from %{kind} because \"%{reason}\".", "success": "Successfully authenticated from %{kind} account." }, "passwords": { "no_token": "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided.", "send_instructions": "You will receive an email with instructions about how to reset your password in a few minutes.", "send_paranoid_instructions": "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.", "updated": "Your password was changed successfully. You are now signed in.", "updated_not_active": "Your password was changed successfully." }, "registrations": { "destroyed": "Bye! Your account was successfully cancelled. We hope to see you again soon.", "signed_up": "Welcome! You have signed up successfully.", "signed_up_but_inactive": "You have signed up successfully. However, we could not sign you in because your account is not yet activated.", "signed_up_but_locked": "You have signed up successfully. However, we could not sign you in because your account is locked.", "signed_up_but_unconfirmed": "A message with a confirmation link has been sent to your email address. Please open the link to activate your account.", "update_needs_confirmation": "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address.", "updated": "You updated your account successfully." }, "sessions": { "signed_in": "Signed in successfully.", "signed_out": "Signed out successfully.", "locked": "Too many unsuccessful logins have been attempted for this username. The account has been temporarily disabled. If you have forgotten your password, please click \"Forgot your Password?\" to immediately reactivate your account." }, "unlocks": { "send_instructions": "You will receive an email with instructions about how to unlock your account in a few minutes.", "send_paranoid_instructions": "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.", "unlocked": "Your account has been unlocked successfully. Please sign in to continue." } }, "account_pretty_name": "Account", "accounts_pretty_name": "Accounts", "assetgroup_pretty_name": "Asset Group", "asset_type": "Asset Type", "attachable": "Documents", "attachable_pretty_name": "Document", "call_pretty_name": "Call", "date_pretty": "Date", "email": "Email", "formsubmission_pretty_name": "Submitted Document", "fund_pretty_name": "Fund", "fund_values_pretty_name": "Fund Values", "funds_pretty_name": "Funds", "group_pretty_name": "Group", "hedgefund_pretty_name": "Hedge Fund", "hedgefundholding_pretty_name": "Hedge Fund Holding", "holding_pretty_name": "Holding", "holdings_pretty_name": "Holdings", "investment_pretty_name": "Account", "managedaccount_pretty_name": "Managed Account", "managedholding_pretty_name": "Managed Holding", "meeting_pretty_name": "Meeting", "name": "Name", "none": "None", "note_pretty_name": "Note", "privateequityfund_pretty_name": "Private Equity Fund", "privateequityholding_pretty_name": "Private Equity Holding", "product_pretty_name": "Product", "strategy": "Strategy", "user_pretty_name": "User", "author_pretty_name": "User", "transactions": { "CALL": "Call", "COMMITMENT": "Commitment", "DISTRIBUTION": "Distribution", "PURCHASE": "Purchase", "Purchase": "Purchase", "REDEEM": "Redeem", "Redemption": "Redemption", "Sale": "Sale", "Subscription": "Subscription", "SUBSCRIPTION": "Subscription", "TRANSFER": "Transfer", "TRANSFER_PURCHASE": "Transfer Purchase", "TRANSFER_SALE": "Transfer Sale" }, "attachables": { "apply": "Apply", "associated_with": "Associated With", "attachments": "Attachments", "attendees": "Attendees", "clear": "Clear", "correspondence": "Correspondence", "direct_link": "direct link", "effective_date": "Date", "date": "Date", "from": "From", "hide_advanced": "Hide Advanced", "import_date": "Import Date", "imported_during": "Correspondence imported during the most recent %{calendar_days} calendar days.", "imported_since": "imported since", "location": "Location", "recent": "Recent", "recent_correspondence": "Recent Correspondence", "search_by_association": "Search by Association", "search_by_date": "Search by Date", "set": "Set", "show_advanced": "Show Advanced", "title": "Title", "to": "To", "type": "Type", "view_all_tags": "View All Correspondence Types", "viewed_by": "Viewed by" }, "attachable_types": { "Call": "Call", "Document": "Document", "Email": "Email", "Meeting": "Meeting", "Note": "Note" }, "funds": { "fund_size": "Fund Size", "vintage_year": "Vintage Year", "regional_focus": "Regional Focus" }, "investments": { "3_year_annualized": "3 Year Ann", "5_year_annualized": "5 Year Ann", "10_year_annualized": "10 Year Ann", "account_details": "Account Details", "account_documents": "Account Documents", "account_name": "Account Name", "account_values": "Account Values", "accounts_in_fund": "Accounts in Fund", "amount": "Amount", "appreciation": "Appreciation", "asset_group_name": "Asset Group Name", "asset_group_values": "Asset Group Values", "asset_types": "Asset Types", "aum": "AUM", "aum_history": "AUM History", "aum_millions": "Assets Under Management (in millions)", "benchmark": "Benchmark", "breakdown_asset": "Breakdown by Asset Type", "closing_value": "Closing Value", "contributed_amount": "Contributed Amount", "currency": "Currency", "current_value": "Current Value", "date_added": "Date Added", "date_removed": "Date Removed", "denotes_estimate": "Denotes an Estimate", "denotes_partial": "Denotes a Partial Period Estimate", "details": "Details", "end_date": "End Date", "fees": "Fees", "fund_name": "Fund Name", "hedge_fund_name": "Hedge Fund Name", "hedge_funds": "Hedge Funds", "historic_and_aum": "Historic Returns and AUM", "historic_performance": "Historic Performance", "holding_name": "Holding Name", "investment_values": "Investment Values", "investments_by_strategy": "Investments by Strategy", "is_return_estimate": "Is the Return an Estimate", "label_aum": "Assets Under Management (in millions)", "label_return": "Returns", "ltd": "LTD", "ltd_compounded": "LTD Comp", "ltd_irr": "Life to Date IRR", "ltd_return": "LTD Return", "ltd_total_redeemed": "LTD Total Redeemed", "ltd_year_annualized": "LTD Year Ann", "management_company": "Management Company", "most_recent_appreciation": "Most Recent Net Appreciation", "most_recent_period": "Most Recent Period", "most_recent_return": "Most Recent Reported Return", "mtd": "MTD", "mtd_compounded": "MTD Comp", "mtd_return": "MTD Return", "net_appreciation": "Net Appreciation", "net_income_for_month": "Net Income for Month", "participant_name": "Participant Name", "participant_since": "Participant Since", "participant_type": "Participant Type", "participants": "Participants", "participants_for": "Participants for", "percent_contribution": "Percent Contribution", "percent_of_group": "Percent of Group", "performance": "Performance", "performance_snapshot": "Performance Snapshot", "period": "Period", "portfolio": "Portfolio", "portfolio_name": "Portfolio Name", "private_equity_fund_name": "Private Equity Fund Name", "private_equity_funds": "Private Equity Funds", "product_name": "Product Name", "prospect_type": "Prospect Type", "prospective_funds": "Prospective Funds", "qtd": "QTD", "qtd_compounded": "QTD Comp", "related_funds": "Related Funds", "reported_return": "Reported Return", "return": "Return", "return_history": "Return History", "start_date": "Start Date", "starting_value": "Starting Value", "stop_date": "Stop Date", "terms": "Terms", "total_invested": "Total Invested", "transactions": "Transactions", "underlying_asset": "Underlying Asset", "underlying_type": "Underlying Type", "value_as_of": "Value as Of", "values": "Values", "values_for_fund": "Values for Fund", "values_for_hedge_fund": "Values for Hedge Fund", "values_for_pe_fund": "Values for Private Equity Fund", "view_accounts": "View Accounts", "view_funds": "View Funds", "view_hf_details": "To view individual hedge fund details click on the hedge fund name", "view_holdings": "View Holdings", "view_hf_holdings": "View Hedge Fund Holdings", "view_pe_holdings": "View Private Equity Holdings", "view_participants": "View Participants", "view_pe_funds": "View Private Equity Funds", "year": "Year", "your_accounts": "Your Accounts in", "ytd": "YTD", "ytd_compounded": "YTD Comp", "ytd_return": "YTD Return" }, "fund_details": { "Accepting New Investments": "Accepting New Investments", "Additional Investment": "Additional Investment", "Clawback": "Clawback", "Date Closed": "Date Closed", "Gate": "Gate", "Gate Percent": "Gate Percent", "High Water Mark": "High Water Mark", "High Water Terms": "High Water Terms", "Hurdle Rate": "Hurdle Rate", "Hurdle Terms": "Hurdle Terms", "Incentive Fee Percent": "Incentive Fee", "Inception Date": "Inception Date", "Initial Lockup Months": "Initial Lockup Months", "Ltd Compounded Return": "Ltd Compounded Return", "Management Fee Percent": "Management Fee", "Maximum Side Pocket Percent": "Maximum Side Pocket", "Minimum Investment": "Minimum Investment", "Offering Memorandum Date": "Offering Memorandum Date", "Other Fees": "Other Fees", "Redemption Fee": "Redemption Fee", "Redemption Notice": "Redemption Notice", "Redemptions": "Redemptions", "Regional Focus": "Regional Focus", "Registration Type": "Registration Type", "Sales Fee": "Sales Fee", "Sector Industry": "Sector Industry", "Side Pocket": "Side Pocket", "Soft Lockup": "Soft Lockup", "Soft Lockup Months": "Soft Lockup Months", "Subscriptions": "Subscriptions", "Us Taxable": "Us Taxable", "Use Of Leverage": "Use Of Leverage", "Uses Leverage": "Uses Leverage", "Ytd Compounded Return": "Ytd Compounded Return" }, "hedgefund_details": { "3 Month Rolling Compounded Return": "3 Month Rolling Compounded Return", "6 Month Rolling Compounded Return": "6 Month Rolling Compounded Return", "12 Month Rolling Compounded Return": "12 Month Rolling Compounded Return", "24 Month Largest Drawdown": "24 Month Largest Drawdown", "24 Month Rolling Compounded Return": "24 Month Rolling Compounded Return", "24 Month Standard Deviation": "24 Month Standard Deviation", "Asset Type": "Strategy", "Backstop Id": "Backstop Id", "Benchmark A Name": "Benchmark A Name", "Benchmark A Symbol": "Benchmark A Symbol", "Benchmark B Name": "Benchmark B Name", "Benchmark B Symbol": "Benchmark B Symbol", "Currency": "Currency", "Description": "Description", "Firm AUM": "Firm AUM", "Fund Manager": "Fund Manager", "Incentive Fee": "Incentive Fee", "Inception Date": "Inception Date", "Investment Details": "Investment Details", "Is Product?": "Is Product?", "Management Company": "Management Company", "Management Fee": "Management Fee", "Manager Bio": "Manager Bio", "Tracked Since": "Tracked Since" }, "asset_details": { "Asset Group Name": "Asset Group Name", "Benchmark A": "Benchmark A", "Benchmark A Name": "Benchmark A Name", "Benchmark A Symbol": "Benchmark A Symbol", "Benchmark B": "Benchmark B", "Benchmark B Name": "Benchmark B Name", "Benchmark B Symbol": "Benchmark B Symbol", "Benchmark C": "Benchmark C", "Benchmark C Name": "Benchmark C Name", "Benchmark C Symbol": "Benchmark C Symbol", "Benchmark D": "Benchmark D", "Benchmark D Name": "Benchmark D Name", "Benchmark D Symbol": "Benchmark D Symbol", "Benchmark E": "Benchmark E", "Benchmark E Name": "Benchmark E Name", "Benchmark E Symbol": "Benchmark E Symbol", "Benchmark F": "Benchmark F", "Benchmark F Name": "Benchmark F Name", "Benchmark G": "Benchmark G", "Benchmark G Name": "Benchmark G Name", "Benchmark H": "Benchmark H", "Benchmark H Name": "Benchmark H Name", "Currency Code": "Currency Code", "Current Month Compounded Return": "Current Month Compounded Return", "Current Value": "Current Value", "LTD Compounded Return": "LTD Compounded Return", "LTD IRR": "LTD IRR", "LTD Total Invested Over Period": "LTD Total Invested Over Period", "LTD Total Redeemed Over Period": "LTD Total Redeemed Over Period", "QTD Compounded Return": "QTD Compounded Return", "Risk Free Benchmark": "Risk Free Benchmark", "YTD Compounded Return": "YTD Compounded Return" }, "investment_details": { "Annualized IRR": "Annualized IRR", "Annualized Return": "Annualized Return", "Annualized Standard Deviation": "Annualized Standard Deviation", "Average Monthly Gain": "Average Monthly Gain", "Average Monthly Loss": "Average Monthly Loss", "Current Month % Of Profitable Months": "Current Month % Of Profitable Months", "Current Month Annualized Return": "Current Month Annualized Return", "Current Month Average Gain": "Current Month Average Gain", "Current Month Average Loss": "Current Month Average Loss", "Current Month IRR": "Current Month IRR", "Earnings": "Earnings", "Gate": "Gate", "Hedge Fund": "Hedge Fund", "Incentive Fee": "Incentive Fee", "Investor Since": "Investor Since", "LTD Alpha": "LTD Alpha", "LTD Beta": "LTD Beta", "LTD Compound": "LTD Compound", "LTD Correlation": "LTD Correlation (r)", "LTD Earnings": "LTD Earnings", "LTD Sharpe Ratio": "LTD Sharpe Ratio", "LTD Sortino Ratio": "LTD Sortino Ratio", "Last Valuation": "Last Valuation", "Management Fee": "Management Fee", "Maximum Drawdown": "Maximum Drawdown", "Maximum Side Pocket": "Maximum Side Pocket", "Percent of Portfolio": "Percent of Portfolio", "Profitable Percentage": "Profitable Percentage", "QTD Return": "QTD Return", "Returns and Risk": "Returns & Risk", "Total Invested": "Total Invested", "Total Redemptions": "Total Redemptions", "Type": "Type", "YTD Return": "YTD Return" }, "charts": { "distibution_title": "Distribution of Returns Chart", "frequency": "Frequency (months)", "monthly_returns": "Monthly Returns", "value_of_1000": "Value of $1000", "vami_title": "VAMI chart", "export_chart": "Export Chart" }, "excel_export": { "link_text": "Export to Excel", "button_text": "Export to Excel" }, "user": { "back_to_top": "Back to Top", "logout": "Log Out", "menu": "Menu", "printed_by": "Printed by", "welcome": "Welcome" }, "password": { "accept_our": "Accept our", "confirm_password": "Submit", "enter_pw": "Set Your Password", "enter_pw_text": "Enter in a new password here", "fair_def": "Fair - contains two of the above parameters", "forgot_password": "Forgot Password?", "good_def": "Good - contains four of the above parameters", "has_6": "Has more than 6 characters", "has_12": "Has more than 12 characters", "includes_lower": "Includes lower case letters", "includes_numbers": "Includes numbers", "includes_special": "Includes special characters, such as @ # $ % ^ & * ? ~ - ( )", "includes_upper": "Includes upper case letters", "medium_def": "Medium - contains three of the above parameters", "minimum_strength": "The required minimum strength level for your password is", "password": "Password", "password_confirmation": "Confirm Password", "password_reset": "Password Reset", "reset_instructions": "Please enter your email address in the field below, then click the Reset Password button. A new invitation message will be sent to your email address.", "reset_password": "Reset Password", "secure_def": "Secure - contains five of the above parameters", "strength_indicator": "This level is indicated by the hash mark in the meter that appears once you start typing in the Password field", "strength_levels": "The strength levels and the requirements for each are", "submit": "Submit", "terms_of_use": "Terms of Use", "user": "User", "very_secure_def": "Very Secure - contains all six of the above parameters", "weak_def": "Weak - contains only one of the above parameters", "what_makes_pw_secure": "What makes a password more secure" }, "drm": { "about_secure_pdf": "About Secure PDFs", "about_secure_text": "This website uses a secure file encryption system to control access to certain PDF documents. To view an encrypted PDF file you must be logged in to the website, and you must open it using Adobe Reader/Acrobat with the FileOpen plug-in installed. The FileOpen plug-in allow users to view the PDF, but limits the ability to save, print or forward a readable copy of the file.", "adobe_link": "download Adobe Reader", "adobe_text": "If you do not have Adobe Reader/Acrobat, you will need to", "document_download": "Document Download", "download_error": "Error(s) Occurred Downloading This Document", "fileopen_link": "download FileOpen", "fileopen_text1": "If you do not have the FileOpen plug-in,", "fileopen_text2": "(You should be prompted to install the plug-in when you download your first secure PDF.)", "if_clicking": "If clicking on the link above does not open the document, right-click on the link, save the document to your computer and open it in Adobe Reader/Acrobat. If you continue to have difficulty, please read the configuration and troubleshooting details below.", "if_not": "If not please try this", "secure_document_download": "Secure Document Download", "start_download": "Start Download", "taken_to_document": "You will be taken to your Document shortly" }, "instructions": { "search_attachable": "Please choose the Document Type you would like to view in the drop down menu.  Clicking on the magnifying icon in the document table to open search options.  Clicking on the calendar in the document table will open a Date Filter." }, "messages": { "bad_login": "<br/>Email and Password combination was not found.<br/><br/>\nIf you continue to have problems logging in please <a href='%{password_reset_url}'>Reset Your Password Here</a><br/><br/>\n", "inactive_login": "Your user account has not been activated yet. Please contact your site administrator for assistance.", "about_to_lock": "Warning: The next unsuccessful login attempt with this username will temporarily disable the account for %{ban_time} minutes.", "login_required": "Please login to access the requested page.", "click_to_download": "click to download", "config_updated": "Configuration updated!", "doc_only_import_unavailable": "Documents & Activity import cannot be run until a full import has successfully completed. Please run a full import and try again.", "download_problem": "There was a problem with your download. Please try again.", "email_sent": "An email has been sent to that address with instructions on how to reset your password.", "emails_sent_to": "Emails Were Sent to %{user_count} user(s)", "forbidden": "You do not have the proper permissions to view this page.", "form_deleted": "Form on %{page_title} was successfully deleted.", "form_disabled": "Form submissions are currently disabled.", "form_errors": "Your Form was not saved because of these errors:", "form_success": "Form on %{page_title} was successfully created.", "form_updated": "Form on %{page_title} was successfully updated.", "import_running": "Import already running. Can't run another.", "investment_data_only_import_unavailable": "Investment Data import cannot be run until a full import has successfully completed. Please run a full import and try again.","logged_document":"You must be logged in to view this secure document.","login_banned":"Too many unsuccessful logins have been attempted for this username. The account has been temporarily disabled for %{ban_time} minutes. If you have forgotten your password, please click 'Forgot your Password?' to immediately reactivate your account.","login_warning":"Warning: The next unsuccessful login attempt with this username will temporarily disable the account for %{ban_time} minutes.","must_be_author":"You must be logged in as an author to view this page","no_permission":"You do not have the proper permissions to view that page.","not_activiated":"Your user account has not been activated yet. Please contact your site administrator for assistance.","password_blank":"Password must not be blank","password_success":"Password successfully updated.","please":"Please","pw_reset_expired":"Your password reset link has expired. Please contact your site administrator for assistance.","record_created":"%{record} was created successfully.","record_updated":"%{record} was updated successfully.","record_invalid":"%{record} was not valid.","requires_flash":"This page requires Adobe Flash to upload documents.","sent_success":"Your message has been successfully sent.","server_timeout":"InvestorBridge was unable to connect to the background server. Please contact your Backstop Support.","unconfigured_import":"Backstop Import Is Not Configured. Please contact your administrator.","user_inactive":"Previewing is unavailable for inactive users.","user_only_import_unavailable":"User import cannot be run until a full import has successfully completed. Please run a full import and try again.","visibility_failure":"Visibility import failed.","visibility_import_timeout":"Visibility import failed."},"session":{"timeout":{"message":"You have been logged out due to session inactivity."}},"navigation":{"admin_home":{"text":"Admin Home","tooltip":"Review Release Notes and Support Documents"},"edit_content":{"text":"Edit Content","tooltip":"Edit Page Content"}},"models":{"account":{"placeholder":{"name":"[Account Name]"}},"document":{"to_s":"Title: %{title}.  Other_id (from Backstop): %{other_id}"}},"formats":{"na":"N/A","date":"%m-%d-%Y","time":"%I:%M%p","datetime":"%m-%d-%Y %I:%M%p %Z"},"month":{"month_names":[null,"January","February","March","April","May","June","July","August","September","October","November","December"],"abbr_month_names":[null,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},"quarter":{"names":[null,"Q1","Q2","Q3","Q4"]},"scheduled_tasks":{"type":{"full_download":"Backstop Import","doc_only":"Document Only Import","user_only":"User Only Import"}},"email_template":{"blank_template":"Blank Template","general_email":"General Email","password_reset":"Password Reset Email"},"system_api":{"ip_regex":"^(192\\.168|127\\.0)\\.\\d+\\.\\d+$"},"configuration":{"revision":{"not_found":"A revision file was not found at:%{REVISION_PATH}"},"branch":{"not_found":"A branch file was not found at:%{BRANCH_PATH}"}},"parameter_filtering":{"mask":"[U_CAN_NOT_HAZ]"},"recaptcha":{"errors":{"verification_failed":"The Captcha value you entered is incorrect.  Please try again.","recaptcha_unavailable":"Captcha service is momentarily unavailable.  Please try again in a few minutes."}}}};

;(function ($) {
  function hashify (links) {
    var map = {};
    if (typeof links === 'undefined') {
      throw 'Parse error reading link definition from server';
    }

    try {
      $.each( links, function( i, value ) {
        map[ value.rel ] = value.href;
      });
      return map;
    } catch (e) {
      throw 'Unparsable response from server: ' + links;
    }
  }

  Backstop.InvestorBridgeJson = function ( data ) {
    this.data = data;
    this._links = hashify( data._links );
  };

  Backstop.InvestorBridgeJson.prototype.link = function ( rel ) {
    try {
      return this._links[rel];
    } catch (e) {
      throw 'Unparsable response from server: ' + this.data;
    }
  };
}(jQuery));
// -*- coding: utf-8 -*-



;(function($) {
  Backstop.drm_on = $('meta[name="enable-enhanced-pdf-encryption"]').attr('content') == 'true';

  var CreationHandler = function() {
    this.drmd = $('meta[name="enable-enhanced-pdf-encryption"]').attr('content') == 'true';
  };

  CreationHandler.prototype.onCreate = function( responseData, poller ) {
    if ( this.drmd && responseData._links[0].encrypting) {
      poller.going();
      var ibJson = new Backstop.InvestorBridgeJson( responseData );
      Backstop.redirect( ibJson.link( 'self' ) );
    } else {
      poller.handleStatus( responseData, undefined, function( url ) {
        poller.going();
        Backstop.redirect( url );
      });
    }
  };
  Backstop.CreationHandler = CreationHandler;

  var DownloadPoller = function( link, body, successCallback, errorCallback ) {
    this.link = $(link);
    this.waiting();
    this.createUrl = this.link.data( 'download-url' );
    this.statusUrl = this.link.data( 'status-url' );
    this.cancelUrl = this.link.data( 'cancel-url' );
    this.body = body;
    this.errorCallback = errorCallback;
    this.successCallback = successCallback;
    this.canceled = false;
    this.readStateText = this.link.parents('.single-download-links').prev()[0];
  };

  Backstop.DownloadPoller = DownloadPoller;

  DownloadPoller.prototype = {
    start: function() {
      this.create( this.createUrl, this.body );
    },

    pollStatus: function() {
      var self = this;
      this.waiting();
      this.handleStatus( undefined, undefined, function( url ) {
        self.link.attr( 'href', url );
        self.going();
      });
    },

    waiting: function() {
      if ($('p.download-in-progress').size() > 0) { return; }
      var tag = $('<p></p>');
      tag.addClass( 'download-in-progress' );
      tag.addClass( 'waiting-ajax' );
      tag.html( 'Creating your download&hellip;' );

      this.link.hide();
      this.link.after( tag );
      this.link.addClass( 'waiting-ajax' );
    },

    going: function() {
      this.link.next( 'p.download-in-progress' ).remove();
      this.link.removeClass( 'waiting-ajax' );
      this.link.show();
    },

    cancel: function() {
      this.canceled = true;
    },

    create: function( url, body ) {
      var self = this;
      this.waiting();

      var onError = this.errorCallback;
      if (onError === undefined) { onError = function() { window.location.reload(); }; }

      $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: body,
        success: function( data, textStatus ) {
          new CreationHandler().onCreate( data, self );
        },
        error: function( xhr, textStatus, errorThrown ) {
          onError( xhr, textStatus, errorThrown );
          self.going();
        }
      });
    },

    handleStatus: function( data, textStatus, readyCallback ) {
      var self = this;
      var defaultReadyHandler = function( url ) {
        if ( new Backstop.CreationHandler().drmd ) {
          self.going();
        } else {
          Backstop.redirect(url);
        }
      };

      var defaultErrorHandler = function( xhr, textStatus, errorThrown ) {
        var error;
        try {
          error = jQuery.parseJSON(xhr.responseText).download.messages;
        } catch (e) {
          error = undefined;
        }

        var message = $('<div class=error> <p>' + (error || 'There was a problem ' +
                      'creating your download, please try again.') + '</p></div>');

        if ( xhr.status == 410 ) {
          self.create( self.createUrl );
        } else {
          $('#flash-div').html( message );
          message.fadeIn( 'fast' );
        }
      };

      if (data && data._links) {
        var ibJson = new Backstop.InvestorBridgeJson( data );
        this.statusUrl = ibJson.link( 'self' );
        this.cancelUrl = ibJson.link( 'cancel' );
      }

      var onReady = readyCallback;
      if (onReady === undefined) { onReady = defaultReadyHandler; }

      var onError = this.errorCallback;
      if (onError === undefined ) { onError = defaultErrorHandler; }

      var onSuccessfulDownload = this.successCallback;
      if (onSuccessfulDownload === undefined ) { onSuccessfulDownload = function(data) {}; }

      if (this.canceled) {
        $.ajax({
          url: this.cancelUrl,
          type: 'DELETE',
          success: function( data, textStatus, xhr ) {
            self.going();
          },
          error: function( data, textStatus, xhr ) {
            onError( data, textStatus, xhr );
            self.going();
          }
        });

        return;
      }

      $.ajax({
        url: this.statusUrl,
        context: this,
        dataType: 'json',
        success: function( data, textStatus, xhr ) {
          var status = xhr.status;
          var ibJson = new Backstop.InvestorBridgeJson( data );

          if (status === 202) {
            setTimeout(function () {
              $.proxy(self.handleStatus( undefined, undefined, onReady ), self);
            }, 500);
          } else {
            var download_url = ibJson.link( 'self' );
            var pollerObject = this;

            onSuccessfulDownload( xhr );
            onReady( download_url );
            if (pollerObject.readStateText) {
              pollerObject.readStateText.classList.remove('is-unread');
            }
          }
        },

        error: function (xhr, textStatus, errorThrown) {
          onError( xhr, textStatus, errorThrown );
          self.going();
        },
        complete: function( xhr, textStatus ) {}
      });
    }
  };

  function setCsrfToken( options, originalOptions, jqXHR ) {
    var token = $('meta[name="csrf-token"]').attr('content');
    if (token) {
      jqXHR.setRequestHeader('X-CSRF-Token', token);
    }
  }

  $.fn.pollingDocumentDownload = function() {
    return this.each(function() {
      var $this = $(this);
      var sentinel = $this.data('backstop.pollingDocumentDownload');

      if (!sentinel) {
        $this.delegate( 'a[data-download-url]', 'click', function (event) {
          event.preventDefault();
          new DownloadPoller( this ).start();
        });


        $this.find( 'a[data-status-url]' ).each( function() {
          new DownloadPoller( this ).pollStatus();
        });

        $this.data( 'backstop.pollingDocumentDownload', { poller: this } );
      }
    });
  };

  DownloadPoller.init = function() {
    $.ajaxPrefilter( setCsrfToken );
    $('#body-content, #control-panel-bg').pollingDocumentDownload();
  };

  $(function() { DownloadPoller.init(); });
}(jQuery));
/*!
 *
 * MediaElement.js
 * HTML5 <video> and <audio> shim and player
 * http://mediaelementjs.com/
 *
 * Creates a JavaScript object that mimics HTML5 MediaElement API
 * for browsers that don't understand HTML5 or can't play the provided codec
 * Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
 *
 * Copyright 2010-2014, John Dyer (http://j.hn)
 * License: MIT
 *
 */
// Namespace
var mejs = mejs || {};

// version number
mejs.version = '2.23.5';


// player number (for missing, same id attr)
mejs.meIndex = 0;

// media types accepted by plugins
mejs.plugins = {
	silverlight: [
		{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
	],
	flash: [
		{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a', 'audio/mp4', 'audio/mpeg', 'video/dailymotion', 'video/x-dailymotion', 'application/x-mpegURL', 'audio/ogg']}
		// 'video/youtube', 'video/x-youtube', 
		// ,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
	],
	youtube: [
		{version: null, types: ['video/youtube', 'video/x-youtube', 'audio/youtube', 'audio/x-youtube']}
	],
	vimeo: [
		{version: null, types: ['video/vimeo', 'video/x-vimeo']}
	]
};

/*
Utility methods
*/
mejs.Utility = {
	encodeUrl: function(url) {
		return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
	},
	escapeHTML: function(s) {
		return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
	},
	absolutizeUrl: function(url) {
		var el = document.createElement('div');
		el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
		return el.firstChild.href;
	},
	getScriptPath: function(scriptNames) {
		var
			i = 0,
			j,
			codePath = '',
			testname = '',
			slashPos,
			filenamePos,
			scriptUrl,
			scriptPath,			
			scriptFilename,
			scripts = document.getElementsByTagName('script'),
			il = scripts.length,
			jl = scriptNames.length;
			
		// go through all <script> tags
		for (; i < il; i++) {
			scriptUrl = scripts[i].src;
			slashPos = scriptUrl.lastIndexOf('/');
			if (slashPos > -1) {
				scriptFilename = scriptUrl.substring(slashPos + 1);
				scriptPath = scriptUrl.substring(0, slashPos + 1);
			} else {
				scriptFilename = scriptUrl;
				scriptPath = '';			
			}
			
			// see if any <script> tags have a file name that matches the 
			for (j = 0; j < jl; j++) {
				testname = scriptNames[j];
				filenamePos = scriptFilename.indexOf(testname);
				if (filenamePos > -1) {
					codePath = scriptPath;
					break;
				}
			}
			
			// if we found a path, then break and return it
			if (codePath !== '') {
				break;
			}
		}
		
		// send the best path back
		return codePath;
	},
	/*
	 * Calculate the time format to use. We have a default format set in the
	 * options but it can be imcomplete. We ajust it according to the media
	 * duration.
	 *
	 * We support format like 'hh:mm:ss:ff'.
	 */
	calculateTimeFormat: function(time, options, fps) {
		if (time < 0) {
			time = 0;
		}

		if(typeof fps == 'undefined') {
		    fps = 25;
		}

		var format = options.timeFormat,
			firstChar = format[0],
			firstTwoPlaces = (format[1] == format[0]),
			separatorIndex = firstTwoPlaces? 2: 1,
			separator = ':',
			hours = Math.floor(time / 3600) % 24,
			minutes = Math.floor(time / 60) % 60,
			seconds = Math.floor(time % 60),
			frames = Math.floor(((time % 1)*fps).toFixed(3)),
			lis = [
				[frames, 'f'],
				[seconds, 's'],
				[minutes, 'm'],
				[hours, 'h']
			];

		// Try to get the separator from the format
		if (format.length < separatorIndex) {
			separator = format[separatorIndex];
		}

		var required = false;

		for (var i=0, len=lis.length; i < len; i++) {
			if (format.indexOf(lis[i][1]) !== -1) {
				required=true;
			}
			else if (required) {
				var hasNextValue = false;
				for (var j=i; j < len; j++) {
					if (lis[j][0] > 0) {
						hasNextValue = true;
						break;
					}
				}

				if (! hasNextValue) {
					break;
				}

				if (!firstTwoPlaces) {
					format = firstChar + format;
				}
				format = lis[i][1] + separator + format;
				if (firstTwoPlaces) {
					format = lis[i][1] + format;
				}
				firstChar = lis[i][1];
			}
		}
		options.currentTimeFormat = format;
	},
	/*
	 * Prefix the given number by zero if it is lower than 10.
	 */
	twoDigitsString: function(n) {
		if (n < 10) {
			return '0' + n;
		}
		return String(n);
	},
	secondsToTimeCode: function(time, options) {
		if (time < 0) {
			time = 0;
		}

		// Maintain backward compatibility with method signature before v2.18.
		if (typeof options !== 'object') {
			var format = 'm:ss';
			format = arguments[1] ? 'hh:mm:ss' : format; // forceHours
			format = arguments[2] ? format + ':ff' : format; // showFrameCount

			options = {
				currentTimeFormat: format,
				framesPerSecond: arguments[3] || 25
			};
		}

		var fps = options.framesPerSecond;
		if(typeof fps === 'undefined') {
			fps = 25;
		}

		var format = options.currentTimeFormat,
			hours = Math.floor(time / 3600) % 24,
			minutes = Math.floor(time / 60) % 60,
			seconds = Math.floor(time % 60),
			frames = Math.floor(((time % 1)*fps).toFixed(3));
			lis = [
				[frames, 'f'],
				[seconds, 's'],
				[minutes, 'm'],
				[hours, 'h']
			];

		var res = format;
		for (i=0,len=lis.length; i < len; i++) {
			res = res.replace(lis[i][1]+lis[i][1], this.twoDigitsString(lis[i][0]));
			res = res.replace(lis[i][1], lis[i][0]);
		}
		return res;
	},
	
	timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
		if (typeof showFrameCount == 'undefined') {
		    showFrameCount=false;
		} else if(typeof fps == 'undefined') {
		    fps = 25;
		}
	
		var tc_array = hh_mm_ss_ff.split(":"),
			tc_hh = parseInt(tc_array[0], 10),
			tc_mm = parseInt(tc_array[1], 10),
			tc_ss = parseInt(tc_array[2], 10),
			tc_ff = 0,
			tc_in_seconds = 0;
		
		if (showFrameCount) {
		    tc_ff = parseInt(tc_array[3])/fps;
		}
		
		tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
		
		return tc_in_seconds;
	},
	

	convertSMPTEtoSeconds: function (SMPTE) {
		if (typeof SMPTE != 'string') 
			return false;

		SMPTE = SMPTE.replace(',', '.');
		
		var secs = 0,
			decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
			multiplier = 1;
		
		SMPTE = SMPTE.split(':').reverse();
		
		for (var i = 0; i < SMPTE.length; i++) {
			multiplier = 1;
			if (i > 0) {
				multiplier = Math.pow(60, i); 
			}
			secs += Number(SMPTE[i]) * multiplier;
		}
		return Number(secs.toFixed(decimalLen));
	},	
	
	/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
	removeSwf: function(id) {
		var obj = document.getElementById(id);
		if (obj && /object|embed/i.test(obj.nodeName)) {
			if (mejs.MediaFeatures.isIE) {
				obj.style.display = "none";
				(function(){
					if (obj.readyState == 4) {
						mejs.Utility.removeObjectInIE(id);
					} else {
						setTimeout(arguments.callee, 10);
					}
				})();
			} else {
				obj.parentNode.removeChild(obj);
			}
		}
	},
	removeObjectInIE: function(id) {
		var obj = document.getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}		
	},
    determineScheme: function(url) {
        if (url && url.indexOf("://") != -1) {
            return url.substr(0, url.indexOf("://")+3);
        }
        return "//"; // let user agent figure this out
    },

	// taken from underscore
	debounce: function(func, wait, immediate) {
		var timeout;
		return function() {
			var context = this, args = arguments;
			var later = function() {
				timeout = null;
				if (!immediate) func.apply(context, args);
			};
			var callNow = immediate && !timeout;
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
			if (callNow) func.apply(context, args);
		};
	},

	/**
	* Returns true if targetNode appears after sourceNode in the dom.
	* @param {HTMLElement} sourceNode - the source node for comparison
	* @param {HTMLElement} targetNode - the node to compare against sourceNode
	*/
	isNodeAfter: function(sourceNode, targetNode) {
		return !!(
			sourceNode &&
			targetNode &&
			typeof sourceNode.compareDocumentPosition === 'function' &&
			sourceNode.compareDocumentPosition(targetNode) & Node.DOCUMENT_POSITION_PRECEDING
		);
	}
};


// Core detector, plugins are added below
mejs.PluginDetector = {

	// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
	hasPluginVersion: function(plugin, v) {
		var pv = this.plugins[plugin];
		v[1] = v[1] || 0;
		v[2] = v[2] || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	},

	// cached values
	nav: window.navigator,
	ua: window.navigator.userAgent.toLowerCase(),

	// stored version numbers
	plugins: [],

	// runs detectPlugin() and stores the version number
	addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
		this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
	},

	// get the version number from the mimetype (all but IE) or ActiveX (IE)
	detectPlugin: function(pluginName, mimeType, activeX, axDetect) {

		var version = [0,0,0],
			description,
			i,
			ax;

		// Firefox, Webkit, Opera
		if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
			description = this.nav.plugins[pluginName].description;
			if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
				version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
				for (i=0; i<version.length; i++) {
					version[i] = parseInt(version[i].match(/\d+/), 10);
				}
			}
		// Internet Explorer / ActiveX
		} else if (typeof(window.ActiveXObject) != 'undefined') {
			try {
				ax = new ActiveXObject(activeX);
				if (ax) {
					version = axDetect(ax);
				}
			}
			catch (e) { }
		}
		return version;
	}
};

// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
	// adapted from SWFObject
	var version = [],
		d = ax.GetVariable("$version");
	if (d) {
		d = d.split(" ")[1].split(",");
		version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
	}
	return version;
});

// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
	// Silverlight cannot report its version number to IE
	// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
	// adapted from http://www.silverlightversion.com/
	var v = [0,0,0,0],
		loopMatch = function(ax, v, i, n) {
			while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
				v[i]+=n;
			}
			v[i] -= n;
		};
	loopMatch(ax, v, 0, 1);
	loopMatch(ax, v, 1, 1);
	loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
	loopMatch(ax, v, 2, 1000);
	loopMatch(ax, v, 2, 100);
	loopMatch(ax, v, 2, 10);
	loopMatch(ax, v, 2, 1);
	loopMatch(ax, v, 3, 1);

	return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
	var version = [],
		d = ax.GetVersions().split(',')[0].split('=')[1].split('.');

	if (d) {
		version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
	}
	return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
	init: function() {
		var
			t = this,
			d = document,
			nav = mejs.PluginDetector.nav,
			ua = mejs.PluginDetector.ua.toLowerCase(),
			i,
			v,
			html5Elements = ['source','track','audio','video'];

		// detect browsers (only the ones that have some kind of quirk we need to work around)
		t.isiPad = (ua.match(/ipad/i) !== null);
		t.isiPhone = (ua.match(/iphone/i) !== null);
		t.isiOS = t.isiPhone || t.isiPad;
		t.isAndroid = (ua.match(/android/i) !== null);
		t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
		t.isBustedNativeHTTPS = (location.protocol === 'https:' && (ua.match(/android [12]\./) !== null || ua.match(/macintosh.* version.* safari/) !== null));
		t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1 || nav.appName.toLowerCase().match(/trident/gi) !== null);
		t.isChrome = (ua.match(/chrome/gi) !== null);
		t.isChromium = (ua.match(/chromium/gi) !== null);
		t.isFirefox = (ua.match(/firefox/gi) !== null);
		t.isWebkit = (ua.match(/webkit/gi) !== null);
		t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit && !t.isIE;
		t.isOpera = (ua.match(/opera/gi) !== null);
		t.hasTouch = ('ontouchstart' in window); //  && window.ontouchstart != null); // this breaks iOS 7

		// Borrowed from `Modernizr.svgasimg`, sources:
		// - https://github.com/Modernizr/Modernizr/issues/687
		// - https://github.com/Modernizr/Modernizr/pull/1209/files
		t.svgAsImg = !!document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');

		// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
		for (i=0; i<html5Elements.length; i++) {
			v = document.createElement(html5Elements[i]);
		}

		t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);

		// Fix for IE9 on Windows 7N / Windows 7KN (Media Player not installer)
		try{
			v.canPlayType("video/mp4");
		}catch(e){
			t.supportsMediaTag = false;
		}

		t.supportsPointerEvents = (function() {
			// TAKEN FROM MODERNIZR
			var element = document.createElement('x'),
				documentElement = document.documentElement,
				getComputedStyle = window.getComputedStyle,
				supports;
			if(!('pointerEvents' in element.style)){
				return false;
			}
			element.style.pointerEvents = 'auto';
			element.style.pointerEvents = 'x';
			documentElement.appendChild(element);
			supports = getComputedStyle &&
				getComputedStyle(element, '').pointerEvents === 'auto';
			documentElement.removeChild(element);
			return !!supports;
		})();


		 // Older versions of Firefox can't move plugins around without it resetting,
		t.hasFirefoxPluginMovingProblem = false;

		// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)

		// iOS
		t.hasiOSFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');

		// W3C
		t.hasNativeFullscreen = (typeof v.requestFullscreen !== 'undefined');

		// webkit/firefox/IE11+
		t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
		t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
		t.hasMsNativeFullScreen = (typeof v.msRequestFullscreen !== 'undefined');

		t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen || t.hasMsNativeFullScreen);
		t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;

		// Enabled?
		if (t.hasMozNativeFullScreen) {
			t.nativeFullScreenEnabled = document.mozFullScreenEnabled;
		} else if (t.hasMsNativeFullScreen) {
			t.nativeFullScreenEnabled = document.msFullscreenEnabled;
		}

		if (t.isChrome) {
			t.hasiOSFullScreen = false;
		}

		if (t.hasTrueNativeFullScreen) {

			t.fullScreenEventName = '';
			if (t.hasWebkitNativeFullScreen) {
				t.fullScreenEventName = 'webkitfullscreenchange';

			} else if (t.hasMozNativeFullScreen) {
				t.fullScreenEventName = 'mozfullscreenchange';

			} else if (t.hasMsNativeFullScreen) {
				t.fullScreenEventName = 'MSFullscreenChange';
			}

			t.isFullScreen = function() {
				if (t.hasMozNativeFullScreen) {
					return d.mozFullScreen;

				} else if (t.hasWebkitNativeFullScreen) {
					return d.webkitIsFullScreen;

				} else if (t.hasMsNativeFullScreen) {
					return d.msFullscreenElement !== null;
				}
			}

			t.requestFullScreen = function(el) {

				if (t.hasWebkitNativeFullScreen) {
					el.webkitRequestFullScreen();

				} else if (t.hasMozNativeFullScreen) {
					el.mozRequestFullScreen();

				} else if (t.hasMsNativeFullScreen) {
					el.msRequestFullscreen();

				}
			}

			t.cancelFullScreen = function() {
				if (t.hasWebkitNativeFullScreen) {
					document.webkitCancelFullScreen();

				} else if (t.hasMozNativeFullScreen) {
					document.mozCancelFullScreen();

				} else if (t.hasMsNativeFullScreen) {
					document.msExitFullscreen();

				}
			}

		}


		// OS X 10.5 can't do this even if it says it can :(
		if (t.hasiOSFullScreen && ua.match(/mac os x 10_5/i)) {
			t.hasNativeFullScreen = false;
			t.hasiOSFullScreen = false;
		}

	}
};
mejs.MediaFeatures.init();

/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
	pluginType: 'native',
	isFullScreen: false,

	setCurrentTime: function (time) {
		this.currentTime = time;
	},

	setMuted: function (muted) {
		this.muted = muted;
	},

	setVolume: function (volume) {
		this.volume = volume;
	},

	// for parity with the plugin versions
	stop: function () {
		this.pause();
	},

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		
		// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
		var 
			existingSources = this.getElementsByTagName('source');
		while (existingSources.length > 0){
			this.removeChild(existingSources[0]);
		}
	
		if (typeof url == 'string') {
			this.src = url;
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.src = media.src;
					break;
				}
			}
		}
	},

	setVideoSize: function (width, height) {
		this.width = width;
		this.height = height;
	}
};

/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
	this.id = pluginid;
	this.pluginType = pluginType;
	this.src = mediaUrl;
	this.events = {};
	this.attributes = {};
};

// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {

	// special
	pluginElement: null,
	pluginType: '',
	isFullScreen: false,

	// not implemented :(
	playbackRate: -1,
	defaultPlaybackRate: -1,
	seekable: [],
	played: [],

	// HTML5 read-only properties
	paused: true,
	ended: false,
	seeking: false,
	duration: 0,
	error: null,
	tagName: '',

	// HTML5 get/set properties, but only set (updated by event handlers)
	muted: false,
	volume: 1,
	currentTime: 0,

	// HTML5 methods
	play: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.playVideo();
			} else {
				this.pluginApi.playMedia();
			}
			this.paused = false;
		}
	},
	load: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
			} else {
				this.pluginApi.loadMedia();
			}
			
			this.paused = false;
		}
	},
	pause: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
		        if( this.pluginApi.getPlayerState() == 1 ) {
				    this.pluginApi.pauseVideo();
                }
			} else {
				this.pluginApi.pauseMedia();
			}			
			
			
			this.paused = true;
		}
	},
	stop: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.stopVideo();
			} else {
				this.pluginApi.stopMedia();
			}	
			this.paused = true;
		}
	},
	canPlayType: function(type) {
		var i,
			j,
			pluginInfo,
			pluginVersions = mejs.plugins[this.pluginType];

		for (i=0; i<pluginVersions.length; i++) {
			pluginInfo = pluginVersions[i];

			// test if user has the correct plugin version
			if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {

				// test for plugin playback types
				for (j=0; j<pluginInfo.types.length; j++) {
					// find plugin that can play the type
					if (type == pluginInfo.types[j]) {
						return 'probably';
					}
				}
			}
		}

		return '';
	},
	
	positionFullscreenButton: function(x,y,visibleAndAbove) {
		if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
			this.pluginApi.positionFullscreenButton(Math.floor(x),Math.floor(y),visibleAndAbove);
		}
	},
	
	hideFullscreenButton: function() {
		if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
			this.pluginApi.hideFullscreenButton();
		}		
	},	
	

	// custom methods since not all JavaScript implementations support get/set

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
			this.src = mejs.Utility.absolutizeUrl(url);
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
					this.src = mejs.Utility.absolutizeUrl(media.src);
					break;
				}
			}
		}

	},
	setCurrentTime: function (time) {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.seekTo(time);
			} else {
				this.pluginApi.setCurrentTime(time);
			}				
			
			
			
			this.currentTime = time;
		}
	},
	setVolume: function (volume) {
		if (this.pluginApi != null) {
			// same on YouTube and MEjs
			if (this.pluginType == 'youtube') {
				this.pluginApi.setVolume(volume * 100);
			} else {
				this.pluginApi.setVolume(volume);
			}
			this.volume = volume;
		}
	},
	setMuted: function (muted) {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube') {
				if (muted) {
					this.pluginApi.mute();
				} else {
					this.pluginApi.unMute();
				}
				this.muted = muted;
				this.dispatchEvent({type:'volumechange'});
			} else {
				this.pluginApi.setMuted(muted);
			}
			this.muted = muted;
		}
	},

	// additional non-HTML5 methods
	setVideoSize: function (width, height) {
		
		//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
			if (this.pluginElement && this.pluginElement.style) {
				this.pluginElement.style.width = width + 'px';
				this.pluginElement.style.height = height + 'px';
			}
			if (this.pluginApi != null && this.pluginApi.setVideoSize) {
				this.pluginApi.setVideoSize(width, height);
			}
		//}
	},

	setFullscreen: function (fullscreen) {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.pluginApi.setFullscreen(fullscreen);
		}
	},
	
	enterFullScreen: function() {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.setFullscreen(true);
		}		
		
	},
	
	exitFullScreen: function() {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.setFullscreen(false);
		}
	},	

	// start: fake events
	addEventListener: function (eventName, callback, bubble) {
		this.events[eventName] = this.events[eventName] || [];
		this.events[eventName].push(callback);
	},
	removeEventListener: function (eventName, callback) {
		if (!eventName) { this.events = {}; return true; }
		var callbacks = this.events[eventName];
		if (!callbacks) return true;
		if (!callback) { this.events[eventName] = []; return true; }
		for (var i = 0; i < callbacks.length; i++) {
			if (callbacks[i] === callback) {
				this.events[eventName].splice(i, 1);
				return true;
			}
		}
		return false;
	},	
	dispatchEvent: function (event) {
		var i,
			args,
			callbacks = this.events[event.type];

		if (callbacks) {
			for (i = 0; i < callbacks.length; i++) {
				callbacks[i].apply(this, [event]);
			}
		}
	},
	// end: fake events
	
	// fake DOM attribute methods
	hasAttribute: function(name){
		return (name in this.attributes);  
	},
	removeAttribute: function(name){
		delete this.attributes[name];
	},
	getAttribute: function(name){
		if (this.hasAttribute(name)) {
			return this.attributes[name];
		}
		return null;
	},
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},

	remove: function() {
		mejs.Utility.removeSwf(this.pluginElement.id);
	}
};

/*
Default options
*/
mejs.MediaElementDefaults = {
	// allows testing on HTML5, flash, silverlight
	// auto: attempts to detect what the browser can do
	// auto_plugin: prefer plugins and then attempt native HTML5
	// native: forces HTML5 playback
	// shim: disallows HTML5, will attempt either Flash or Silverlight
	// none: forces fallback view
	mode: 'auto',
	// remove or reorder to change plugin priority and availability
	plugins: ['flash','silverlight','youtube','vimeo'],
	// shows debug errors on screen
	enablePluginDebug: false,
	// use plugin for browsers that have trouble with Basic Authentication on HTTPS sites
	httpsBasicAuthSite: false,
	// overrides the type specified, useful for dynamic instantiation
	type: '',
	// path to Flash and Silverlight plugins
	pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
	// name of flash file
	flashName: 'flashmediaelement.swf',
	// streamer for RTMP streaming
	flashStreamer: '',
	// set to 'always' for CDN version
	flashScriptAccess: 'sameDomain',	
	// turns on the smoothing filter in Flash
	enablePluginSmoothing: false,
	// enabled pseudo-streaming (seek) on .mp4 files
	enablePseudoStreaming: false,
	// start query parameter sent to server for pseudo-streaming
	pseudoStreamingStartQueryParam: 'start',
	// name of silverlight file
	silverlightName: 'silverlightmediaelement.xap',
	// default if the <video width> is not specified
	defaultVideoWidth: 480,
	// default if the <video height> is not specified
	defaultVideoHeight: 270,
	// overrides <video width>
	pluginWidth: -1,
	// overrides <video height>
	pluginHeight: -1,
	// additional plugin variables in 'key=value' form
	pluginVars: [],	
	// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
	// larger number is less accurate, but less strain on plugin->JavaScript bridge
	timerRate: 250,
	// initial volume for player
	startVolume: 0.8,
	// custom error message in case media cannot be played; otherwise, Download File
	// link will be displayed
	customError: "",
	success: function () { },
	error: function () { }
};

/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
	return mejs.HtmlMediaElementShim.create(el,o);
};

mejs.HtmlMediaElementShim = {

	create: function(el, o) {
		var
			options = {},
			htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
			tagName = htmlMediaElement.tagName.toLowerCase(),
			isMediaTag = (tagName === 'audio' || tagName === 'video'),
			src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
			poster = htmlMediaElement.getAttribute('poster'),
			autoplay =  htmlMediaElement.getAttribute('autoplay'),
			preload =  htmlMediaElement.getAttribute('preload'),
			controls =  htmlMediaElement.getAttribute('controls'),
			playback,
			prop;

		// extend options
		for (prop in mejs.MediaElementDefaults) {
			options[prop] = mejs.MediaElementDefaults[prop];
		}
		for (prop in o) {
			options[prop] = o[prop];
		}		
		

		// clean up attributes
		src = 		(typeof src == 'undefined' 	|| src === null || src == '') ? null : src;		
		poster =	(typeof poster == 'undefined' 	|| poster === null) ? '' : poster;
		preload = 	(typeof preload == 'undefined' 	|| preload === null || preload === 'false') ? 'none' : preload;
		autoplay = 	!(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
		controls = 	!(typeof controls == 'undefined' || controls === null || controls === 'false');

		// test for HTML5 and plugin capabilities
		playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
		playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
        	playback.scheme = mejs.Utility.determineScheme(playback.url);

		if (playback.method == 'native') {
			// second fix for android
			if (mejs.MediaFeatures.isBustedAndroid) {
				htmlMediaElement.src = playback.url;
				htmlMediaElement.addEventListener('click', function() {
					htmlMediaElement.play();
				}, false);
			}
		
			// add methods to native HTMLMediaElement
			return this.updateNative(playback, options, autoplay, preload);
		} else if (playback.method !== '') {
			// create plugin to mimic HTMLMediaElement
			
			return this.createPlugin( playback,  options, poster, autoplay, preload, controls);
		} else {
			// boo, no HTML5, no Flash, no Silverlight.
			this.createErrorMessage( playback, options, poster );
			
			return this;
		}
	},
	
	determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
		var
			mediaFiles = [],
			i,
			j,
			k,
			l,
			n,
			type,
			result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() !== 'audio'), scheme: ''},
			pluginName,
			pluginVersions,
			pluginInfo,
			dummy,
			media;
			
		// STEP 1: Get URL and type from <video src> or <source src>

		// supplied type overrides <video type> and <source type>
		if (typeof options.type != 'undefined' && options.type !== '') {
			
			// accept either string or array of types
			if (typeof options.type == 'string') {
				mediaFiles.push({type:options.type, url:src});
			} else {
				
				for (i=0; i<options.type.length; i++) {
					mediaFiles.push({type:options.type[i], url:src});
				}
			}

		// test for src attribute first
		} else if (src !== null) {
			type = this.formatType(src, htmlMediaElement.getAttribute('type'));
			mediaFiles.push({type:type, url:src});

		// then test for <source> elements
		} else {
			// test <source> types to see if they are usable
			for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
				n = htmlMediaElement.childNodes[i];
				if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
					src = n.getAttribute('src');
					type = this.formatType(src, n.getAttribute('type'));
					media = n.getAttribute('media');

					if (!media || !window.matchMedia || (window.matchMedia && window.matchMedia(media).matches)) {
						mediaFiles.push({type:type, url:src});
					}
				}
			}
		}
		
		// in the case of dynamicly created players
		// check for audio types
		if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
			result.isVideo = false;
		}
		

		// STEP 2: Test for playback method
		
		// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
		if (result.isVideo && mejs.MediaFeatures.isBustedAndroid) {
			htmlMediaElement.canPlayType = function(type) {
				return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
			};
		}		
		
		// special case for Chromium to specify natively supported video codecs (i.e. WebM and Theora) 
		if (result.isVideo && mejs.MediaFeatures.isChromium) {
			htmlMediaElement.canPlayType = function(type) { 
				return (type.match(/video\/(webm|ogv|ogg)/gi) !== null) ? 'maybe' : '';
			}; 
		}

		// test for native playback first
		if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')  && !(mejs.MediaFeatures.isBustedNativeHTTPS && options.httpsBasicAuthSite === true)) {
						
			if (!isMediaTag) {

				// create a real HTML5 Media Element 
				dummy = document.createElement( result.isVideo ? 'video' : 'audio');			
				htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
				htmlMediaElement.style.display = 'none';
				
				// use this one from now on
				result.htmlMediaElement = htmlMediaElement = dummy;
			}
				
			for (i=0; i<mediaFiles.length; i++) {
				// normal check
				if (mediaFiles[i].type == "video/m3u8" || htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
					// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
					|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== ''
					// special case for m4a supported by detecting mp4 support
					|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/m4a/,'mp4')).replace(/no/, '') !== '') {
					result.method = 'native';
					result.url = mediaFiles[i].url;
					break;
				}
			}			
			
			if (result.method === 'native') {
				if (result.url !== null) {
					htmlMediaElement.src = result.url;
				}
			
				// if `auto_plugin` mode, then cache the native result but try plugins.
				if (options.mode !== 'auto_plugin') {
					return result;
				}
			}
		}

		// if native playback didn't work, then test plugins
		if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
			for (i=0; i<mediaFiles.length; i++) {
				type = mediaFiles[i].type;

				// test all plugins in order of preference [silverlight, flash]
				for (j=0; j<options.plugins.length; j++) {

					pluginName = options.plugins[j];
			
					// test version of plugin (for future features)
					pluginVersions = mejs.plugins[pluginName];				
					
					for (k=0; k<pluginVersions.length; k++) {
						pluginInfo = pluginVersions[k];
					
						// test if user has the correct plugin version
						
						// for youtube/vimeo
						if (pluginInfo.version == null || 
							
							mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {

							// test for plugin playback types
							for (l=0; l<pluginInfo.types.length; l++) {
								// find plugin that can play the type
								if (type.toLowerCase() == pluginInfo.types[l].toLowerCase()) {
									result.method = pluginName;
									result.url = mediaFiles[i].url;
									return result;
								}
							}
						}
					}
				}
			}
		}
		
		// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
		// if we have native support then return that.
		if (options.mode === 'auto_plugin' && result.method === 'native') {
			return result;
		}

		// what if there's nothing to play? just grab the first available
		if (result.method === '' && mediaFiles.length > 0) {
			result.url = mediaFiles[0].url;
		}

		return result;
	},

	formatType: function(url, type) {
		// if no type is supplied, fake it with the extension
		if (url && !type) {		
			return this.getTypeFromFile(url);
		} else {
			// only return the mime part of the type in case the attribute contains the codec
			// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
			// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
			
			if (type && ~type.indexOf(';')) {
				return type.substr(0, type.indexOf(';')); 
			} else {
				return type;
			}
		}
	},
	
	getTypeFromFile: function(url) {
		url = url.split('?')[0];
		var
			ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase(),
			av = /(mp4|m4v|ogg|ogv|m3u8|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video/' : 'audio/';
		return this.getTypeFromExtension(ext, av);
	},
	
	getTypeFromExtension: function(ext, av) {
		av = av || '';
		
		switch (ext) {
			case 'mp4':
			case 'm4v':
			case 'm4a':
			case 'f4v':
			case 'f4a':
				return av + 'mp4';
			case 'flv':
				return av + 'x-flv';
			case 'webm':
			case 'webma':
			case 'webmv':	
				return av + 'webm';
			case 'ogg':
			case 'oga':
			case 'ogv':	
				return av + 'ogg';
			case 'm3u8':
				return 'application/x-mpegurl';
			case 'ts':
				return av + 'mp2t';
			default:
				return av + ext;
		}
	},

	createErrorMessage: function(playback, options, poster) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			errorContainer = document.createElement('div'),
			errorContent = options.customError;
			
		errorContainer.className = 'me-cannotplay';

		try {
			errorContainer.style.width = htmlMediaElement.width + 'px';
			errorContainer.style.height = htmlMediaElement.height + 'px';
		} catch (e) {}

		if (!errorContent) {
			errorContent = '<a href="' + playback.url + '">';

			if (poster !== '') {
				errorContent += '<img src="' + poster + '" width="100%" height="100%" alt="" />';
			}

			errorContent += '<span>' + mejs.i18n.t('mejs.download-file') + '</span></a>';
		}

		errorContainer.innerHTML = errorContent;

		htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
		htmlMediaElement.style.display = 'none';

		options.error(htmlMediaElement);
	},

	createPlugin:function(playback, options, poster, autoplay, preload, controls) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			width = 1,
			height = 1,
			pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
			pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
			container = document.createElement('div'),
			specialIEContainer,
			node,
			initVars;

		// copy tagName from html media element
		pluginMediaElement.tagName = htmlMediaElement.tagName;

		// copy attributes from html media element to plugin media element
		for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
			var attribute = htmlMediaElement.attributes[i];
			if (attribute.specified) {
				pluginMediaElement.setAttribute(attribute.name, attribute.value);
			}
		}

		// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
		node = htmlMediaElement.parentNode;

		while (node !== null && node.tagName != null && node.tagName.toLowerCase() !== 'body' && 
				node.parentNode != null && node.parentNode.tagName != null && node.parentNode.constructor != null && node.parentNode.constructor.name === "ShadowRoot") {
			if (node.parentNode.tagName.toLowerCase() === 'p') {
				node.parentNode.parentNode.insertBefore(node, node.parentNode);
				break;
			}
			node = node.parentNode;
		}

		if (playback.isVideo) {
			width = (options.pluginWidth > 0) ? options.pluginWidth : (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
			height = (options.pluginHeight > 0) ? options.pluginHeight : (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
		
			// in case of '%' make sure it's encoded
			width = mejs.Utility.encodeUrl(width);
			height = mejs.Utility.encodeUrl(height);
		
		} else {
			if (options.enablePluginDebug) {
				width = 320;
				height = 240;
			}
		}

		// register plugin
		pluginMediaElement.success = options.success;
		
		// add container (must be added to DOM before inserting HTML for IE)
		container.className = 'me-plugin';
		container.id = pluginid + '_container';
		
		if (playback.isVideo) {
				htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
		} else {
				document.body.insertBefore(container, document.body.childNodes[0]);
		}
		
		if (playback.method === 'flash' || playback.method === 'silverlight') {

			var canPlayVideo = htmlMediaElement.getAttribute('type') === 'audio/mp4',
				childrenSources = htmlMediaElement.getElementsByTagName('source');

			if (childrenSources && !canPlayVideo) {
				for (var i = 0, total = childrenSources.length; i < total; i++) {
					if (childrenSources[i].getAttribute('type') === 'audio/mp4') {
						canPlayVideo = true;
					}
				}
			}

			// flash/silverlight vars
			initVars = [
				'id=' + pluginid,
				'isvideo=' + ((playback.isVideo || canPlayVideo) ? "true" : "false"),
				'autoplay=' + ((autoplay) ? "true" : "false"),
				'preload=' + preload,
				'width=' + width,
				'startvolume=' + options.startVolume,
				'timerrate=' + options.timerRate,
				'flashstreamer=' + options.flashStreamer,
				'height=' + height,
				'pseudostreamstart=' + options.pseudoStreamingStartQueryParam];
	
			if (playback.url !== null) {
				if (playback.method == 'flash') {
					initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
				} else {
					initVars.push('file=' + playback.url);
				}
			}
			if (options.enablePluginDebug) {
				initVars.push('debug=true');
			}
			if (options.enablePluginSmoothing) {
				initVars.push('smoothing=true');
			}
			if (options.enablePseudoStreaming) {
				initVars.push('pseudostreaming=true');
			}
			if (controls) {
				initVars.push('controls=true'); // shows controls in the plugin if desired
			}
			if (options.pluginVars) {
				initVars = initVars.concat(options.pluginVars);
			}		
			
			// call from plugin
			window[pluginid + '_init'] = function() {
				switch (pluginMediaElement.pluginType) {
					case 'flash':
						pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(pluginid);
						break;
					case 'silverlight':
						pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
						pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
						break;
				}
	
				if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
					pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
				}
			};
			
			// event call from plugin
			window[pluginid + '_event'] = function(eventName, values) {
		
				var
					e,
					i,
					bufferedTime;
		        
				// fake event object to mimic real HTML media event.
				e = {
					type: eventName,
					target: pluginMediaElement
				};
		
				// attach all values to element and event object
				for (i in values) {
					pluginMediaElement[i] = values[i];
					e[i] = values[i];
				}
		
				// fake the newer W3C buffered TimeRange (loaded and total have been removed)
				bufferedTime = values.bufferedTime || 0;
		
				e.target.buffered = e.buffered = {
					start: function(index) {
						return 0;
					},
					end: function (index) {
						return bufferedTime;
					},
					length: 1
				};
		
				pluginMediaElement.dispatchEvent(e);
			}			
			
			
		}

		switch (playback.method) {
			case 'silverlight':
				container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
					break;

			case 'flash':

				if (mejs.MediaFeatures.isIE) {
					specialIEContainer = document.createElement('div');
					container.appendChild(specialIEContainer);
					specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?' + (new Date().getTime()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&amp;') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '" />' +
'<param name="allowFullScreen" value="true" />' +
'<param name="scale" value="default" />' + 
'</object>';

				} else {

					container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="' + options.flashScriptAccess + '" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'scale="default"' + 
'class="mejs-shim"></embed>';
				}
				break;
			
			case 'youtube':
			
				
				var videoId;
				// youtu.be url from share button
				if (playback.url.lastIndexOf("youtu.be") != -1) {
					videoId = playback.url.substr(playback.url.lastIndexOf('/')+1);
					if (videoId.indexOf('?') != -1) {
						videoId = videoId.substr(0, videoId.indexOf('?'));
					}
				}
				else {
					// https://www.youtube.com/watch?v=
					var videoIdMatch = playback.url.match( /[?&]v=([^&#]+)|&|#|$/ );
					if ( videoIdMatch ) {
						videoId = videoIdMatch[1];
					}
				}
				youtubeSettings = {
						container: container,
						containerId: container.id,
						pluginMediaElement: pluginMediaElement,
						pluginId: pluginid,
						videoId: videoId,
						height: height,
						width: width,
                        scheme: playback.scheme,
						variables: options.youtubeIframeVars
					};				
				
				// favor iframe version of YouTube
				if (window.postMessage) {
					mejs.YouTubeApi.enqueueIframe(youtubeSettings);		
				} else if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
					mejs.YouTubeApi.createFlash(youtubeSettings, options);
				}
				break;
			
			// DEMO Code. Does NOT work.
			case 'vimeo':
				var player_id = pluginid + "_player";
				pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
				
				container.innerHTML ='<iframe src="' + playback.scheme + 'player.vimeo.com/video/' + pluginMediaElement.vimeoid + '?api=1&portrait=0&byline=0&title=0&player_id=' + player_id + '" width="' + width +'" height="' + height +'" frameborder="0" class="mejs-shim" id="' + player_id + '" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
				if (typeof($f) == 'function') { // froogaloop available
					var player = $f(container.childNodes[0]),
						playerState = -1;
					
					player.addEvent('ready', function() {
		
						player.playVideo = function() {
							player.api( 'play' );
						};
						player.stopVideo = function() {
							player.api( 'unload' );
						};
						player.pauseVideo = function() {
							player.api( 'pause' );
						};
						player.seekTo = function( seconds ) {
							player.api( 'seekTo', seconds );
						};
						player.setVolume = function( volume ) {
							player.api( 'setVolume', volume );
						};
						player.setMuted = function( muted ) {
							if( muted ) {
								player.lastVolume = player.api( 'getVolume' );
								player.api( 'setVolume', 0 );
							} else {
								player.api( 'setVolume', player.lastVolume );
								delete player.lastVolume;
							}
						};
						// parity with YT player
						player.getPlayerState = function() {
							return playerState;
						};

						function createEvent(player, pluginMediaElement, eventName, e) {
							var event = {
								type: eventName,
								target: pluginMediaElement
							};
							if (eventName == 'timeupdate') {
								pluginMediaElement.currentTime = event.currentTime = e.seconds;
								pluginMediaElement.duration = event.duration = e.duration;
							}
							pluginMediaElement.dispatchEvent(event);
						}

						player.addEvent('play', function() {
							playerState = 1;
							createEvent(player, pluginMediaElement, 'play');
							createEvent(player, pluginMediaElement, 'playing');
						});

						player.addEvent('pause', function() {
							playerState = 2;							
							createEvent(player, pluginMediaElement, 'pause');
						});

						player.addEvent('finish', function() {
							playerState = 0;							
							createEvent(player, pluginMediaElement, 'ended');
						});

						player.addEvent('playProgress', function(e) {
							createEvent(player, pluginMediaElement, 'timeupdate', e);
						});
						
						player.addEvent('seek', function(e) {
							playerState = 3;
							createEvent(player, pluginMediaElement, 'seeked', e);
						});	
						
						player.addEvent('loadProgress', function(e) {
							playerState = 3;
							createEvent(player, pluginMediaElement, 'progress', e);
						});												

						pluginMediaElement.pluginElement = container;
						pluginMediaElement.pluginApi = player;

						pluginMediaElement.success(pluginMediaElement, pluginMediaElement.pluginElement);						
					});
				}
				else {
					console.warn("You need to include froogaloop for vimeo to work");
				}
				break;			
		}
		// hide original element
		htmlMediaElement.style.display = 'none';
		// prevent browser from autoplaying when using a plugin
		htmlMediaElement.removeAttribute('autoplay');
		
		return pluginMediaElement;
	},

	updateNative: function(playback, options, autoplay, preload) {
		
		var htmlMediaElement = playback.htmlMediaElement,
			m;
		
		
		// add methods to video object to bring it into parity with Flash Object
		for (m in mejs.HtmlMediaElement) {
			htmlMediaElement[m] = mejs.HtmlMediaElement[m];
		}

		/*
		Chrome now supports preload="none"
		if (mejs.MediaFeatures.isChrome) {
		
			// special case to enforce preload attribute (Chrome doesn't respect this)
			if (preload === 'none' && !autoplay) {
			
				// forces the browser to stop loading (note: fails in IE9)
				htmlMediaElement.src = '';
				htmlMediaElement.load();
				htmlMediaElement.canceledPreload = true;

				htmlMediaElement.addEventListener('play',function() {
					if (htmlMediaElement.canceledPreload) {
						htmlMediaElement.src = playback.url;
						htmlMediaElement.load();
						htmlMediaElement.play();
						htmlMediaElement.canceledPreload = false;
					}
				}, false);
			// for some reason Chrome forgets how to autoplay sometimes.
			} else if (autoplay) {
				htmlMediaElement.load();
				htmlMediaElement.play();
			}
		}
		*/

		// fire success code
		options.success(htmlMediaElement, htmlMediaElement);
		
		return htmlMediaElement;
	}
};

/*
 - test on IE (object vs. embed)
 - determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
 - fullscreen?
*/

// YouTube Flash and Iframe API
mejs.YouTubeApi = {
	isIframeStarted: false,
	isIframeLoaded: false,
	loadIframeApi: function(yt) {
		if (!this.isIframeStarted) {
			var tag = document.createElement('script');
			tag.src = yt.scheme + "www.youtube.com/player_api";
			var firstScriptTag = document.getElementsByTagName('script')[0];
			firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			this.isIframeStarted = true;
		}
	},
	iframeQueue: [],
	enqueueIframe: function(yt) {
		
		if (this.isLoaded) {
			this.createIframe(yt);
		} else {
			this.loadIframeApi(yt);
			this.iframeQueue.push(yt);
		}
	},
	createIframe: function(settings) {

		var
		pluginMediaElement = settings.pluginMediaElement,
		defaultVars = {controls:0, wmode:'transparent'},
		player = new YT.Player(settings.containerId, {
			height: settings.height,
			width: settings.width,
			videoId: settings.videoId,
			playerVars: mejs.$.extend({}, defaultVars, settings.variables),
			events: {
				'onReady': function(e) {
					
					// wrapper to match
					player.setVideoSize = function(width, height) {
						player.setSize(width, height);
					};
					
					// hook up iframe object to MEjs
					settings.pluginMediaElement.pluginApi = player;
					settings.pluginMediaElement.pluginElement = document.getElementById(settings.containerId);
					
					// init mejs
					pluginMediaElement.success(pluginMediaElement, pluginMediaElement.pluginElement);

					mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
					
					// create timer
					setInterval(function() {
						mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
					}, 250);

					if (typeof pluginMediaElement.attributes.autoplay !== 'undefined') {
						player.playVideo();
					}
				},
				'onStateChange': function(e) {
					
					mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
					
				}
			}
		});
	},
	
	createEvent: function (player, pluginMediaElement, eventName) {
		var event = {
			type: eventName,
			target: pluginMediaElement
		};

		if (player && player.getDuration) {
			
			// time 
			pluginMediaElement.currentTime = event.currentTime = player.getCurrentTime();
			pluginMediaElement.duration = event.duration = player.getDuration();
			
			// state
			event.paused = pluginMediaElement.paused;
			event.ended = pluginMediaElement.ended;			
			
			// sound
			event.muted = player.isMuted();
			event.volume = player.getVolume() / 100;
			
			// progress
			event.bytesTotal = player.getVideoBytesTotal();
			event.bufferedBytes = player.getVideoBytesLoaded();
			
			// fake the W3C buffered TimeRange
			var bufferedTime = event.bufferedBytes / event.bytesTotal * event.duration;
			
			event.target.buffered = event.buffered = {
				start: function(index) {
					return 0;
				},
				end: function (index) {
					return bufferedTime;
				},
				length: 1
			};

		}
		
		// send event up the chain
		pluginMediaElement.dispatchEvent(event);
	},	
	
	iFrameReady: function() {
		
		this.isLoaded = true;
		this.isIframeLoaded = true;
		
		while (this.iframeQueue.length > 0) {
			var settings = this.iframeQueue.pop();
			this.createIframe(settings);
		}	
	},
	
	// FLASH!
	flashPlayers: {},
	createFlash: function(settings) {
		
		this.flashPlayers[settings.pluginId] = settings;
		
		/*
		settings.container.innerHTML =
			'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + settings.scheme + 'www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId  + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0" ' +
				'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
				'<param name="allowScriptAccess" value="sameDomain">' +
				'<param name="wmode" value="transparent">' +
			'</object>';
		*/

		var specialIEContainer,
			youtubeUrl = settings.scheme + 'www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId  + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0';
			
		if (mejs.MediaFeatures.isIE) {
			
			specialIEContainer = document.createElement('div');
			settings.container.appendChild(specialIEContainer);
			specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + settings.scheme + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '" class="mejs-shim">' +
	'<param name="movie" value="' + youtubeUrl + '" />' +
	'<param name="wmode" value="transparent" />' +
	'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '" />' +
	'<param name="allowFullScreen" value="true" />' +
'</object>';
		} else {
		settings.container.innerHTML =
			'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
				'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
				'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '">' +
				'<param name="wmode" value="transparent">' +
			'</object>';
		}		
		
	},
	
	flashReady: function(id) {
		var
			settings = this.flashPlayers[id],
			player = document.getElementById(id),
			pluginMediaElement = settings.pluginMediaElement;
		
		// hook up and return to MediaELementPlayer.success	
		pluginMediaElement.pluginApi = 
		pluginMediaElement.pluginElement = player;
		
		settings.success(pluginMediaElement, pluginMediaElement.pluginElement);
		
		// load the youtube video
		player.cueVideoById(settings.videoId);
		
		var callbackName = settings.containerId + '_callback';
		
		window[callbackName] = function(e) {
			mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
		};
		
		player.addEventListener('onStateChange', callbackName);
		
		setInterval(function() {
			mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
		}, 250);
		
		mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
	},
	
	handleStateChange: function(youTubeState, player, pluginMediaElement) {
		switch (youTubeState) {
			case -1: // not started
				pluginMediaElement.paused = true;
				pluginMediaElement.ended = true;
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
				//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
				break;
			case 0:
				pluginMediaElement.paused = false;
				pluginMediaElement.ended = true;
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
				break;
			case 1:
				pluginMediaElement.paused = false;
				pluginMediaElement.ended = false;				
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
				break;
			case 2:
				pluginMediaElement.paused = true;
				pluginMediaElement.ended = false;				
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
				break;
			case 3: // buffering
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
				break;
			case 5:
				// cued?
				break;						
			
		}			
		
	}
}
// IFRAME
window.onYouTubePlayerAPIReady = function() {
	mejs.YouTubeApi.iFrameReady();
};
// FLASH
window.onYouTubePlayerReady = function(id) {
	mejs.YouTubeApi.flashReady(id);
};

window.mejs = mejs;
window.MediaElement = mejs.MediaElement;

/**
 * Localize strings
 *
 * Include translations from JS files and method to pluralize properly strings.
 *
 */
(function (doc, win, mejs, undefined) {

	var i18n = {
		/**
		 * @type {String}
		 */
		'default': 'en',

		/**
		 * @type {String[]}
		 */
		locale: {
			language: (mejs.i18n && mejs.i18n.locale.language) || '',
			strings: (mejs.i18n && mejs.i18n.locale.strings) || {}
		},

		/**
		 * Filters for available languages.
		 *
		 * This plural forms are grouped in family groups based on
		 * https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules
		 * with some additions and corrections according to the Localization Guide list
		 * (http://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html)
		 *
		 * Arguments are dynamic following the structure:
		 * - argument1 : Number to determine form
		 * - argument2...argumentN: Possible matches
		 *
		 * @type {Function[]}
		 */
		pluralForms: [
			// 0: Chinese, Japanese, Korean, Persian, Turkish, Thai, Lao, Aymará,
			// Tibetan, Chiga, Dzongkha, Indonesian, Lojban, Georgian, Kazakh, Khmer, Kyrgyz, Malay,
			// Burmese, Yakut, Sundanese, Tatar, Uyghur, Vietnamese, Wolof
			function () {
				return arguments[1];
			},
			// 1: Danish, Dutch, English, Faroese, Frisian, German, Norwegian, Swedish, Estonian, Finnish,
			// Hungarian, Basque, Greek, Hebrew, Italian, Portuguese, Spanish, Catalan, Afrikaans,
			// Angika, Assamese, Asturian, Azerbaijani, Bulgarian, Bengali, Bodo, Aragonese, Dogri,
			// Esperanto, Argentinean Spanish, Fulah, Friulian, Galician, Gujarati, Hausa,
			// Hindi, Chhattisgarhi, Armenian, Interlingua, Greenlandic, Kannada, Kurdish, Letzeburgesch,
			// Maithili, Malayalam, Mongolian, Manipuri, Marathi, Nahuatl, Neapolitan, Norwegian Bokmal,
			// Nepali, Norwegian Nynorsk, Norwegian (old code), Northern Sotho, Oriya, Punjabi, Papiamento,
			// Piemontese, Pashto, Romansh, Kinyarwanda, Santali, Scots, Sindhi, Northern Sami, Sinhala,
			// Somali, Songhay, Albanian, Swahili, Tamil, Telugu, Turkmen, Urdu, Yoruba
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 2: French, Brazilian Portuguese, Acholi, Akan, Amharic, Mapudungun, Breton, Filipino,
			// Gun, Lingala, Mauritian Creole, Malagasy, Maori, Occitan, Tajik, Tigrinya, Uzbek, Walloon
			function () {
				var args = arguments;
				if ([0, 1].indexOf(args[0]) > -1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 3: Latvian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] !== 0) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 4: Scottish Gaelic
			function () {
				var args = arguments;
				if (args[0] === 1 || args[0] === 11) {
					return args[1];
				} else if (args[0] === 2 || args[0] === 12) {
					return args[2];
				} else if (args[0] > 2 && args[0] < 20) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 5:  Romanian
			function () {
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 0 || (args[0] % 100 > 0 && args[0] % 100 < 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 6: Lithuanian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] % 10 >= 2 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return [3];
				}
			},
			// 7: Belarusian, Bosnian, Croatian, Serbian, Russian, Ukrainian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 8:  Slovak, Czech
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] >= 2 && args[0] <= 4) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 9: Polish
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 10: Slovenian
			function () {
				var args = arguments;
				if (args[0] % 100 === 1) {
					return args[2];
				} else if (args[0] % 100 === 2) {
					return args[3];
				} else if (args[0] % 100 === 3 || args[0] % 100 === 4) {
					return args[4];
				} else {
					return args[1];
				}
			},
			// 11: Irish Gaelic
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] > 2 && args[0] < 7) {
					return args[3];
				} else if (args[0] > 6 && args[0] < 11) {
					return args[4];
				} else {
					return args[5];
				}
			},
			// 12: Arabic
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else if (args[0] === 1) {
					return args[2];
				} else if (args[0] === 2) {
					return args[3];
				} else if (args[0] % 100 >= 3 && args[0] % 100 <= 10) {
					return args[4];
				} else if (args[0] % 100 >= 11) {
					return args[5];
				} else {
					return args[6];
				}
			},
			// 13: Maltese
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 0 || (args[0] % 100 > 1 && args[0] % 100 < 11)) {
					return args[2];
				} else if (args[0] % 100 > 10 && args[0] % 100 < 20) {
					return args[3];
				} else {
					return args[4];
				}

			},
			// 14: Macedonian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1) {
					return args[1];
				} else if (args[0] % 10 === 2) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 15:  Icelandic
			function () {
				var args = arguments;
				if (args[0] !== 11 && args[0] % 10 === 1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// New additions

			// 16:  Kashubian
			// Note: in https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules
			// Breton is listed as #16 but in the Localization Guide it belongs to the group 2
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 17:  Welsh
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] !== 8 && args[0] !== 11) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 18:  Javanese
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 19:  Cornish
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] === 3) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 20:  Mandinka
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else if (args[0] === 1) {
					return args[2];
				} else {
					return args[3];
				}
			}
		],
		/**
		 * Get specified language
		 *
		 */
		getLanguage: function () {
			var language = i18n.locale.language || i18n['default'];
			return /^(x\-)?[a-z]{2,}(\-\w{2,})?(\-\w{2,})?$/.exec(language) ? language : i18n['default'];
		},

		/**
		 * Translate a string to a specified language, including optionally a number to pluralize translation
		 *
		 * @param {String} message
		 * @param {Number} pluralParam
		 * @return {String}
		 */
		t: function (message, pluralParam) {

			if (typeof message === 'string' && message.length) {

				var
					language = i18n.getLanguage(),
					str,
					pluralForm,
					/**
					 * Modify string using algorithm to detect plural forms.
					 *
					 * @private
					 * @see http://stackoverflow.com/questions/1353408/messageformat-in-javascript-parameters-in-localized-ui-strings
					 * @param {String|String[]} input   - String or array of strings to pick the plural form
					 * @param {Number} number           - Number to determine the proper plural form
					 * @param {Number} form             - Number of language family to apply plural form
					 * @return {String}
					 */
					plural = function (input, number, form) {

						if (typeof input !== 'object' || typeof number !== 'number' || typeof form !== 'number') {
							return input;
						}

						if (typeof input === 'string') {
							return input;
						}

						// Perform plural form or return original text
						return i18n.pluralForms[form].apply(null, [number].concat(input));
					},
					/**
					 *
					 * @param {String} input
					 * @return {String}
					 */
					escapeHTML = function (input) {
						var map = {
							'&': '&amp;',
							'<': '&lt;',
							'>': '&gt;',
							'"': '&quot;'
						};

						return input.replace(/[&<>"]/g, function(c) {
							return map[c];
						});
					}
				;

				// Fetch the localized version of the string
				if (i18n.locale.strings && i18n.locale.strings[language]) {
					str = i18n.locale.strings[language][message];
					if (typeof pluralParam === 'number') {
						pluralForm = i18n.locale.strings[language]['mejs.plural-form'];
						str = plural.apply(null, [str, pluralParam, pluralForm]);
					}
				}

				// Fallback to default language if requested uid is not translated
				if (!str && i18n.locale.strings && i18n.locale.strings[i18n['default']]) {
					str = i18n.locale.strings[i18n['default']][message];
					if (typeof pluralParam === 'number') {
						pluralForm = i18n.locale.strings[i18n['default']]['mejs.plural-form'];
						str = plural.apply(null, [str, pluralParam, pluralForm]);

					}
				}

				// As a last resort, use the requested uid, to mimic original behavior of i18n utils (in which uid was the english text)
				str = str || message;

				// Replace token
				if (typeof pluralParam === 'number') {
					str = str.replace('%1', pluralParam);
				}

				return escapeHTML(str);

			}

			return message;
		}

	};

	// i18n fixes for compatibility with WordPress
	if (typeof mejsL10n !== 'undefined') {
		i18n.locale.language = mejsL10n.language;
	}

	// Register variable
	mejs.i18n = i18n;


}(document, window, mejs));

// i18n fixes for compatibility with WordPress
;(function (mejs, undefined) {

	"use strict";

	if (typeof mejsL10n !== 'undefined') {
		mejs[mejsL10n.language] = mejsL10n.strings;
	}

}(mejs.i18n.locale.strings));
/*!
 * This is a i18n.locale language object.
 *
 * English; This can serve as a template for other languages to translate
 *
 * @author
 *   TBD
 *   Sascha Greuel (Twitter: @SoftCreatR)
 *
 * @see
 *   me-i18n.js
 *
 * @params
 *  - exports - CommonJS, window ..
 */
(function (exports) {
    "use strict";

    if (exports.en === undefined) {
        exports.en = {
            "mejs.plural-form": 1,

            // me-shim
            "mejs.download-file": "Download File",

            // mep-feature-contextmenu
            "mejs.fullscreen-off": "Turn off Fullscreen",
            "mejs.fullscreen-on": "Go Fullscreen",
            "mejs.download-video": "Download Video",

            // mep-feature-fullscreen
            "mejs.fullscreen": "Fullscreen",

            // mep-feature-jumpforward
            "mejs.time-jump-forward": ["Jump forward 1 second", "Jump forward %1 seconds"],

            // mep-feature-playpause
            "mejs.play": "Play",
            "mejs.pause": "Pause",

            // mep-feature-postroll
            "mejs.close": "Close",

            // mep-feature-progress
            "mejs.time-slider": "Time Slider",
            "mejs.time-help-text": "Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.",

            // mep-feature-skipback
            "mejs.time-skip-back": ["Skip back 1 second", "Skip back %1 seconds"],

            // mep-feature-tracks
            "mejs.captions-subtitles": "Captions/Subtitles",
            "mejs.none": "None",

            // mep-feature-volume
            "mejs.mute-toggle": "Mute Toggle",
            "mejs.volume-help-text": "Use Up/Down Arrow keys to increase or decrease volume.",
            "mejs.unmute": "Unmute",
            "mejs.mute": "Mute",
            "mejs.volume-slider": "Volume Slider",

            // mep-player
            "mejs.video-player": "Video Player",
            "mejs.audio-player": "Audio Player",

            // mep-feature-ads
            "mejs.ad-skip": "Skip ad",
            "mejs.ad-skip-info": ["Skip in 1 second", "Skip in %1 seconds"],

            // mep-feature-sourcechooser
            "mejs.source-chooser": "Source Chooser"
        };
    }
}(mejs.i18n.locale.strings));

/*!
 *
 * MediaElementPlayer
 * http://mediaelementjs.com/
 *
 * Creates a controller bar for HTML5 <video> add <audio> tags
 * using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
 *
 * Copyright 2010-2013, John Dyer (http://j.hn/)
 * License: MIT
 *
 */
if (typeof jQuery != 'undefined') {
	mejs.$ = jQuery;
} else if (typeof Zepto != 'undefined') {
	mejs.$ = Zepto;

	// define `outerWidth` method which has not been realized in Zepto
	Zepto.fn.outerWidth = function(includeMargin) {
		var width = $(this).width();
		if (includeMargin) {
			width += parseInt($(this).css('margin-right'), 10);
			width += parseInt($(this).css('margin-left'), 10);
		}
		return width
	}

} else if (typeof ender != 'undefined') {
	mejs.$ = ender;
}
(function ($) {

	// default player values
	mejs.MepDefaults = {
		// url to poster (to fix iOS 3.x)
		poster: '',
		// When the video is ended, we can show the poster.
		showPosterWhenEnded: false,
		// default if the <video width> is not specified
		defaultVideoWidth: 480,
		// default if the <video height> is not specified
		defaultVideoHeight: 270,
		// if set, overrides <video width>
		videoWidth: -1,
		// if set, overrides <video height>
		videoHeight: -1,
		// default if the user doesn't specify
		defaultAudioWidth: 400,
		// default if the user doesn't specify
		defaultAudioHeight: 30,
		// default amount to move back when back key is pressed
		defaultSeekBackwardInterval: function(media) {
			return (media.duration * 0.05);
		},
		// default amount to move forward when forward key is pressed
		defaultSeekForwardInterval: function(media) {
			return (media.duration * 0.05);
		},
		// set dimensions via JS instead of CSS
		setDimensions: true,
		// width of audio player
		audioWidth: -1,
		// height of audio player
		audioHeight: -1,
		// initial volume when the player starts (overrided by user cookie)
		startVolume: 0.8,
		// useful for <audio> player loops
		loop: false,
		// rewind to beginning when media ends
		autoRewind: true,
		// resize to media dimensions
		enableAutosize: true,
		/*
		 * Time format to use. Default: 'mm:ss'
		 * Supported units:
		 *   h: hour
		 *   m: minute
		 *   s: second
		 *   f: frame count
		 * When using 'hh', 'mm', 'ss' or 'ff' we always display 2 digits.
		 * If you use 'h', 'm', 's' or 'f' we display 1 digit if possible.
		 *
		 * Example to display 75 seconds:
		 * Format 'mm:ss': 01:15
		 * Format 'm:ss': 1:15
		 * Format 'm:s': 1:15
		 */
		timeFormat: '',
		// forces the hour marker (##:00:00)
		alwaysShowHours: false,
		// show framecount in timecode (##:00:00:00)
		showTimecodeFrameCount: false,
		// used when showTimecodeFrameCount is set to true
		framesPerSecond: 25,
		// automatically calculate the width of the progress bar based on the sizes of other elements
		autosizeProgress : true,
		// Hide controls when playing and mouse is not over the video
		alwaysShowControls: false,
		// Display the video control
		hideVideoControlsOnLoad: false,
		// Enable click video element to toggle play/pause
		clickToPlayPause: true,
		// Time in ms to hide controls
		controlsTimeoutDefault: 1500,
		// Time in ms to trigger the timer when mouse moves
		controlsTimeoutMouseEnter: 2500,
		// Time in ms to trigger the timer when mouse leaves
		controlsTimeoutMouseLeave: 1000,
		// force iPad's native controls
		iPadUseNativeControls: false,
		// force iPhone's native controls
		iPhoneUseNativeControls: false,
		// force Android's native controls
		AndroidUseNativeControls: false,
		// features to show
		features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
		// only for dynamic
		isVideo: true,
		// stretching modes (auto, fill, responsive, none)
		stretching: 'auto',
		// turns keyboard support on and off for this instance
		enableKeyboard: true,
		// when this player starts, it will pause other players
		pauseOtherPlayers: true,
		// array of keyboard actions such as play pause
		keyActions: [
				{
						keys: [
								32, // SPACE
								179 // GOOGLE play/pause button
								 ],
						action: function(player, media, key, event) {

							if (!mejs.MediaFeatures.isFirefox) {
								if (media.paused || media.ended) {
									media.play();
								} else {
									media.pause();
								}
							}
						}
				},
				{
						keys: [38], // UP
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}

								var newVolume = Math.min(media.volume + 0.1, 1);
								media.setVolume(newVolume);
						}
				},
				{
						keys: [40], // DOWN
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}

								var newVolume = Math.max(media.volume - 0.1, 0);
								media.setVolume(newVolume);
						}
				},
				{
						keys: [
								37, // LEFT
								227 // Google TV rewind
						],
						action: function(player, media, key, event) {
								if (!isNaN(media.duration) && media.duration > 0) {
										if (player.isVideo) {
												player.showControls();
												player.startControlsTimer();
										}

										// 5%
										var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
										media.setCurrentTime(newTime);
								}
						}
				},
				{
						keys: [
								39, // RIGHT
								228 // Google TV forward
						],
						action: function(player, media, key, event) {
								if (!isNaN(media.duration) && media.duration > 0) {
										if (player.isVideo) {
												player.showControls();
												player.startControlsTimer();
										}

										// 5%
										var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
										media.setCurrentTime(newTime);
								}
						}
				},
				{
						keys: [70], // F
						action: function(player, media, key, event) {
								if (typeof player.enterFullScreen != 'undefined') {
										if (player.isFullScreen) {
												player.exitFullScreen();
										} else {
												player.enterFullScreen();
										}
								}
						}
				},
				{
						keys: [77], // M
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}
								if (player.media.muted) {
										player.setMuted(false);
								} else {
										player.setMuted(true);
								}
						}
				}
		]
	};

	mejs.mepIndex = 0;

	mejs.players = {};

	// wraps a MediaElement object in player controls
	mejs.MediaElementPlayer = function(node, o) {
		// enforce object, even without "new" (via John Resig)
		if ( !(this instanceof mejs.MediaElementPlayer) ) {
			return new mejs.MediaElementPlayer(node, o);
		}

		var t = this;

		// these will be reset after the MediaElement.success fires
		t.$media = t.$node = $(node);
		t.node = t.media = t.$media[0];

		if(!t.node) {
			return;
		}

		// check for existing player
		if (typeof t.node.player != 'undefined') {
			return t.node.player;
		}


		// try to get options from data-mejsoptions
		if (typeof o == 'undefined') {
			o = t.$node.data('mejsoptions');
		}

		// extend default options
		t.options = $.extend({},mejs.MepDefaults,o);

		if (!t.options.timeFormat) {
			// Generate the time format according to options
			t.options.timeFormat = 'mm:ss';
			if (t.options.alwaysShowHours) {
				t.options.timeFormat = 'hh:mm:ss';
			}
			if (t.options.showTimecodeFrameCount) {
				t.options.timeFormat += ':ff';
			}
		}

		mejs.Utility.calculateTimeFormat(0, t.options, t.options.framesPerSecond || 25);

		// unique ID
		t.id = 'mep_' + mejs.mepIndex++;

		// add to player array (for focus events)
		mejs.players[t.id] = t;

		// start up
		t.init();

		return t;
	};

	// actual player
	mejs.MediaElementPlayer.prototype = {

		hasFocus: false,

		controlsAreVisible: true,

		init: function() {

			var
				t = this,
				mf = mejs.MediaFeatures,
				// options for MediaElement (shim)
				meOptions = $.extend(true, {}, t.options, {
					success: function(media, domNode) { t.meReady(media, domNode); },
					error: function(e) { t.handleError(e);}
				}),
				tagName = t.media.tagName.toLowerCase();

			t.isDynamic = (tagName !== 'audio' && tagName !== 'video');

			if (t.isDynamic) {
				// get video from src or href?
				t.isVideo = t.options.isVideo;
			} else {
				t.isVideo = (tagName !== 'audio' && t.options.isVideo);
			}

			// use native controls in iPad, iPhone, and Android
			if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {

				// add controls and stop
				t.$media.attr('controls', 'controls');

				// attempt to fix iOS 3 bug
				//t.$media.removeAttr('poster');
								// no Issue found on iOS3 -ttroxell

				// override Apple's autoplay override for iPads
				if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
					t.play();
				}

			} else if (mf.isAndroid && t.options.AndroidUseNativeControls) {

				// leave default player

			} else if (t.isVideo || (!t.isVideo && t.options.features.length)) {

				// DESKTOP: use MediaElementPlayer controls

				// remove native controls
				t.$media.removeAttr('controls');
				var videoPlayerTitle = t.isVideo ?
					mejs.i18n.t('mejs.video-player') : mejs.i18n.t('mejs.audio-player');
				// insert description for screen readers
				$('<span class="mejs-offscreen">' + videoPlayerTitle + '</span>').insertBefore(t.$media);
				// build container
				t.container =
					$('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svgAsImg ? 'svg' : 'no-svg') +
					  '" tabindex="0" role="application" aria-label="' + videoPlayerTitle + '">'+
						'<div class="mejs-inner">'+
							'<div class="mejs-mediaelement"></div>'+
							'<div class="mejs-layers"></div>'+
							'<div class="mejs-controls"></div>'+
							'<div class="mejs-clear"></div>'+
						'</div>' +
					'</div>')
					.addClass(t.$media[0].className)
					.insertBefore(t.$media)
					.focus(function ( e ) {
						if( !t.controlsAreVisible && !t.hasFocus && t.controlsEnabled) {
							t.showControls(true);
							// In versions older than IE11, the focus causes the playbar to be displayed
							// if user clicks on the Play/Pause button in the control bar once it attempts
							// to hide it
							if (!t.hasMsNativeFullScreen) {
								// If e.relatedTarget appears before container, send focus to play button,
								// else send focus to last control button.
								var btnSelector = '.mejs-playpause-button > button';

								if (mejs.Utility.isNodeAfter(e.relatedTarget, t.container[0])) {
									btnSelector = '.mejs-controls .mejs-button:last-child > button';
								}

								var button = t.container.find(btnSelector);
								button.focus();
							}
						}
					});

				// When no elements in controls, hide bar completely
				if (!t.options.features.length) {
					t.container.css('background', 'transparent').find('.mejs-controls').hide();
				}
 
				if (t.isVideo && t.options.stretching === 'fill' && !t.container.parent('mejs-fill-container').length) {
					// outer container
					t.outerContainer = t.$media.parent();
					t.container.wrap('<div class="mejs-fill-container"/>');
				}

				// add classes for user and content
				t.container.addClass(
					(mf.isAndroid ? 'mejs-android ' : '') +
					(mf.isiOS ? 'mejs-ios ' : '') +
					(mf.isiPad ? 'mejs-ipad ' : '') +
					(mf.isiPhone ? 'mejs-iphone ' : '') +
					(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
				);


				// move the <video/video> tag into the right spot
				t.container.find('.mejs-mediaelement').append(t.$media);

				// needs to be assigned here, after iOS remap
				t.node.player = t;

				// find parts
				t.controls = t.container.find('.mejs-controls');
				t.layers = t.container.find('.mejs-layers');

				// determine the size

				/* size priority:
					(1) videoWidth (forced),
					(2) style="width;height;"
					(3) width attribute,
					(4) defaultVideoWidth (for unspecified cases)
				*/

				var tagType = (t.isVideo ? 'video' : 'audio'),
					capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);



				if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
					t.width = t.options[tagType + 'Width'];
				} else if (t.media.style.width !== '' && t.media.style.width !== null) {
					t.width = t.media.style.width;
				} else if (t.media.getAttribute('width') !== null) {
					t.width = t.$media.attr('width');
				} else {
					t.width = t.options['default' + capsTagName + 'Width'];
				}

				if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
					t.height = t.options[tagType + 'Height'];
				} else if (t.media.style.height !== '' && t.media.style.height !== null) {
					t.height = t.media.style.height;
				} else if (t.$media[0].getAttribute('height') !== null) {
					t.height = t.$media.attr('height');
				} else {
					t.height = t.options['default' + capsTagName + 'Height'];
				}

				// set the size, while we wait for the plugins to load below
				t.setPlayerSize(t.width, t.height);

				// create MediaElementShim
				meOptions.pluginWidth = t.width;
				meOptions.pluginHeight = t.height;
			}
			// Hide media completely for audio that doesn't have any features
			else if (!t.isVideo && !t.options.features.length) {
				t.$media.hide();
			}

			// create MediaElement shim
			mejs.MediaElement(t.$media[0], meOptions);

			if (typeof(t.container) !== 'undefined' && t.options.features.length && t.controlsAreVisible) {
				// controls are shown when loaded
				t.container.trigger('controlsshown');
			}
		},

		showControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (t.controlsAreVisible)
				return;

			if (doAnimation) {
				t.controls
					.removeClass('mejs-offscreen')
					.stop(true, true).fadeIn(200, function() {
						t.controlsAreVisible = true;
						t.container.trigger('controlsshown');
					});

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.removeClass('mejs-offscreen')
					.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});

			} else {
				t.controls
					.removeClass('mejs-offscreen')
					.css('display','block');

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.removeClass('mejs-offscreen')
					.css('display','block');

				t.controlsAreVisible = true;
				t.container.trigger('controlsshown');
			}

			t.setControlsSize();

		},

		hideControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (!t.controlsAreVisible || t.options.alwaysShowControls || t.keyboardAction || t.media.paused || t.media.ended)
				return;

			if (doAnimation) {
				// fade out main controls
				t.controls.stop(true, true).fadeOut(200, function() {
					$(this)
						.addClass('mejs-offscreen')
						.css('display','block');

					t.controlsAreVisible = false;
					t.container.trigger('controlshidden');
				});

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
					$(this)
						.addClass('mejs-offscreen')
						.css('display','block');
				});
			} else {

				// hide main controls
				t.controls
					.addClass('mejs-offscreen')
					.css('display','block');

				// hide others
				t.container.find('.mejs-control')
					.addClass('mejs-offscreen')
					.css('display','block');

				t.controlsAreVisible = false;
				t.container.trigger('controlshidden');
			}
		},

		controlsTimer: null,

		startControlsTimer: function(timeout) {

			var t = this;

			timeout = typeof timeout != 'undefined' ? timeout : t.options.controlsTimeoutDefault;

			t.killControlsTimer('start');

			t.controlsTimer = setTimeout(function() {
				//
				t.hideControls();
				t.killControlsTimer('hide');
			}, timeout);
		},

		killControlsTimer: function(src) {

			var t = this;

			if (t.controlsTimer !== null) {
				clearTimeout(t.controlsTimer);
				delete t.controlsTimer;
				t.controlsTimer = null;
			}
		},

		controlsEnabled: true,

		disableControls: function() {
			var t= this;

			t.killControlsTimer();
			t.hideControls(false);
			this.controlsEnabled = false;
		},

		enableControls: function() {
			var t= this;

			t.showControls(false);

			t.controlsEnabled = true;
		},

		// Sets up all controls and events
		meReady: function(media, domNode) {
			
			var
				t = this,
				mf = mejs.MediaFeatures,
				autoplayAttr = domNode.getAttribute('autoplay'),
				autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
				featureIndex,
				feature;

			// make sure it can't create itself again if a plugin reloads
			if (t.created) {
				return;
			} else {
				t.created = true;
			}

			t.media = media;
			t.domNode = domNode;

			if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {

				// In the event that no features are specified for audio,
				// create only MediaElement instance rather than
				// doing all the work to create a full player
				if (!t.isVideo && !t.options.features.length) {

					// force autoplay for HTML5
					if (autoplay && media.pluginType == 'native') {
						t.play();
					}


					if (t.options.success) {

						if (typeof t.options.success == 'string') {
							window[t.options.success](t.media, t.domNode, t);
						} else {
							t.options.success(t.media, t.domNode, t);
						}
					}

					return;
				}

				// two built in features
				t.buildposter(t, t.controls, t.layers, t.media);
				t.buildkeyboard(t, t.controls, t.layers, t.media);
				t.buildoverlays(t, t.controls, t.layers, t.media);

				// grab for use by features
				t.findTracks();

				// add user-defined features/controls
				for (featureIndex in t.options.features) {
					feature = t.options.features[featureIndex];
					if (t['build' + feature]) {
						try {
							t['build' + feature](t, t.controls, t.layers, t.media);
						} catch (e) {
							// TODO: report control error
							//throw e;
							
							
						}
					}
				}

				t.container.trigger('controlsready');

				// reset all layers and controls
				t.setPlayerSize(t.width, t.height);
				t.setControlsSize();


				// controls fade
				if (t.isVideo) {

					if (mejs.MediaFeatures.hasTouch && !t.options.alwaysShowControls) {

						// for touch devices (iOS, Android)
						// show/hide without animation on touch

						t.$media.bind('touchstart', function() {

							// toggle controls
							if (t.controlsAreVisible) {
								t.hideControls(false);
							} else {
								if (t.controlsEnabled) {
									t.showControls(false);
								}
							}
						});

					} else {

						// create callback here since it needs access to current
						// MediaElement object
						t.clickToPlayPauseCallback = function() {
							//

							if (t.options.clickToPlayPause) {
								if (t.media.paused) {
									t.play();
								} else {
									t.pause();
								}

								var button = t.$media.closest('.mejs-container').find('.mejs-overlay-button'),
									pressed = button.attr('aria-pressed');
								button.attr('aria-pressed', !pressed);
							}
						};

						// click to play/pause
						t.media.addEventListener('click', t.clickToPlayPauseCallback, false);

						// show/hide controls
						t.container
							.bind('mouseenter', function () {
								if (t.controlsEnabled) {
									if (!t.options.alwaysShowControls ) {
										t.killControlsTimer('enter');
										t.showControls();
										t.startControlsTimer(t.options.controlsTimeoutMouseEnter);
									}
								}
							})
							.bind('mousemove', function() {
								if (t.controlsEnabled) {
									if (!t.controlsAreVisible) {
										t.showControls();
									}
									if (!t.options.alwaysShowControls) {
										t.startControlsTimer(t.options.controlsTimeoutMouseEnter);
									}
								}
							})
							.bind('mouseleave', function () {
								if (t.controlsEnabled) {
									if (!t.media.paused && !t.options.alwaysShowControls) {
										t.startControlsTimer(t.options.controlsTimeoutMouseLeave);
									}
								}
							});
					}

					if(t.options.hideVideoControlsOnLoad) {
						t.hideControls(false);
					}

					// check for autoplay
					if (autoplay && !t.options.alwaysShowControls) {
						t.hideControls();
					}

					// resizer
					if (t.options.enableAutosize) {
						t.media.addEventListener('loadedmetadata', function(e) {
							// if the <video height> was not set and the options.videoHeight was not set
							// then resize to the real dimensions
							if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
								t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
								t.setControlsSize();
								t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
							}
						}, false);
					}
				}

				// EVENTS

				// FOCUS: when a video starts playing, it takes focus from other players (possibly pausing them)
				t.media.addEventListener('play', function() {
					var playerIndex;

					// go through all other players
					for (playerIndex in mejs.players) {
						var p = mejs.players[playerIndex];
						if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
							p.pause();
						}
						p.hasFocus = false;
					}

					t.hasFocus = true;
				},false);


				// ended for all
				t.media.addEventListener('ended', function (e) {
					if(t.options.autoRewind) {
						try{
							t.media.setCurrentTime(0);
							// Fixing an Android stock browser bug, where "seeked" isn't fired correctly after ending the video and jumping to the beginning
							window.setTimeout(function(){
								$(t.container).find('.mejs-overlay-loading').parent().hide();
							}, 20);
						} catch (exp) {

						}
					}
					if (t.media.pluginType === 'youtube') {
						t.media.stop();
					} else {
						t.media.pause();
					}

					if (t.setProgressRail) {
						t.setProgressRail();
					}
					if (t.setCurrentRail) {
						t.setCurrentRail();
					}

					if (t.options.loop) {
						t.play();
					} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
						t.showControls();
					}
				}, false);

				// resize on the first play
				t.media.addEventListener('loadedmetadata', function() {

					mejs.Utility.calculateTimeFormat(t.duration, t.options, t.options.framesPerSecond || 25);

					if (t.updateDuration) {
						t.updateDuration();
					}
					if (t.updateCurrent) {
						t.updateCurrent();
					}

					if (!t.isFullScreen) {
						t.setPlayerSize(t.width, t.height);
						t.setControlsSize();
					}
				}, false);

				// Only change the time format when necessary
				var duration = null;
				t.media.addEventListener('timeupdate',function() {
					if (duration !== this.duration) {
						duration = this.duration;
						mejs.Utility.calculateTimeFormat(duration, t.options, t.options.framesPerSecond || 25);
						
						// make sure to fill in and resize the controls (e.g., 00:00 => 01:13:15
						if (t.updateDuration) {
							t.updateDuration();
						}
						if (t.updateCurrent) {
							t.updateCurrent();
						}
						t.setControlsSize();
						
					}
				}, false);

				t.container.focusout(function (e) {
					if( e.relatedTarget ) { //FF is working on supporting focusout https://bugzilla.mozilla.org/show_bug.cgi?id=687787
						var $target = $(e.relatedTarget);
						if (t.keyboardAction && $target.parents('.mejs-container').length === 0) {
							t.keyboardAction = false;
							if (t.isVideo && !t.options.alwaysShowControls) {
								t.hideControls(true);
							}

						}
					}
				});

				// webkit has trouble doing this without a delay
				setTimeout(function () {
					t.setPlayerSize(t.width, t.height);
					t.setControlsSize();
				}, 50);

				// adjust controls whenever window sizes (used to be in fullscreen only)
				t.globalBind('resize', function() {

					// don't resize for fullscreen mode
					if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
						t.setPlayerSize(t.width, t.height);
					}

					// always adjust controls
					t.setControlsSize();
				});

				// This is a work-around for a bug in the YouTube iFrame player, which means
				//	we can't use the play() API for the initial playback on iOS or Android;
				//	user has to start playback directly by tapping on the iFrame.
				if (t.media.pluginType == 'youtube' && ( mf.isiOS || mf.isAndroid ) ) {
					t.container.find('.mejs-overlay-play').hide();
					t.container.find('.mejs-poster').hide();
				}
			}

			// force autoplay for HTML5
			if (autoplay && media.pluginType == 'native') {
				t.play();
			}


			if (t.options.success) {

				if (typeof t.options.success == 'string') {
					window[t.options.success](t.media, t.domNode, t);
				} else {
					t.options.success(t.media, t.domNode, t);
				}
			}
		},

		handleError: function(e) {
			var t = this;

			if (t.controls) {
				t.controls.hide();
			}

			// Tell user that the file cannot be played
			if (t.options.error) {
				t.options.error(e);
			}
		},

		setPlayerSize: function(width,height) {
			var t = this;

			if( !t.options.setDimensions ) {
				return false;
			}

			if (typeof width != 'undefined') {
				t.width = width;
			}

			if (typeof height != 'undefined') {
				t.height = height;
			}
 
			// check stretching modes
			switch (t.options.stretching) {
				case 'fill':
					// The 'fill' effect only makes sense on video; for audio we will set the dimensions
					if (t.isVideo) {
						this.setFillMode();
					} else {
						this.setDimensions(t.width, t.height);
					}
					break;
				case 'responsive':
					this.setResponsiveMode();
					break;
				case 'none':
					this.setDimensions(t.width, t.height);
					break;
				// This is the 'auto' mode
				default:
					if (this.hasFluidMode() === true) {
						this.setResponsiveMode();
					} else {
						this.setDimensions(t.width, t.height);
					}
					break;
			}
		},
 
		hasFluidMode: function() {
			var t = this;
	 
			// detect 100% mode - use currentStyle for IE since css() doesn't return percentages
			return (t.height.toString().indexOf('%') > 0 || (t.$node.css('max-width') !== 'none' && t.$node.css('max-width') !== 't.width') || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%'));
		},
 
		setResponsiveMode: function() {
			var t = this;
		
			// do we have the native dimensions yet?
			var nativeWidth = (function() {
				if (t.isVideo) {
					if (t.media.videoWidth && t.media.videoWidth > 0) {
						return t.media.videoWidth;
					} else if (t.media.getAttribute('width') !== null) {
						return t.media.getAttribute('width');
					} else {
						return t.options.defaultVideoWidth;
					}
				} else {
					return t.options.defaultAudioWidth;
				}
			})();
		
			var nativeHeight = (function() {
				if (t.isVideo) {
					if (t.media.videoHeight && t.media.videoHeight > 0) {
						return t.media.videoHeight;
					} else if (t.media.getAttribute('height') !== null) {
						return t.media.getAttribute('height');
					} else {
						return t.options.defaultVideoHeight;
					}
				} else {
					return t.options.defaultAudioHeight;
				}
			})();
		
			var parentWidth = t.container.parent().closest(':visible').width(),
			parentHeight = t.container.parent().closest(':visible').height(),
			newHeight = t.isVideo || !t.options.autosizeProgress ? parseInt(parentWidth * nativeHeight/nativeWidth, 10) : nativeHeight;
			
			// When we use percent, the newHeight can't be calculated so we get the container height
			if (isNaN(newHeight) || ( parentHeight !== 0 && newHeight > parentHeight && parentHeight > nativeHeight)) {
				newHeight = parentHeight;
			}
		
			if (t.container.parent().length > 0 && t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
				parentWidth = $(window).width();
				newHeight = $(window).height();
			}
		
			if ( newHeight && parentWidth ) {
			
				// set outer container size
				t.container
					.width(parentWidth)
					.height(newHeight);
				
				// set native <video> or <audio> and shims
				t.$media.add(t.container.find('.mejs-shim'))
					.width('100%')
					.height('100%');
				
				// if shim is ready, send the size to the embeded plugin
				if (t.isVideo) {
					if (t.media.setVideoSize) {
						t.media.setVideoSize(parentWidth, newHeight);
					}
				}
		
				// set the layers
				t.layers.children('.mejs-layer')
					.width('100%')
					.height('100%');
			}
		},
 
		setFillMode: function() {
			var t = this,
				parent = t.outerContainer;
 
			if (!parent.width()) {
				parent.height(t.$media.width());
			}
 
			if (!parent.height()) {
				parent.height(t.$media.height());
			}
 
			var parentWidth = parent.width(),
				parentHeight = parent.height();
			
			t.setDimensions('100%', '100%');
			
			// This prevents an issue when displaying poster
			t.container.find('.mejs-poster img').css('display', 'block');
			
			targetElement = t.container.find('object, embed, iframe, video');
			
			// calculate new width and height
			var initHeight = t.height,
				initWidth = t.width,
				// scale to the target width
				scaleX1 = parentWidth,
				scaleY1 = (initHeight * parentWidth) / initWidth,
				// scale to the target height
				scaleX2 = (initWidth * parentHeight) / initHeight,
				scaleY2 = parentHeight,
				// now figure out which one we should use
				bScaleOnWidth = !(scaleX2 > parentWidth),
				finalWidth = bScaleOnWidth ? Math.floor(scaleX1) : Math.floor(scaleX2),
				finalHeight = bScaleOnWidth ? Math.floor(scaleY1) : Math.floor(scaleY2);
			
			if (bScaleOnWidth) {
				targetElement.height(finalHeight).width(parentWidth);
				if (t.media.setVideoSize) {
					t.media.setVideoSize(parentWidth, finalHeight);
				}
			} else {
				targetElement.height(parentHeight).width(finalWidth);
				if (t.media.setVideoSize) {
					t.media.setVideoSize(finalWidth, parentHeight);
				}
			}
			
			targetElement.css({
				'margin-left': Math.floor((parentWidth - finalWidth) / 2),
				'margin-top': 0
			});
		},
	 
		setDimensions: function(width, height) {
			var t = this;
			
			t.container
				.width(width)
				.height(height);
			
			t.layers.children('.mejs-layer')
				.width(width)
				.height(height);
		},

		setControlsSize: function() {
			var t = this,
				usedWidth = 0,
				railWidth = 0,
				rail = t.controls.find('.mejs-time-rail'),
				total = t.controls.find('.mejs-time-total'),
				others = rail.siblings(),
				lastControl = others.last(),
				lastControlPosition = null,
				avoidAutosizeProgress = t.options && !t.options.autosizeProgress;

			// skip calculation if hidden
			if (!t.container.is(':visible') || !rail.length || !rail.is(':visible')) {
				return;
			}

			// allow the size to come from custom CSS
			if (avoidAutosizeProgress) {
				// Also, frontends devs can be more flexible
				// due the opportunity of absolute positioning.
				railWidth = parseInt(rail.css('width'), 10);
			}

			// attempt to autosize
			if (railWidth === 0 || !railWidth) {

				// find the size of all the other controls besides the rail
				others.each(function() {
					var $this = $(this);
					if ($this.css('position') != 'absolute' && $this.is(':visible')) {
						usedWidth += $(this).outerWidth(true);
					}
				});

				// fit the rail into the remaining space
				railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
			}

			// resize the rail,
			// but then check if the last control (say, the fullscreen button) got pushed down
			// this often happens when zoomed
			do {
				// outer area
				// we only want to set an inline style with the width of the rail
				// if we're trying to autosize.
				if (!avoidAutosizeProgress) {
					rail.width(railWidth);
				}

				// dark space
				total.width(railWidth - (total.outerWidth(true) - total.width()));

				if (lastControl.css('position') != 'absolute') {
					lastControlPosition = lastControl.length ? lastControl.position() : null;
					railWidth--;
				}
			} while (lastControlPosition !== null && lastControlPosition.top.toFixed(2) > 0 && railWidth > 0);

			t.container.trigger('controlsresize');
		},


		buildposter: function(player, controls, layers, media) {
			var t = this,
				poster =
				$('<div class="mejs-poster mejs-layer">' +
				'</div>')
					.appendTo(layers),
				posterUrl = player.$media.attr('poster');

			// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
			if (player.options.poster !== '') {
				posterUrl = player.options.poster;
			}

			// second, try the real poster
			if ( posterUrl ) {
				t.setPoster(posterUrl);
			} else {
				poster.hide();
			}

			media.addEventListener('play',function() {
				poster.hide();
			}, false);

			if(player.options.showPosterWhenEnded && player.options.autoRewind){
				media.addEventListener('ended',function() {
					poster.show();
				}, false);
			}
		},

		setPoster: function(url) {
			var t = this,
				posterDiv = t.container.find('.mejs-poster'),
				posterImg = posterDiv.find('img');

			if (posterImg.length === 0) {
				posterImg = $('<img width="100%" height="100%" alt="" />').appendTo(posterDiv);
			}

			posterImg.attr('src', url);
			posterDiv.css({'background-image' : 'url(' + url + ')'});
		},

		buildoverlays: function(player, controls, layers, media) {
			var t = this;
			if (!player.isVideo)
				return;

			var
			loading =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-loading"><span></span></div>'+
				'</div>')
				.hide() // start out hidden
				.appendTo(layers),
			error =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-error"></div>'+
				'</div>')
				.hide() // start out hidden
				.appendTo(layers),
			// this needs to come last so it's on top
			bigPlay =
				$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
					'<div class="mejs-overlay-button" role="button" aria-label="' + mejs.i18n.t('mejs.play') + '" aria-pressed="false"></div>'+
				'</div>')
				.appendTo(layers)
				.bind('click', function() {	 // Removed 'touchstart' due issues on Samsung Android devices where a tap on bigPlay started and immediately stopped the video
					if (t.options.clickToPlayPause) {
						if (media.paused) {
							media.play();
						}

						var button = $(this).find('.mejs-overlay-button'),
							pressed = button.attr('aria-pressed');
						button.attr('aria-pressed', !!pressed);
					}
				});

			/*
			if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
				bigPlay.remove();
				loading.remove();
			}
			*/


			// show/hide big play button
			media.addEventListener('play',function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('playing', function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('seeking', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);

			media.addEventListener('seeked', function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
			}, false);

			media.addEventListener('pause',function() {
				if (!mejs.MediaFeatures.isiPhone) {
					bigPlay.show();
				}
			}, false);

			media.addEventListener('waiting', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);


			// show/hide loading
			media.addEventListener('loadeddata',function() {
				// for some reason Chrome is firing this event
				//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
				//	return;

				loading.show();
				controls.find('.mejs-time-buffering').show();
				// Firing the 'canplay' event after a timeout which isn't getting fired on some Android 4.1 devices (https://github.com/johndyer/mediaelement/issues/1305)
				if (mejs.MediaFeatures.isAndroid) {
					media.canplayTimeout = window.setTimeout(
						function() {
							if (document.createEvent) {
								var evt = document.createEvent('HTMLEvents');
								evt.initEvent('canplay', true, true);
								return media.dispatchEvent(evt);
							}
						}, 300
					);
				}
			}, false);
			media.addEventListener('canplay',function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				clearTimeout(media.canplayTimeout); // Clear timeout inside 'loadeddata' to prevent 'canplay' to fire twice
			}, false);

			// error handling
			media.addEventListener('error',function(e) {
				t.handleError(e);
				loading.hide();
				bigPlay.hide();
				error.show();
				error.find('.mejs-overlay-error').html("Error loading this resource");
			}, false);

			media.addEventListener('keydown', function(e) {
				t.onkeydown(player, media, e);
			}, false);
		},

		buildkeyboard: function(player, controls, layers, media) {

				var t = this;

				t.container.keydown(function () {
					t.keyboardAction = true;
				});

				// listen for key presses
				t.globalBind('keydown', function(event) {
					player.hasFocus = $(event.target).closest('.mejs-container').length !== 0
						&& $(event.target).closest('.mejs-container').attr('id') === player.$media.closest('.mejs-container').attr('id');
					return t.onkeydown(player, media, event);
				});


				// check if someone clicked outside a player region, then kill its focus
				t.globalBind('click', function(event) {
					player.hasFocus = $(event.target).closest('.mejs-container').length !== 0;
				});

		},
		onkeydown: function(player, media, e) {
			if (player.hasFocus && player.options.enableKeyboard) {
				// find a matching key
				for (var i = 0, il = player.options.keyActions.length; i < il; i++) {
					var keyAction = player.options.keyActions[i];

					for (var j = 0, jl = keyAction.keys.length; j < jl; j++) {
						if (e.keyCode == keyAction.keys[j]) {
							if (typeof(e.preventDefault) == "function") e.preventDefault();
							keyAction.action(player, media, e.keyCode, e);
							return false;
						}
					}
				}
			}

			return true;
		},

		findTracks: function() {
			var t = this,
				tracktags = t.$media.find('track');

			// store for use by plugins
			t.tracks = [];
			tracktags.each(function(index, track) {

				track = $(track);

				t.tracks.push({
					srclang: (track.attr('srclang')) ? track.attr('srclang').toLowerCase() : '',
					src: track.attr('src'),
					kind: track.attr('kind'),
					label: track.attr('label') || '',
					entries: [],
					isLoaded: false
				});
			});
		},
		changeSkin: function(className) {
			this.container[0].className = 'mejs-container ' + className;
			this.setPlayerSize(this.width, this.height);
			this.setControlsSize();
		},
		play: function() {
			this.load();
			this.media.play();
		},
		pause: function() {
			try {
				this.media.pause();
			} catch (e) {}
		},
		load: function() {
			if (!this.isLoaded) {
				this.media.load();
			}

			this.isLoaded = true;
		},
		setMuted: function(muted) {
			this.media.setMuted(muted);
		},
		setCurrentTime: function(time) {
			this.media.setCurrentTime(time);
		},
		getCurrentTime: function() {
			return this.media.currentTime;
		},
		setVolume: function(volume) {
			this.media.setVolume(volume);
		},
		getVolume: function() {
			return this.media.volume;
		},
		setSrc: function(src) {
			var
				t = this;

			// If using YouTube, its API is different to load a specific source
			if (t.media.pluginType === 'youtube') {
				var videoId;

				if (typeof src !== 'string') {
					var i, media;

					for (i=0; i<src.length; i++) {
						media = src[i];
						if (this.canPlayType(media.type)) {
							src = media.src;
							break;
						}
					}
				}

				// youtu.be url from share button
				if (src.lastIndexOf('youtu.be') !== -1) {
					videoId = src.substr(src.lastIndexOf('/') + 1);

					if (videoId.indexOf('?') !== -1) {
						videoId = videoId.substr(0, videoId.indexOf('?'));
					}

				} else {
					// https://www.youtube.com/watch?v=
					var videoIdMatch = src.match(/[?&]v=([^&#]+)|&|#|$/);

					if (videoIdMatch) {
						videoId = videoIdMatch[1];
					}
				}

				if (t.media.getAttribute('autoplay') !== null) {
					t.media.pluginApi.loadVideoById(videoId);
				} else {
					t.media.pluginApi.cueVideoById(videoId);
				}

			}
			else {
				t.media.setSrc(src);
			}
		},
		remove: function() {
			var t = this, featureIndex, feature;

			t.container.prev('.mejs-offscreen').remove();

			// invoke features cleanup
			for (featureIndex in t.options.features) {
				feature = t.options.features[featureIndex];
				if (t['clean' + feature]) {
					try {
						t['clean' + feature](t);
					} catch (e) {
						// TODO: report control error
						//throw e;
						//
						//
					}
				}
			}

			// grab video and put it back in place
			if (!t.isDynamic) {
				t.$media.prop('controls', true);
				// detach events from the video
				// TODO: detach event listeners better than this;
				//		 also detach ONLY the events attached by this plugin!
				t.$node.clone().insertBefore(t.container).show();
				t.$node.remove();
			} else {
				t.$node.insertBefore(t.container);
			}

			if (t.media.pluginType !== 'native') {
				t.media.remove();
			}

			// Remove the player from the mejs.players object so that pauseOtherPlayers doesn't blow up when trying to pause a non existance flash api.
			delete mejs.players[t.id];

			if (typeof t.container == 'object') {
				t.container.remove();
			}
			t.globalUnbind();
			delete t.node.player;
		},
		rebuildtracks: function(){
			var t = this;
			t.findTracks();
			t.buildtracks(t, t.controls, t.layers, t.media);
		},
		resetSize: function(){
			var t = this;
			// webkit has trouble doing this without a delay
			setTimeout(function () {
				//
				t.setPlayerSize(t.width, t.height);
				t.setControlsSize();
			}, 50);
		}
	};

	(function(){
		var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;

		function splitEvents(events, id) {
			// add player ID as an event namespace so it's easier to unbind them all later
			var ret = {d: [], w: []};
			$.each((events || '').split(' '), function(k, v){
				var eventname = v + '.' + id;
				if (eventname.indexOf('.') === 0) {
					ret.d.push(eventname);
					ret.w.push(eventname);
				}
				else {
					ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
				}
			});
			ret.d = ret.d.join(' ');
			ret.w = ret.w.join(' ');
			return ret;
		}

		mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
			var t = this;
			var doc = t.node ? t.node.ownerDocument : document;

			events = splitEvents(events, t.id);
			if (events.d) $(doc).bind(events.d, data, callback);
			if (events.w) $(window).bind(events.w, data, callback);
		};

		mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
			var t = this;
			var doc = t.node ? t.node.ownerDocument : document;

			events = splitEvents(events, t.id);
			if (events.d) $(doc).unbind(events.d, callback);
			if (events.w) $(window).unbind(events.w, callback);
		};
	})();

	// turn into jQuery plugin
	if (typeof $ != 'undefined') {
		$.fn.mediaelementplayer = function (options) {
			if (options === false) {
				this.each(function () {
					var player = $(this).data('mediaelementplayer');
					if (player) {
						player.remove();
					}
					$(this).removeData('mediaelementplayer');
				});
			}
			else {
				this.each(function () {
					$(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
				});
			}
			return this;
		};


		$(document).ready(function() {
			// auto enable using JSON attribute
			$('.mejs-player').mediaelementplayer();
		});
	}

	// push out to window
	window.MediaElementPlayer = mejs.MediaElementPlayer;

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		playText: '',
		pauseText: ''
	});


	// PLAY/pause BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildplaypause: function(player, controls, layers, media) {
			var 
				t = this,
				op = t.options,
				playTitle = op.playText ? op.playText : mejs.i18n.t('mejs.play'),
				pauseTitle = op.pauseText ? op.pauseText : mejs.i18n.t('mejs.pause'),
				play =
				$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
					'<button type="button" aria-controls="' + t.id + '" title="' + playTitle + '" aria-label="' + pauseTitle + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function(e) {
					e.preventDefault();
				
					if (media.paused) {
						media.play();
					} else {
						media.pause();
					}
					
					return false;
				}),
				play_btn = play.find('button');


			function togglePlayPause(which) {
				if ('play' === which) {
					play.removeClass('mejs-play').addClass('mejs-pause');
					play_btn.attr({
						'title': pauseTitle,
						'aria-label': pauseTitle
					});
				} else {
					play.removeClass('mejs-pause').addClass('mejs-play');
					play_btn.attr({
						'title': playTitle,
						'aria-label': playTitle
					});
				}
			};
			togglePlayPause('pse');


			media.addEventListener('play',function() {
				togglePlayPause('play');
			}, false);
			media.addEventListener('playing',function() {
				togglePlayPause('play');
			}, false);


			media.addEventListener('pause',function() {
				togglePlayPause('pse');
			}, false);
			media.addEventListener('paused',function() {
				togglePlayPause('pse');
			}, false);
		}
	});
	
})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		stopText: 'Stop'
	});

	// STOP BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildstop: function(player, controls, layers, media) {
			var t = this;

			$('<div class="mejs-button mejs-stop-button mejs-stop">' +
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '" aria-label="' + t.options.stopText + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function() {
					if (!media.paused) {
						media.pause();
					}
					if (media.currentTime > 0) {
						media.setCurrentTime(0);
                        media.pause();
						controls.find('.mejs-time-current').width('0px');
						controls.find('.mejs-time-handle').css('left', '0px');
						controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0, player.options));
						controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0, player.options));
						layers.find('.mejs-poster').show();
					}
				});
		}
	});
	
})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		// Enable tooltip that shows time in progress bar
		enableProgressTooltip: true,
		progressHelpText: ''
	});

	// progress/loaded bar
	$.extend(MediaElementPlayer.prototype, {
		buildprogress: function(player, controls, layers, media) {

			var
				t = this,
				mouseIsDown = false,
				mouseIsOver = false,
				lastKeyPressTime = 0,
				startedPaused = false,
				autoRewindInitial = player.options.autoRewind,
				progressTitle = t.options.progressHelpText ? t.options.progressHelpText : mejs.i18n.t('mejs.time-help-text'),
				tooltip = player.options.enableProgressTooltip ? '<span class="mejs-time-float">' +
					'<span class="mejs-time-float-current">00:00</span>' +
					'<span class="mejs-time-float-corner"></span>' +
				'</span>' : "";

			$('<div class="mejs-time-rail">' +
				'<span  class="mejs-time-total mejs-time-slider">' +
				//'<span class="mejs-offscreen">' + progressTitle + '</span>' +
					'<span class="mejs-time-buffering"></span>' +
					'<span class="mejs-time-loaded"></span>' +
					'<span class="mejs-time-current"></span>' +
					'<span class="mejs-time-handle"></span>' +
					 tooltip +
				'</span>' +
			'</div>')
				.appendTo(controls);
			controls.find('.mejs-time-buffering').hide();

			t.total = controls.find('.mejs-time-total');
			t.loaded  = controls.find('.mejs-time-loaded');
			t.current  = controls.find('.mejs-time-current');
			t.handle  = controls.find('.mejs-time-handle');
			t.timefloat  = controls.find('.mejs-time-float');
			t.timefloatcurrent  = controls.find('.mejs-time-float-current');
			t.slider = controls.find('.mejs-time-slider');

			var handleMouseMove = function (e) {

					var offset = t.total.offset(),
						width = t.total.width(),
						percentage = 0,
						newTime = 0,
						pos = 0,
						x;

					// mouse or touch position relative to the object
					if (e.originalEvent && e.originalEvent.changedTouches) {
						x = e.originalEvent.changedTouches[0].pageX;
					} else if (e.changedTouches) { // for Zepto
						x = e.changedTouches[0].pageX;
					} else {
						x = e.pageX;
					}

					if (media.duration) {
						if (x < offset.left) {
							x = offset.left;
						} else if (x > width + offset.left) {
							x = width + offset.left;
						}

						pos = x - offset.left;
						percentage = (pos / width);
						newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;

						// seek to where the mouse is
						if (mouseIsDown && newTime !== media.currentTime) {
							media.setCurrentTime(newTime);
						}

						// position floating time box
						if (!mejs.MediaFeatures.hasTouch) {
							t.timefloat.css('left', pos);
							t.timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime, player.options) );
							t.timefloat.show();
						}
					}
				},
				// Accessibility for slider
				updateSlider = function (e) {

					var seconds = media.currentTime,
						timeSliderText = mejs.i18n.t('mejs.time-slider'),
						time = mejs.Utility.secondsToTimeCode(seconds, player.options),
						duration = media.duration;

					t.slider.attr({
						'aria-label': timeSliderText,
						'aria-valuemin': 0,
						'aria-valuemax': duration,
						'aria-valuenow': seconds,
						'aria-valuetext': time,
						'role': 'slider',
						'tabindex': 0
					});

				},
				restartPlayer = function () {
					var now = new Date();
					if (now - lastKeyPressTime >= 1000) {
						media.play();
					}
				};

			t.slider.bind('focus', function (e) {
				player.options.autoRewind = false;
			});

			t.slider.bind('blur', function (e) {
				player.options.autoRewind = autoRewindInitial;
			});

			t.slider.bind('keydown', function (e) {

				if ((new Date() - lastKeyPressTime) >= 1000) {
					startedPaused = media.paused;
				}

				var keyCode = e.keyCode,
					duration = media.duration,
					seekTime = media.currentTime,
					seekForward  = player.options.defaultSeekForwardInterval(media),
					seekBackward = player.options.defaultSeekBackwardInterval(media);

				switch (keyCode) {
					case 37: // left
					case 40: // Down
						seekTime -= seekBackward;
						break;
					case 39: // Right
					case 38: // Up
						seekTime += seekForward;
						break;
					case 36: // Home
						seekTime = 0;
						break;
					case 35: // end
						seekTime = duration;
						break;
					case 32: // space
					case 13: // enter
						media.paused ? media.play() : media.pause();
						return;
					default:
						return;
				}

				seekTime = seekTime < 0 ? 0 : (seekTime >= duration ? duration : Math.floor(seekTime));
				lastKeyPressTime = new Date();
				if (!startedPaused) {
					media.pause();
				}

				if (seekTime < media.duration && !startedPaused) {
					setTimeout(restartPlayer, 1100);
				}

				media.setCurrentTime(seekTime);

				e.preventDefault();
				e.stopPropagation();
				return false;
			});


			// handle clicks
			//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
			t.total
				.bind('mousedown touchstart', function (e) {
					// only handle left clicks or touch
					if (e.which === 1 || e.which === 0) {
						mouseIsDown = true;
						handleMouseMove(e);
						t.globalBind('mousemove.dur touchmove.dur', function(e) {
							handleMouseMove(e);
						});
						t.globalBind('mouseup.dur touchend.dur', function (e) {
							mouseIsDown = false;
							if (typeof t.timefloat !== 'undefined') {
								t.timefloat.hide();
							}
							t.globalUnbind('.dur');
						});
					}
				})
				.bind('mouseenter', function(e) {
					mouseIsOver = true;
					t.globalBind('mousemove.dur', function(e) {
						handleMouseMove(e);
					});
					if (typeof t.timefloat !== 'undefined' && !mejs.MediaFeatures.hasTouch) {
						t.timefloat.show();
					}
				})
				.bind('mouseleave',function(e) {
					mouseIsOver = false;
					if (!mouseIsDown) {
						t.globalUnbind('.dur');
						if (typeof t.timefloat !== 'undefined') {
							t.timefloat.hide();
						}
					}
				});

			// loading
			media.addEventListener('progress', function (e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			}, false);

			// current time
			media.addEventListener('timeupdate', function(e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
				updateSlider(e);
			}, false);

			t.container.on('controlsresize', function(e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			});
		},
		setProgressRail: function(e) {

			var
				t = this,
				target = (e !== undefined) ? e.target : t.media,
				percent = null;

			// newest HTML5 spec has buffered array (FF4, Webkit)
			if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
				// account for a real array with multiple values - always read the end of the last buffer
				percent = target.buffered.end(target.buffered.length - 1) / target.duration;
			} 
			// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
			// to be anything other than 0. If the byte count is available we use this instead.
			// Browsers that support the else if do not seem to have the bufferedBytes value and
			// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
			else if (target && target.bytesTotal !== undefined && target.bytesTotal > 0 && target.bufferedBytes !== undefined) {
				percent = target.bufferedBytes / target.bytesTotal;
			}
			// Firefox 3 with an Ogg file seems to go this way
			else if (e && e.lengthComputable && e.total !== 0) {
				percent = e.loaded / e.total;
			}

			// finally update the progress bar
			if (percent !== null) {
				percent = Math.min(1, Math.max(0, percent));
				// update loaded bar
				if (t.loaded && t.total) {
					t.loaded.width(t.total.width() * percent);
				}
			}
		},
		setCurrentRail: function() {

			var t = this;
		
			if (t.media.currentTime !== undefined && t.media.duration) {

				// update bar and handle
				if (t.total && t.handle) {
					var 
						newWidth = Math.round(t.total.width() * t.media.currentTime / t.media.duration),
						handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);

					t.current.width(newWidth);
					t.handle.css('left', handlePos);
				}
			}

		}
	});
})(mejs.$);

(function($) {
	
	// options
	$.extend(mejs.MepDefaults, {
		duration: -1,
		timeAndDurationSeparator: '<span> | </span>'
	});


	// current and duration 00:00 / 00:00
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;
			
			$('<div class="mejs-time" role="timer" aria-live="off">' +
					'<span class="mejs-currenttime">' + 
						mejs.Utility.secondsToTimeCode(0, player.options) +
                    '</span>'+
				'</div>')
			.appendTo(controls);
			
			t.currenttime = t.controls.find('.mejs-currenttime');

			media.addEventListener('timeupdate',function() {
				if (t.controlsAreVisible) {
					player.updateCurrent();
				}

			}, false);
		},


		buildduration: function(player, controls, layers, media) {
			var t = this;
			
			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'<span class="mejs-duration">' + 
						mejs.Utility.secondsToTimeCode(t.options.duration, t.options) +
					'</span>')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
				
				$('<div class="mejs-time mejs-duration-container">'+
					'<span class="mejs-duration">' + 
						mejs.Utility.secondsToTimeCode(t.options.duration, t.options) +
					'</span>' +
				'</div>')
				.appendTo(controls);
			}
			
			t.durationD = t.controls.find('.mejs-duration');

			media.addEventListener('timeupdate',function() {
				if (t.controlsAreVisible) {
					player.updateDuration();
				}
			}, false);
		},
		
		updateCurrent:  function() {
			var t = this;
			
			var currentTime = t.media.currentTime;
			
			if (isNaN(currentTime)) {
				currentTime = 0;
			}

			if (t.currenttime) {
				t.currenttime.html(mejs.Utility.secondsToTimeCode(currentTime, t.options));
			}
		},
		
		updateDuration: function() {
			var t = this;
			
			var duration = t.media.duration;
			if (t.options.duration > 0) {
				duration = t.options.duration;
			}
			
			if (isNaN(duration)) {
				duration = 0;
			}

			//Toggle the long video class if the video is longer than an hour.
			t.container.toggleClass("mejs-long-video", duration > 3600);
			
			if (t.durationD && duration > 0) {
				t.durationD.html(mejs.Utility.secondsToTimeCode(duration, t.options));
			}		
		}
	});

})(mejs.$);

(function ($) {

	$.extend(mejs.MepDefaults, {
		muteText: mejs.i18n.t('mejs.mute-toggle'),
		allyVolumeControlText: mejs.i18n.t('mejs.volume-help-text'),
		hideVolumeOnTouchDevices: true,

		audioVolume: 'horizontal',
		videoVolume: 'vertical'
	});

	$.extend(MediaElementPlayer.prototype, {
		buildvolume: function (player, controls, layers, media) {

			// Android and iOS don't support volume controls
			if ((mejs.MediaFeatures.isAndroid || mejs.MediaFeatures.isiOS) && this.options.hideVolumeOnTouchDevices)
				return;

			var t = this,
				mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
				mute = (mode == 'horizontal') ?

					// horizontal version
					$('<div class="mejs-button mejs-volume-button mejs-mute">' +
						'<button type="button" aria-controls="' + t.id +
						'" title="' + t.options.muteText +
						'" aria-label="' + t.options.muteText +
						'"></button>' +
						'</div>' +
						'<a href="javascript:void(0);" class="mejs-horizontal-volume-slider">' + // outer background
						'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
						'<div class="mejs-horizontal-volume-total"></div>' + // line background
						'<div class="mejs-horizontal-volume-current"></div>' + // current volume
						'<div class="mejs-horizontal-volume-handle"></div>' + // handle
						'</a>'
					)
					.appendTo(controls) :

					// vertical version
					$('<div class="mejs-button mejs-volume-button mejs-mute">' +
						'<button type="button" aria-controls="' + t.id +
						'" title="' + t.options.muteText +
						'" aria-label="' + t.options.muteText +
						'"></button>' +
						'<a href="javascript:void(0);" class="mejs-volume-slider">' + // outer background
						'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
						'<div class="mejs-volume-total"></div>' + // line background
						'<div class="mejs-volume-current"></div>' + // current volume
						'<div class="mejs-volume-handle"></div>' + // handle
						'</a>' +
						'</div>')
					.appendTo(controls),
				volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
				volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
				volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
				volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),

				positionVolumeHandle = function (volume, secondTry) {

					if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
						volumeSlider.show();
						positionVolumeHandle(volume, true);
						volumeSlider.hide();
						return;
					}

					// correct to 0-1
					volume = Math.max(0, volume);
					volume = Math.min(volume, 1);

					// adjust mute button style
					if (volume === 0) {
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
						mute.children('button').attr('title', mejs.i18n.t('mejs.unmute')).attr('aria-label', mejs.i18n.t('mejs.unmute'));
					} else {
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
						mute.children('button').attr('title', mejs.i18n.t('mejs.mute')).attr('aria-label', mejs.i18n.t('mejs.mute'));
					}

					// top/left of full size volume slider background
					var totalPosition = volumeTotal.position();
					// position slider
					if (mode == 'vertical') {
						var
							// height of the full size volume slider background
							totalHeight = volumeTotal.height(),

							// the new top position based on the current volume
							// 70% volume on 100px height == top:30px
							newTop = totalHeight - (totalHeight * volume);

						// handle
						volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));

						// show the current visibility
						volumeCurrent.height(totalHeight - newTop);
						volumeCurrent.css('top', totalPosition.top + newTop);
					} else {
						var
							// height of the full size volume slider background
							totalWidth = volumeTotal.width(),

							// the new left position based on the current volume
							newLeft = totalWidth * volume;

						// handle
						volumeHandle.css('left', Math.round(totalPosition.left + newLeft - (volumeHandle.width() / 2)));

						// rezize the current part of the volume bar
						volumeCurrent.width(Math.round(newLeft));
					}
				},
				handleVolumeMove = function (e) {

					var volume = null,
						totalOffset = volumeTotal.offset();

					// calculate the new volume based on the moust position
					if (mode === 'vertical') {

						var
							railHeight = volumeTotal.height(),
							newY = e.pageY - totalOffset.top;

						volume = (railHeight - newY) / railHeight;

						// the controls just hide themselves (usually when mouse moves too far up)
						if (totalOffset.top === 0 || totalOffset.left === 0) {
							return;
						}

					} else {
						var
							railWidth = volumeTotal.width(),
							newX = e.pageX - totalOffset.left;

						volume = newX / railWidth;
					}

					// ensure the volume isn't outside 0-1
					volume = Math.max(0, volume);
					volume = Math.min(volume, 1);

					// position the slider and handle
					positionVolumeHandle(volume);

					// set the media object (this will trigger the volumechanged event)
					if (volume === 0) {
						media.setMuted(true);
					} else {
						media.setMuted(false);
					}
					media.setVolume(volume);
				},
				mouseIsDown = false,
				mouseIsOver = false;

			// SLIDER

			mute
			.hover(function () {
				volumeSlider.show();
				mouseIsOver = true;
			}, function () {
				mouseIsOver = false;

				if (!mouseIsDown && mode == 'vertical') {
					volumeSlider.hide();
				}
			});

			var updateVolumeSlider = function (e) {

				var volume = Math.floor(media.volume * 100);

				volumeSlider.attr({
					'aria-label': mejs.i18n.t('mejs.volume-slider'),
					'aria-valuemin': 0,
					'aria-valuemax': 100,
					'aria-valuenow': volume,
					'aria-valuetext': volume + '%',
					'role': 'slider',
					'tabindex': 0
				});

			};

			volumeSlider
			.bind('mouseover', function () {
				mouseIsOver = true;
			})
			.bind('mousedown', function (e) {
				handleVolumeMove(e);
				t.globalBind('mousemove.vol', function (e) {
					handleVolumeMove(e);
				});
				t.globalBind('mouseup.vol', function () {
					mouseIsDown = false;
					t.globalUnbind('.vol');

					if (!mouseIsOver && mode == 'vertical') {
						volumeSlider.hide();
					}
				});
				mouseIsDown = true;

				return false;
			})
			.bind('keydown', function (e) {
				var keyCode = e.keyCode;
				var volume = media.volume;
				switch (keyCode) {
					case 38: // Up
						volume = Math.min(volume + 0.1, 1);
						break;
					case 40: // Down
						volume = Math.max(0, volume - 0.1);
						break;
					default:
						return true;
				}

				mouseIsDown = false;
				positionVolumeHandle(volume);
				media.setVolume(volume);
				return false;
			});

			// MUTE button
			mute.find('button').click(function () {
				media.setMuted(!media.muted);
			});

			//Keyboard input
			mute.find('button').bind('focus', function () {
				volumeSlider.show();
			});

			// listen for volume change events from other sources
			media.addEventListener('volumechange', function (e) {
				if (!mouseIsDown) {
					if (media.muted) {
						positionVolumeHandle(0);
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
					} else {
						positionVolumeHandle(media.volume);
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
					}
				}
				updateVolumeSlider(e);
			}, false);

			// mutes the media and sets the volume icon muted if the initial volume is set to 0
			if (player.options.startVolume === 0) {
				media.setMuted(true);
			}

			// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
			if (media.pluginType === 'native') {
				media.setVolume(player.options.startVolume);
			}

			t.container.on('controlsresize', function () {
				if (media.muted) {
					positionVolumeHandle(0);
					mute.removeClass('mejs-mute').addClass('mejs-unmute');
				} else {
					positionVolumeHandle(media.volume);
					mute.removeClass('mejs-unmute').addClass('mejs-mute');
				}
			});
		}
	});

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		usePluginFullScreen: true,
		newWindowCallback: function() { return '';},
		fullscreenText: ''
	});

	$.extend(MediaElementPlayer.prototype, {

		isFullScreen: false,

		isNativeFullScreen: false,

		isInIframe: false,
							
		// Possible modes
		// (1) 'native-native' 	HTML5 video  + browser fullscreen (IE10+, etc.)
		// (2) 'plugin-native' 	plugin video + browser fullscreen (fails in some versions of Firefox)
		// (3) 'fullwindow' 	Full window (retains all UI)
		// usePluginFullScreen = true
		// (4) 'plugin-click' 	Flash 1 - click through with pointer events
		// (5) 'plugin-hover' 	Flash 2 - hover popup in flash (IE6-8)		
		fullscreenMode: '',

		buildfullscreen: function(player, controls, layers, media) {

			if (!player.isVideo)
				return;
				
			player.isInIframe = (window.location != window.parent.location);	
		
			// detect on start
			media.addEventListener('loadstart', function() { player.detectFullscreenMode(); });
				
			// build button
			var t = this,
				hideTimeout = null,
				fullscreenTitle = t.options.fullscreenText ? t.options.fullscreenText : mejs.i18n.t('mejs.fullscreen'),
				fullscreenBtn =
					$('<div class="mejs-button mejs-fullscreen-button">' +
						'<button type="button" aria-controls="' + t.id + '" title="' + fullscreenTitle + '" aria-label="' + fullscreenTitle + '"></button>' +
					'</div>')
					.appendTo(controls)
					.on('click', function() {
						
						// toggle fullscreen
						var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
	
						if (isFullScreen) {
							player.exitFullScreen();
						} else {
							player.enterFullScreen();
						}
					})										
					.on('mouseover', function() {
						
						// very old browsers with a plugin
						if (t.fullscreenMode == 'plugin-hover') {						
							if (hideTimeout !== null) {
								clearTimeout(hideTimeout);
								delete hideTimeout;
							}
	
							var buttonPos = fullscreenBtn.offset(),
								containerPos = player.container.offset();
	
							media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
						}

					})
					.on('mouseout', function() {

						if (t.fullscreenMode == 'plugin-hover') {						
							if (hideTimeout !== null) {
								clearTimeout(hideTimeout);
								delete hideTimeout;
							}
	
							hideTimeout = setTimeout(function() {
								media.hideFullscreenButton();
							}, 1500);
						}

					});

					

			player.fullscreenBtn = fullscreenBtn;

			t.globalBind('keydown',function (e) {
				if (e.keyCode == 27 && ((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen)) {
					player.exitFullScreen();
				}
			});
			
			t.normalHeight = 0;
			t.normalWidth = 0;					
					
			// setup native fullscreen event
			if (mejs.MediaFeatures.hasTrueNativeFullScreen) {

				// chrome doesn't alays fire this in an iframe
				var fullscreenChanged = function(e) {
					if (player.isFullScreen) {
						if (mejs.MediaFeatures.isFullScreen()) {
							player.isNativeFullScreen = true;
							// reset the controls once we are fully in full screen
							player.setControlsSize();
						} else {
							player.isNativeFullScreen = false;
							// when a user presses ESC
							// make sure to put the player back into place
							player.exitFullScreen();
						}
					}
				};

				player.globalBind(mejs.MediaFeatures.fullScreenEventName, fullscreenChanged);
			}

		},
		
		detectFullscreenMode: function() {
			
			var t = this,
				mode = '',
				features = mejs.MediaFeatures;
			
			if (features.hasTrueNativeFullScreen && t.media.pluginType === 'native') {
				mode = 'native-native';
			} else if (features.hasTrueNativeFullScreen && t.media.pluginType !== 'native' && !features.hasFirefoxPluginMovingProblem) {
				mode = 'plugin-native';					
			} else if (t.usePluginFullScreen) { 
				if (mejs.MediaFeatures.supportsPointerEvents) {
					mode = 'plugin-click';
					// this needs some special setup
					t.createPluginClickThrough();				
				} else { 
					mode = 'plugin-hover';
				}
				
			} else {
				mode = 'fullwindow';
			}
			
			
			t.fullscreenMode = mode;		
			return mode;
		},
		
		isPluginClickThroughCreated: false,
		
		createPluginClickThrough: function() {
				
			var t = this;
			
			// don't build twice
			if (t.isPluginClickThroughCreated) {
				return;
			}	

			// allows clicking through the fullscreen button and controls down directly to Flash

			/*
			 When a user puts his mouse over the fullscreen button, we disable the controls so that mouse events can go down to flash (pointer-events)
			 We then put a divs over the video and on either side of the fullscreen button
			 to capture mouse movement and restore the controls once the mouse moves outside of the fullscreen button
			*/

			var fullscreenIsDisabled = false,
				restoreControls = function() {
					if (fullscreenIsDisabled) {
						// hide the hovers
						for (var i in hoverDivs) {
							hoverDivs[i].hide();
						}

						// restore the control bar
						t.fullscreenBtn.css('pointer-events', '');
						t.controls.css('pointer-events', '');

						// prevent clicks from pausing video
						t.media.removeEventListener('click', t.clickToPlayPauseCallback);

						// store for later
						fullscreenIsDisabled = false;
					}
				},
				hoverDivs = {},
				hoverDivNames = ['top', 'left', 'right', 'bottom'],
				i, len,
				positionHoverDivs = function() {
					var fullScreenBtnOffsetLeft = fullscreenBtn.offset().left - t.container.offset().left,
						fullScreenBtnOffsetTop = fullscreenBtn.offset().top - t.container.offset().top,
						fullScreenBtnWidth = fullscreenBtn.outerWidth(true),
						fullScreenBtnHeight = fullscreenBtn.outerHeight(true),
						containerWidth = t.container.width(),
						containerHeight = t.container.height();

					for (i in hoverDivs) {
						hoverDivs[i].css({position: 'absolute', top: 0, left: 0}); //, backgroundColor: '#f00'});
					}

					// over video, but not controls
					hoverDivs['top']
						.width( containerWidth )
						.height( fullScreenBtnOffsetTop );

					// over controls, but not the fullscreen button
					hoverDivs['left']
						.width( fullScreenBtnOffsetLeft )
						.height( fullScreenBtnHeight )
						.css({top: fullScreenBtnOffsetTop});

					// after the fullscreen button
					hoverDivs['right']
						.width( containerWidth - fullScreenBtnOffsetLeft - fullScreenBtnWidth )
						.height( fullScreenBtnHeight )
						.css({top: fullScreenBtnOffsetTop,
							 left: fullScreenBtnOffsetLeft + fullScreenBtnWidth});

					// under the fullscreen button
					hoverDivs['bottom']
						.width( containerWidth )
						.height( containerHeight - fullScreenBtnHeight - fullScreenBtnOffsetTop )
						.css({top: fullScreenBtnOffsetTop + fullScreenBtnHeight});
				};

			t.globalBind('resize', function() {
				positionHoverDivs();
			});

			for (i = 0, len = hoverDivNames.length; i < len; i++) {
				hoverDivs[hoverDivNames[i]] = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls).hide();
			}

			// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
			fullscreenBtn.on('mouseover',function() {

				if (!t.isFullScreen) {

					var buttonPos = fullscreenBtn.offset(),
						containerPos = player.container.offset();

					// move the button in Flash into place
					media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);

					// allows click through
					t.fullscreenBtn.css('pointer-events', 'none');
					t.controls.css('pointer-events', 'none');

					// restore click-to-play
					t.media.addEventListener('click', t.clickToPlayPauseCallback);

					// show the divs that will restore things
					for (i in hoverDivs) {
						hoverDivs[i].show();
					}

					positionHoverDivs();

					fullscreenIsDisabled = true;
				}

			});

			// restore controls anytime the user enters or leaves fullscreen
			media.addEventListener('fullscreenchange', function(e) {
				t.isFullScreen = !t.isFullScreen;
				// don't allow plugin click to pause video - messes with
				// plugin's controls
				if (t.isFullScreen) {
					t.media.removeEventListener('click', t.clickToPlayPauseCallback);
				} else {
					t.media.addEventListener('click', t.clickToPlayPauseCallback);
				}
				restoreControls();
			});


			// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
			// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button

			t.globalBind('mousemove', function(e) {

				// if the mouse is anywhere but the fullsceen button, then restore it all
				if (fullscreenIsDisabled) {

					var fullscreenBtnPos = fullscreenBtn.offset();


					if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
						e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
						) {

						fullscreenBtn.css('pointer-events', '');
						t.controls.css('pointer-events', '');

						fullscreenIsDisabled = false;
					}
				}
			});


			t.isPluginClickThroughCreated = true;
		},		

		cleanfullscreen: function(player) {
			player.exitFullScreen();
		},

        containerSizeTimeout: null,

		enterFullScreen: function() {

			var t = this;

			if (mejs.MediaFeatures.isiOS && mejs.MediaFeatures.hasiOSFullScreen && typeof t.media.webkitEnterFullscreen === 'function') {
			    t.media.webkitEnterFullscreen();
				return;
			}

			// set it to not show scroll bars so 100% will work
            $(document.documentElement).addClass('mejs-fullscreen');

			// store sizing
			t.normalHeight = t.container.height();
			t.normalWidth = t.container.width();



			// attempt to do true fullscreen
			if (t.fullscreenMode === 'native-native' || t.fullscreenMode === 'plugin-native') {

				mejs.MediaFeatures.requestFullScreen(t.container[0]);
				//return;

				if (t.isInIframe) {
					// sometimes exiting from fullscreen doesn't work
					// notably in Chrome <iframe>. Fixed in version 17
					setTimeout(function checkFullscreen() {

						if (t.isNativeFullScreen) {
							var percentErrorMargin = 0.002, // 0.2%
								windowWidth = $(window).width(),
								screenWidth = screen.width,
								absDiff = Math.abs(screenWidth - windowWidth),
								marginError = screenWidth * percentErrorMargin;

							// check if the video is suddenly not really fullscreen
							if (absDiff > marginError) {
								// manually exit
								t.exitFullScreen();
							} else {
								// test again
								setTimeout(checkFullscreen, 500);
							}
						}
						
					}, 1000);
				}
				
			} else if (t.fullscreeMode == 'fullwindow') {				
				// move into position
				
			}			
			
			// make full size
			t.container
				.addClass('mejs-container-fullscreen')
				.width('100%')
				.height('100%');
				//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});

			// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
			// Actually, it seems to be needed for IE8, too
			//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
				t.containerSizeTimeout = setTimeout(function() {
					t.container.css({width: '100%', height: '100%'});
					t.setControlsSize();
				}, 500);
			//}

			if (t.media.pluginType === 'native') {
				t.$media
					.width('100%')
					.height('100%');
			} else {
				t.container.find('.mejs-shim')
					.width('100%')
					.height('100%');	
				
				setTimeout(function() {
					var win = $(window),
						winW = win.width(),
						winH = win.height();
							
					t.media.setVideoSize(winW,winH);			
				}, 500);
			}

			t.layers.children('div')
				.width('100%')
				.height('100%');

			if (t.fullscreenBtn) {
				t.fullscreenBtn
					.removeClass('mejs-fullscreen')
					.addClass('mejs-unfullscreen');
			}

			t.setControlsSize();
			t.isFullScreen = true;

			var zoomFactor = Math.min(screen.width / t.width, screen.height / t.height);
			t.container.find('.mejs-captions-text').css('font-size', zoomFactor * 100 + '%');
			t.container.find('.mejs-captions-text').css('line-height', 'normal');
			t.container.find('.mejs-captions-position').css('bottom', '45px');

			t.container.trigger('enteredfullscreen');
		},

		exitFullScreen: function() {

			var t = this;

            // Prevent container from attempting to stretch a second time
            clearTimeout(t.containerSizeTimeout);

			// firefox can't adjust plugins
			/*
			if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
				t.media.setFullscreen(false);
				//player.isFullScreen = false;
				return;
			}
			*/

			// come out of native fullscreen
			if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
				mejs.MediaFeatures.cancelFullScreen();
			}

			// restore scroll bars to document
            $(document.documentElement).removeClass('mejs-fullscreen');

			t.container
				.removeClass('mejs-container-fullscreen')
				.width(t.normalWidth)
				.height(t.normalHeight);

			if (t.media.pluginType === 'native') {
				t.$media
					.width(t.normalWidth)
					.height(t.normalHeight);
			} else {
				t.container.find('.mejs-shim')
					.width(t.normalWidth)
					.height(t.normalHeight);

				t.media.setVideoSize(t.normalWidth, t.normalHeight);
			}

			t.layers.children('div')
				.width(t.normalWidth)
				.height(t.normalHeight);

			t.fullscreenBtn
				.removeClass('mejs-unfullscreen')
				.addClass('mejs-fullscreen');

			t.setControlsSize();
			t.isFullScreen = false;

			t.container.find('.mejs-captions-text').css('font-size','');
			t.container.find('.mejs-captions-text').css('line-height', '');
			t.container.find('.mejs-captions-position').css('bottom', '');

			t.container.trigger('exitedfullscreen');
		}
	});

})(mejs.$);

(function($) {

	// Speed
	$.extend(mejs.MepDefaults, {

		// We also support to pass object like this:
		// [{name: 'Slow', value: '0.75'}, {name: 'Normal', value: '1.00'}, ...]
		speeds: ['2.00', '1.50', '1.25', '1.00', '0.75'],

		defaultSpeed: '1.00',
		
		speedChar: 'x'

	});

	$.extend(MediaElementPlayer.prototype, {

		buildspeed: function(player, controls, layers, media) {
			var t = this;

			if (t.media.pluginType == 'native') {
				var 
					speedButton = null,
					speedSelector = null,
					playbackSpeed = null,
					inputId = null;

				var speeds = [];
				var defaultInArray = false;
				for (var i=0, len=t.options.speeds.length; i < len; i++) {
					var s = t.options.speeds[i];
					if (typeof(s) === 'string'){
						speeds.push({
							name: s + t.options.speedChar,
							value: s
						});
						if(s === t.options.defaultSpeed) {
							defaultInArray = true;
						}
					}
					else {
						speeds.push(s);
						if(s.value === t.options.defaultSpeed) {
							defaultInArray = true;
						}
					}
				}

				if (!defaultInArray) {
					speeds.push({
						name: t.options.defaultSpeed + t.options.speedChar,
						value: t.options.defaultSpeed
					});
				}

				speeds.sort(function(a, b) {
					return parseFloat(b.value) - parseFloat(a.value);
				});

				var getSpeedNameFromValue = function(value) {
					for(i=0,len=speeds.length; i <len; i++) {
						if (speeds[i].value === value) {
							return speeds[i].name;
						}
					}
				};

				var html = '<div class="mejs-button mejs-speed-button">' +
							'<button type="button">' + getSpeedNameFromValue(t.options.defaultSpeed) + '</button>' +
							'<div class="mejs-speed-selector">' +
							'<ul>';

				for (i = 0, il = speeds.length; i<il; i++) {
					inputId = t.id + '-speed-' + speeds[i].value;
					html += '<li>' + 
								'<input type="radio" name="speed" ' + 
											'value="' + speeds[i].value + '" ' +
											'id="' + inputId + '" ' +
											(speeds[i].value === t.options.defaultSpeed ? ' checked' : '') +
											' />' +
								'<label for="' + inputId + '" ' +
											(speeds[i].value === t.options.defaultSpeed ? ' class="mejs-speed-selected"' : '') +
											'>' + speeds[i].name + '</label>' +
							'</li>';
				}
				html += '</ul></div></div>';

				speedButton = $(html).appendTo(controls);
				speedSelector = speedButton.find('.mejs-speed-selector');

				playbackSpeed = t.options.defaultSpeed;

				media.addEventListener('loadedmetadata', function(e) {
					if (playbackSpeed) {
						media.playbackRate = parseFloat(playbackSpeed);
					}
				}, true);

				speedSelector
					.on('click', 'input[type="radio"]', function() {
						var newSpeed = $(this).attr('value');
						playbackSpeed = newSpeed;
						media.playbackRate = parseFloat(newSpeed);
						speedButton.find('button').html(getSpeedNameFromValue(newSpeed));
						speedButton.find('.mejs-speed-selected').removeClass('mejs-speed-selected');
						speedButton.find('input[type="radio"]:checked').next().addClass('mejs-speed-selected');
					});
				speedButton
					.one( 'mouseenter focusin', function() {
						speedSelector
							.height(
								speedButton.find('.mejs-speed-selector ul').outerHeight(true) +
								speedButton.find('.mejs-speed-translations').outerHeight(true))
							.css('top', (-1 * speedSelector.height()) + 'px');
					});
			}
		}
	});

})(mejs.$);

(function($) {

	// add extra default options
	$.extend(mejs.MepDefaults, {
		// this will automatically turn on a <track>
		startLanguage: '',

		tracksText: '',

		// By default, no WAI-ARIA live region - don't make a
		// screen reader speak captions over an audio track.
		tracksAriaLive: false,

		// option to remove the [cc] button when no <track kind="subtitles"> are present
		hideCaptionsButtonWhenEmpty: true,

		// If true and we only have one track, change captions to popup
		toggleCaptionsButtonWhenOnlyOne: false,

		// #id or .class
		slidesSelector: ''
	});

	$.extend(MediaElementPlayer.prototype, {

		hasChapters: false,

		cleartracks: function(player, controls, layers, media){
			if(player) {
				if(player.captions) player.captions.remove();
				if(player.chapters) player.chapters.remove();
				if(player.captionsText) player.captionsText.remove();
				if(player.captionsButton) player.captionsButton.remove();
			}
		},
		buildtracks: function(player, controls, layers, media) {
			if (player.tracks.length === 0)
				return;

			var t = this,
				attr = t.options.tracksAriaLive ?
					'role="log" aria-live="assertive" aria-atomic="false"' : '',
				tracksTitle = t.options.tracksText ? t.options.tracksText : mejs.i18n.t('mejs.captions-subtitles'),
				i,
				kind;

			if (t.domNode.textTracks) { // if browser will do native captions, prefer mejs captions, loop through tracks and hide
				for (i = t.domNode.textTracks.length - 1; i >= 0; i--) {
					t.domNode.textTracks[i].mode = "hidden";
				}
			}
			t.cleartracks(player, controls, layers, media);
			player.chapters =
					$('<div class="mejs-chapters mejs-layer"></div>')
						.prependTo(layers).hide();
			player.captions =
					$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover" ' +
					attr + '><span class="mejs-captions-text"></span></div></div>')
						.prependTo(layers).hide();
			player.captionsText = player.captions.find('.mejs-captions-text');
			player.captionsButton =
					$('<div class="mejs-button mejs-captions-button">'+
						'<button type="button" aria-controls="' + t.id + '" title="' + tracksTitle + '" aria-label="' + tracksTitle + '"></button>'+
						'<div class="mejs-captions-selector">'+
							'<ul>'+
								'<li>'+
									'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
									'<label for="' + player.id + '_captions_none">' + mejs.i18n.t('mejs.none') +'</label>'+
								'</li>'	+
							'</ul>'+
						'</div>'+
					'</div>')
						.appendTo(controls);


			var subtitleCount = 0;
			for (i=0; i<player.tracks.length; i++) {
				kind = player.tracks[i].kind;
				if (kind === 'subtitles' || kind === 'captions') {
					subtitleCount++;
				}
			}

			// if only one language then just make the button a toggle
			if (t.options.toggleCaptionsButtonWhenOnlyOne && subtitleCount == 1){
				// click
				player.captionsButton.on('click',function() {
					if (player.selectedTrack === null) {
						lang = player.tracks[0].srclang;
					} else {
						lang = 'none';
					}
					player.setTrack(lang);
				});
			} else {
				// hover or keyboard focus
				player.captionsButton.on( 'mouseenter focusin', function() {
					$(this).find('.mejs-captions-selector').removeClass('mejs-offscreen');
				})

				// handle clicks to the language radio buttons
				.on('click','input[type=radio]',function() {
					lang = this.value;
					player.setTrack(lang);
				});

				player.captionsButton.on( 'mouseleave focusout', function() {
					$(this).find(".mejs-captions-selector").addClass("mejs-offscreen");
				});

			}

			if (!player.options.alwaysShowControls) {
				// move with controls
				player.container
					.bind('controlsshown', function () {
						// push captions above controls
						player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');

					})
					.bind('controlshidden', function () {
						if (!media.paused) {
							// move back to normal place
							player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
						}
					});
			} else {
				player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
			}

			player.trackToLoad = -1;
			player.selectedTrack = null;
			player.isLoadingTrack = false;

			// add to list
			for (i=0; i<player.tracks.length; i++) {
				kind = player.tracks[i].kind;
				if (kind === 'subtitles' || kind === 'captions') {
					player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
				}
			}

			// start loading tracks
			player.loadNextTrack();

			media.addEventListener('timeupdate',function() {
				player.displayCaptions();
			}, false);

			if (player.options.slidesSelector !== '') {
				player.slidesContainer = $(player.options.slidesSelector);

				media.addEventListener('timeupdate',function() {
					player.displaySlides();
				}, false);

			}

			media.addEventListener('loadedmetadata', function() {
				player.displayChapters();
			}, false);

			player.container.hover(
				function () {
					// chapters
					if (player.hasChapters) {
						player.chapters.removeClass('mejs-offscreen');
						player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
					}
				},
				function () {
					if (player.hasChapters && !media.paused) {
						player.chapters.fadeOut(200, function() {
							$(this).addClass('mejs-offscreen');
							$(this).css('display','block');
						});
					}
				});

			t.container.on('controlsresize', function() {
				t.adjustLanguageBox();
			});

			// check for autoplay
			if (player.node.getAttribute('autoplay') !== null) {
				player.chapters.addClass('mejs-offscreen');
			}
		},

		setTrack: function(lang){

			var t = this,
				i;

			if (lang == 'none') {
				t.selectedTrack = null;
				t.captionsButton.removeClass('mejs-captions-enabled');
			} else {
				for (i=0; i<t.tracks.length; i++) {
					if (t.tracks[i].srclang == lang) {
						if (t.selectedTrack === null)
							t.captionsButton.addClass('mejs-captions-enabled');
						t.selectedTrack = t.tracks[i];
						t.captions.attr('lang', t.selectedTrack.srclang);
						t.displayCaptions();
						break;
					}
				}
			}
		},

		loadNextTrack: function() {
			var t = this;

			t.trackToLoad++;
			if (t.trackToLoad < t.tracks.length) {
				t.isLoadingTrack = true;
				t.loadTrack(t.trackToLoad);
			} else {
				// add done?
				t.isLoadingTrack = false;

				t.checkForTracks();
			}
		},

		loadTrack: function(index){
			var
				t = this,
				track = t.tracks[index],
				after = function() {

					track.isLoaded = true;

					t.enableTrackButton(track.srclang, track.label);

					t.loadNextTrack();

				};


			if (track.src !== undefined || track.src !== "") {
				$.ajax({
					url: track.src,
					dataType: "text",
					success: function(d) {

						// parse the loaded file
						if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
							track.entries = mejs.TrackFormatParser.dfxp.parse(d);
						} else {
							track.entries = mejs.TrackFormatParser.webvtt.parse(d);
						}

						after();

						if (track.kind == 'chapters') {
							t.media.addEventListener('play', function() {
								if (t.media.duration > 0) {
									t.displayChapters(track);
								}
							}, false);
						}

						if (track.kind == 'slides') {
							t.setupSlides(track);
						}
					},
					error: function() {
						t.removeTrackButton(track.srclang);
						t.loadNextTrack();
					}
				});
			}
		},

		enableTrackButton: function(lang, label) {
			var t = this;

			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}

			t.captionsButton
				.find('input[value=' + lang + ']')
					.prop('disabled',false)
				.siblings('label')
					.html( label );

			// auto select
			if (t.options.startLanguage == lang) {
				$('#' + t.id + '_captions_' + lang).prop('checked', true).trigger('click');
			}

			t.adjustLanguageBox();
		},

		removeTrackButton: function(lang) {
			var t = this;

			t.captionsButton.find('input[value=' + lang + ']').closest('li').remove();

			t.adjustLanguageBox();
		},

		addTrackButton: function(lang, label) {
			var t = this;
			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}

			t.captionsButton.find('ul').append(
				$('<li>'+
					'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
					'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
				'</li>')
			);

			t.adjustLanguageBox();

			// remove this from the dropdownlist (if it exists)
			t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
		},

		adjustLanguageBox:function() {
			var t = this;
			// adjust the size of the outer box
			t.captionsButton.find('.mejs-captions-selector').height(
				t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
				t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
			);
		},

		checkForTracks: function() {
			var
				t = this,
				hasSubtitles = false;

			// check if any subtitles
			if (t.options.hideCaptionsButtonWhenEmpty) {
				for (var i=0; i<t.tracks.length; i++) {
					var kind = t.tracks[i].kind;
					if ((kind === 'subtitles' || kind === 'captions') && t.tracks[i].isLoaded) {
						hasSubtitles = true;
						break;
					}
				}

				if (!hasSubtitles) {
					t.captionsButton.hide();
					t.setControlsSize();
				}
			}
		},

		displayCaptions: function() {

			if (typeof this.tracks == 'undefined')
				return;

			var
				t = this,
				i,
				track = t.selectedTrack;

			if (track !== null && track.isLoaded) {
				for (i=0; i<track.entries.times.length; i++) {
					if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop) {
						// Set the line before the timecode as a class so the cue can be targeted if needed
						t.captionsText.html(track.entries.text[i]).attr('class', 'mejs-captions-text ' + (track.entries.times[i].identifier || ''));
						t.captions.show().height(0);
						return; // exit out if one is visible;
					}
				}
				t.captions.hide();
			} else {
				t.captions.hide();
			}
		},

		setupSlides: function(track) {
			var t = this;

			t.slides = track;
			t.slides.entries.imgs = [t.slides.entries.text.length];
			t.showSlide(0);

		},

		showSlide: function(index) {
			if (typeof this.tracks == 'undefined' || typeof this.slidesContainer == 'undefined') {
				return;
			}

			var t = this,
				url = t.slides.entries.text[index],
				img = t.slides.entries.imgs[index];

			if (typeof img == 'undefined' || typeof img.fadeIn == 'undefined') {

				t.slides.entries.imgs[index] = img = $('<img src="' + url + '">')
						.on('load', function() {
							img.appendTo(t.slidesContainer)
								.hide()
								.fadeIn()
								.siblings(':visible')
									.fadeOut();

						});

			} else {

				if (!img.is(':visible') && !img.is(':animated')) {

					//

					img.fadeIn()
						.siblings(':visible')
							.fadeOut();
				}
			}

		},

		displaySlides: function() {

			if (typeof this.slides == 'undefined')
				return;

			var
				t = this,
				slides = t.slides,
				i;

			for (i=0; i<slides.entries.times.length; i++) {
				if (t.media.currentTime >= slides.entries.times[i].start && t.media.currentTime <= slides.entries.times[i].stop){

					t.showSlide(i);

					return; // exit out if one is visible;
				}
			}
		},

		displayChapters: function() {
			var
				t = this,
				i;

			for (i=0; i<t.tracks.length; i++) {
				if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
					t.drawChapters(t.tracks[i]);
					t.hasChapters = true;
					break;
				}
			}
		},

		drawChapters: function(chapters) {
			var
				t = this,
				i,
				dur,
				//width,
				//left,
				percent = 0,
				usedPercent = 0;

			t.chapters.empty();

			for (i=0; i<chapters.entries.times.length; i++) {
				dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
				percent = Math.floor(dur / t.media.duration * 100);
				if (percent + usedPercent > 100 || // too large
					i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
					{
					percent = 100 - usedPercent;
				}
				//width = Math.floor(t.width * dur / t.media.duration);
				//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
				//if (left + width > t.width) {
				//	width = t.width - left;
				//}

				t.chapters.append( $(
					'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
						'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
							'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
							'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start, t.options) + '&ndash;' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop, t.options) + '</span>' +
						'</div>' +
					'</div>'));
				usedPercent += percent;
			}

			t.chapters.find('div.mejs-chapter').click(function() {
				t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
				if (t.media.paused) {
					t.media.play();
				}
			});

			t.chapters.show();
		}
	});



	mejs.language = {
		codes:  {
			af:'Afrikaans',
			sq:'Albanian',
			ar:'Arabic',
			be:'Belarusian',
			bg:'Bulgarian',
			ca:'Catalan',
			zh:'Chinese',
			'zh-cn':'Chinese Simplified',
			'zh-tw':'Chinese Traditional',
			hr:'Croatian',
			cs:'Czech',
			da:'Danish',
			nl:'Dutch',
			en:'English',
			et:'Estonian',
			fl:'Filipino',
			fi:'Finnish',
			fr:'French',
			gl:'Galician',
			de:'German',
			el:'Greek',
			ht:'Haitian Creole',
			iw:'Hebrew',
			hi:'Hindi',
			hu:'Hungarian',
			is:'Icelandic',
			id:'Indonesian',
			ga:'Irish',
			it:'Italian',
			ja:'Japanese',
			ko:'Korean',
			lv:'Latvian',
			lt:'Lithuanian',
			mk:'Macedonian',
			ms:'Malay',
			mt:'Maltese',
			no:'Norwegian',
			fa:'Persian',
			pl:'Polish',
			pt:'Portuguese',
			// 'pt-pt':'Portuguese (Portugal)',
			ro:'Romanian',
			ru:'Russian',
			sr:'Serbian',
			sk:'Slovak',
			sl:'Slovenian',
			es:'Spanish',
			sw:'Swahili',
			sv:'Swedish',
			tl:'Tagalog',
			th:'Thai',
			tr:'Turkish',
			uk:'Ukrainian',
			vi:'Vietnamese',
			cy:'Welsh',
			yi:'Yiddish'
		}
	};

	/*
	Parses WebVTT format which should be formatted as
	================================
	WEBVTT

	1
	00:00:01,1 --> 00:00:05,000
	A line of text

	2
	00:01:15,1 --> 00:02:05,000
	A second line of text

	===============================

	Adapted from: http://www.delphiki.com/html5/playr
	*/
	mejs.TrackFormatParser = {
		webvtt: {
			pattern_timecode: /^((?:[0-9]{1,2}:)?[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ((?:[0-9]{1,2}:)?[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,

			parse: function(trackText) {
				var
					i = 0,
					lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
					entries = {text:[], times:[]},
					timecode,
					text,
					identifier;
				for(; i<lines.length; i++) {
					timecode = this.pattern_timecode.exec(lines[i]);

					if (timecode && i<lines.length) {
						if ((i - 1) >= 0 && lines[i - 1] !== '') {
							identifier = lines[i - 1];
						}
						i++;
						// grab all the (possibly multi-line) text that follows
						text = lines[i];
						i++;
						while(lines[i] !== '' && i<lines.length){
							text = text + '\n' + lines[i];
							i++;
						}
						text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
						// Text is in a different array so I can use .join
						entries.text.push(text);
						entries.times.push(
						{
							identifier: identifier,
							start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) === 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
							stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
							settings: timecode[5]
						});
					}
					identifier = '';
				}
				return entries;
			}
		},
		// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
		dfxp: {
			parse: function(trackText) {
				trackText = $(trackText).filter("tt");
				var
					i = 0,
					container = trackText.children("div").eq(0),
					lines = container.find("p"),
					styleNode = trackText.find("#" + container.attr("style")),
					styles,
					text,
					entries = {text:[], times:[]};


				if (styleNode.length) {
					var attributes = styleNode.removeAttr("id").get(0).attributes;
					if (attributes.length) {
						styles = {};
						for (i = 0; i < attributes.length; i++) {
							styles[attributes[i].name.split(":")[1]] = attributes[i].value;
						}
					}
				}

				for(i = 0; i<lines.length; i++) {
					var style;
					var _temp_times = {
						start: null,
						stop: null,
						style: null
					};
					if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
					if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
					if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
					if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
					if (styles) {
						style = "";
						for (var _style in styles) {
							style += _style + ":" + styles[_style] + ";";
						}
					}
					if (style) _temp_times.style = style;
					if (_temp_times.start === 0) _temp_times.start = 0.200;
					entries.times.push(_temp_times);
					text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
					entries.text.push(text);
				}
				return entries;
			}
		},
		split2: function (text, regex) {
			// normal version for compliant browsers
			// see below for IE fix
			return text.split(regex);
		}
	};

	// test for browsers with bad String.split method.
	if ('x\n\ny'.split(/\n/gi).length != 3) {
		// add super slow IE8 and below version
		mejs.TrackFormatParser.split2 = function(text, regex) {
			var
				parts = [],
				chunk = '',
				i;

			for (i=0; i<text.length; i++) {
				chunk += text.substring(i,i+1);
				if (regex.test(chunk)) {
					parts.push(chunk.replace(regex, ''));
					chunk = '';
				}
			}
			parts.push(chunk);
			return parts;
		};
	}

})(mejs.$);

// Source Chooser Plugin
(function($) {

	$.extend(mejs.MepDefaults, {
		sourcechooserText: ''
	});

	$.extend(MediaElementPlayer.prototype, {
		buildsourcechooser: function(player, controls, layers, media) {

			var
				t = this,
				sourceTitle = t.options.sourcechooserText ? t.options.sourcechooserText : mejs.i18n.t('mejs.source-chooser'),
				hoverTimeout
			;

			player.sourcechooserButton =
				$('<div class="mejs-button mejs-sourcechooser-button">'+
						'<button type="button" role="button" aria-haspopup="true" aria-owns="' + t.id + '" title="' + sourceTitle + '" aria-label="' + sourceTitle + '"></button>'+
						'<div class="mejs-sourcechooser-selector mejs-offscreen" role="menu" aria-expanded="false" aria-hidden="true">'+
							'<ul>'+
							'</ul>'+
						'</div>'+
					'</div>')
					.appendTo(controls)

					// hover
					.hover(function() {
						clearTimeout(hoverTimeout);
						player.showSourcechooserSelector();
					}, function() {
						var self = $(this);
						hoverTimeout = setTimeout(function () {
						player.hideSourcechooserSelector();
						}, 500);
					})

					// keyboard menu activation
					.on('keydown', function (e) {
						var keyCode = e.keyCode;

						switch (keyCode) {
							case 32: // space
								if (!mejs.MediaFeatures.isFirefox) { // space sends the click event in Firefox
									player.showSourcechooserSelector();
								}
								$(this).find('.mejs-sourcechooser-selector')
									.find('input[type=radio]:checked').first().focus();
								break;
							case 13: // enter
								player.showSourcechooserSelector();
								$(this).find('.mejs-sourcechooser-selector')
									.find('input[type=radio]:checked').first().focus();
								break;
							case 27: // esc
								player.hideSourcechooserSelector();
								$(this).find('button').focus();
								break;
							default:
								return true;
								}
							})

					// close menu when tabbing away
					.on('focusout', mejs.Utility.debounce(function (e) { // Safari triggers focusout multiple times
						// Firefox does NOT support e.relatedTarget to see which element
						// just lost focus, so wait to find the next focused element
						setTimeout(function () {
							var parent = $(document.activeElement).closest('.mejs-sourcechooser-selector');
							if (!parent.length) {
								// focus is outside the control; close menu
								player.hideSourcechooserSelector();
							}
						}, 0);
					}, 100))

					// handle clicks to the source radio buttons
					.delegate('input[type=radio]', 'click', function() {
						// set aria states
						$(this).attr('aria-selected', true).attr('checked', 'checked');
						$(this).closest('.mejs-sourcechooser-selector').find('input[type=radio]').not(this).attr('aria-selected', 'false').removeAttr('checked');

						var src = this.value;

						if (media.currentSrc != src) {
							var currentTime = media.currentTime;
							var paused = media.paused;
							media.pause();
							media.setSrc(src);

							media.addEventListener('loadedmetadata', function(e) {
								media.currentTime = currentTime;
							}, true);

							var canPlayAfterSourceSwitchHandler = function(e) {
								if (!paused) {
									media.play();
								}
								media.removeEventListener("canplay", canPlayAfterSourceSwitchHandler, true);
							};
							media.addEventListener('canplay', canPlayAfterSourceSwitchHandler, true);
							media.load();
						}
					})

					// Handle click so that screen readers can toggle the menu
					.delegate('button', 'click', function (e) {
						if ($(this).siblings('.mejs-sourcechooser-selector').hasClass('mejs-offscreen')) {
							player.showSourcechooserSelector();
							$(this).siblings('.mejs-sourcechooser-selector').find('input[type=radio]:checked').first().focus();
						} else {
							player.hideSourcechooserSelector();
						}
					});

			// add to list
			for (var i in this.node.children) {
				var src = this.node.children[i];
				if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) == 'probably' || media.canPlayType(src.type) == 'maybe')) {
					player.addSourceButton(src.src, src.title, src.type, media.src == src.src);
				}
			}
		},

		addSourceButton: function(src, label, type, isCurrent) {
			var t = this;
			if (label === '' || label == undefined) {
				label = src;
			}
			type = type.split('/')[1];

			t.sourcechooserButton.find('ul').append(
				$('<li>'+
						'<input type="radio" name="' + t.id + '_sourcechooser" id="' + t.id + '_sourcechooser_' + label + type + '" role="menuitemradio" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + 'aria-selected="' + isCurrent + '"' + ' />'+
						'<label for="' + t.id + '_sourcechooser_' + label + type + '" aria-hidden="true">' + label + ' (' + type + ')</label>'+
					'</li>')
			);

			t.adjustSourcechooserBox();

		},

		adjustSourcechooserBox: function() {
			var t = this;
			// adjust the size of the outer box
			t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
				t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
			);
		},

		hideSourcechooserSelector: function () {
			this.sourcechooserButton.find('.mejs-sourcechooser-selector')
				.addClass('mejs-offscreen')
				.attr('aria-expanded', 'false')
				.attr('aria-hidden', 'true')
				.find('input[type=radio]') // make radios not fucusable
				.attr('tabindex', '-1');
		},

		showSourcechooserSelector: function () {
			this.sourcechooserButton.find('.mejs-sourcechooser-selector')
				.removeClass('mejs-offscreen')
				.attr('aria-expanded', 'true')
				.attr('aria-hidden', 'false')
				.find('input[type=radio]')
				.attr('tabindex', '0');
		}
	});

})(mejs.$);

/*
* ContextMenu Plugin
* 
*
*/

(function($) {

$.extend(mejs.MepDefaults,
	{ 'contextMenuItems': [
		// demo of a fullscreen option
		{ 
			render: function(player) {
				
				// check for fullscreen plugin
				if (typeof player.enterFullScreen == 'undefined')
					return null;
			
				if (player.isFullScreen) {
					return mejs.i18n.t('mejs.fullscreen-off');
				} else {
					return mejs.i18n.t('mejs.fullscreen-on');
				}
			},
			click: function(player) {
				if (player.isFullScreen) {
					player.exitFullScreen();
				} else {
					player.enterFullScreen();
				}
			}
		}
		,
		// demo of a mute/unmute button
		{ 
			render: function(player) {
				if (player.media.muted) {
					return mejs.i18n.t('mejs.unmute');
				} else {
					return mejs.i18n.t('mejs.mute');
				}
			},
			click: function(player) {
				if (player.media.muted) {
					player.setMuted(false);
				} else {
					player.setMuted(true);
				}
			}
		},
		// separator
		{
			isSeparator: true
		}
		,
		// demo of simple download video
		{ 
			render: function(player) {
				return mejs.i18n.t('mejs.download-video');
			},
			click: function(player) {
				window.location.href = player.media.currentSrc;
			}
		}	
	]}
);


	$.extend(MediaElementPlayer.prototype, {
		buildcontextmenu: function(player, controls, layers, media) {
			
			// create context menu
			player.contextMenu = $('<div class="mejs-contextmenu"></div>')
								.appendTo($('body'))
								.hide();
			
			// create events for showing context menu
			player.container.bind('contextmenu', function(e) {
				if (player.isContextMenuEnabled) {
					e.preventDefault();
					player.renderContextMenu(e.clientX-1, e.clientY-1);
					return false;
				}
			});
			player.container.bind('click', function() {
				player.contextMenu.hide();
			});	
			player.contextMenu.bind('mouseleave', function() {

				//
				player.startContextMenuTimer();
				
			});		
		},

		cleancontextmenu: function(player) {
			player.contextMenu.remove();
		},
		
		isContextMenuEnabled: true,
		enableContextMenu: function() {
			this.isContextMenuEnabled = true;
		},
		disableContextMenu: function() {
			this.isContextMenuEnabled = false;
		},
		
		contextMenuTimeout: null,
		startContextMenuTimer: function() {
			//
			
			var t = this;
			
			t.killContextMenuTimer();
			
			t.contextMenuTimer = setTimeout(function() {
				t.hideContextMenu();
				t.killContextMenuTimer();
			}, 750);
		},
		killContextMenuTimer: function() {
			var timer = this.contextMenuTimer;
			
			//
			
			if (timer != null) {				
				clearTimeout(timer);
				delete timer;
				timer = null;
			}
		},		
		
		hideContextMenu: function() {
			this.contextMenu.hide();
		},
		
		renderContextMenu: function(x,y) {
			
			// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
			var t = this,
				html = '',
				items = t.options.contextMenuItems;
			
			for (var i=0, il=items.length; i<il; i++) {
				
				if (items[i].isSeparator) {
					html += '<div class="mejs-contextmenu-separator"></div>';
				} else {
				
					var rendered = items[i].render(t);
				
					// render can return null if the item doesn't need to be used at the moment
					if (rendered != null) {
						html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
					}
				}
			}
			
			// position and show the context menu
			t.contextMenu
				.empty()
				.append($(html))
				.css({top:y, left:x})
				.show();
				
			// bind events
			t.contextMenu.find('.mejs-contextmenu-item').each(function() {
							
				// which one is this?
				var $dom = $(this),
					itemIndex = parseInt( $dom.data('itemindex'), 10 ),
					item = t.options.contextMenuItems[itemIndex];
				
				// bind extra functionality?
				if (typeof item.show != 'undefined')
					item.show( $dom , t);
				
				// bind click action
				$dom.click(function() {			
					// perform click action
					if (typeof item.click != 'undefined')
						item.click(t);
					
					// close
					t.contextMenu.hide();				
				});				
			});	
			
			// stop the controls from hiding
			setTimeout(function() {
				t.killControlsTimer('rev3');	
			}, 100);
						
		}
	});
	
})(mejs.$);
(function($) {
	// skip back button

	$.extend(mejs.MepDefaults, {
		skipBackInterval: 30,
		// %1 will be replaced with skipBackInterval in this string
		skipBackText: ''
	});

	$.extend(MediaElementPlayer.prototype, {
		buildskipback: function(player, controls, layers, media) {
			var
				t = this,
				defaultTitle = mejs.i18n.t('mejs.time-skip-back', t.options.skipBackInterval),
				skipTitle = t.options.skipBackText ? t.options.skipBackText : defaultTitle,
				// create the loop button
				loop =
				$('<div class="mejs-button mejs-skip-back-button">' +
					'<button type="button" aria-controls="' + t.id + '" title="' + skipTitle + '" aria-label="' + skipTitle + '">' + t.options.skipBackInterval + '</button>' +
				'</div>')
				// append it to the toolbar
				.appendTo(controls)
				// add a click toggle event
				.click(function() {
					media.setCurrentTime(Math.max(media.currentTime - t.options.skipBackInterval, 0));
					$(this).find('button').blur();
				});
		}
	});

})(mejs.$);

/**
 * Postroll plugin
 */
(function($) {

	$.extend(mejs.MepDefaults, {
		postrollCloseText: ''
	});

	// Postroll
	$.extend(MediaElementPlayer.prototype, {
		buildpostroll: function(player, controls, layers, media) {
			var
				t = this,
				postrollTitle = t.options.postrollCloseText ? t.options.postrollCloseText : mejs.i18n.t('mejs.close'),
				postrollLink = t.container.find('link[rel="postroll"]').attr('href');

			if (typeof postrollLink !== 'undefined') {
				player.postroll =
					$('<div class="mejs-postroll-layer mejs-layer"><a class="mejs-postroll-close" onclick="$(this).parent().hide();return false;">' + postrollTitle + '</a><div class="mejs-postroll-layer-content"></div></div>').prependTo(layers).hide();

				t.media.addEventListener('ended', function (e) {
					$.ajax({
						dataType: 'html',
						url: postrollLink,
						success: function (data, textStatus) {
							layers.find('.mejs-postroll-layer-content').html(data);
						}
					});
					player.postroll.show();
				}, false);
			}
		}
	});

})(mejs.$);
/*
MediaElement-Markers is a MediaElement.js plugin that lets you add Visual Cues in the progress time rail. 
This plugin also lets you register a custom callback function that will be called everytime the play position reaches a marker. 
Marker position and a reference to the MediaElement Player object is passed to the registered callback function for any post processing. Marker color is configurable.

*/

(function ($) {
    // markers

    $.extend(mejs.MepDefaults, {
        markerColor: '#E9BC3D', //default marker color
        markers: [],
        markerCallback: function () {

        }
    });

    $.extend(MediaElementPlayer.prototype, {
        buildmarkers: function (player, controls, layers, media) {
            var t = this,
                i = 0,
                currentPos = -1,
                currentMarker = -1,
                lastPlayPos = -1, //Track backward seek
                lastMarkerCallBack = -1; //Prevents successive firing of callbacks

            for (i = 0; i < player.options.markers.length; ++i) {
                controls.find('.mejs-time-total').append('<span class="mejs-time-marker"></span>');
            }

            media.addEventListener('durationchange', function (e) {
                player.setmarkers(controls);
            });
            media.addEventListener('timeupdate', function (e) {
                currentPos = Math.floor(media.currentTime);
                if (lastPlayPos > currentPos) {
                    if (lastMarkerCallBack > currentPos) {
                        lastMarkerCallBack = -1;
                    }
                } else {
                    lastPlayPos = currentPos;
                }

                for (i = 0; i < player.options.markers.length; ++i) {
                    currentMarker = Math.floor(player.options.markers[i]); 
                    if (currentPos === currentMarker && currentMarker !== lastMarkerCallBack) {
                        player.options.markerCallback(media, media.currentTime); //Fires the callback function
                        lastMarkerCallBack = currentMarker;
                    }
                }

            }, false);

        },
        setmarkers: function (controls) {
            var t = this,
                i = 0,
                left;

            for (i = 0; i < t.options.markers.length; ++i) {
                if (Math.floor(t.options.markers[i]) <= t.media.duration && Math.floor(t.options.markers[i]) >= 0) {
                    left = 100 * Math.floor(t.options.markers[i]) / t.media.duration;
                    $(controls.find('.mejs-time-marker')[i]).css({
                        "width": "1px",
                        "left": left+"%",
                        "background": t.options.markerColor
                    });
                }
            }

        }
    });
})(mejs.$);
/*!
 *
 * MediaElement.js
 * HTML5 <video> and <audio> shim and player
 * http://mediaelementjs.com/
 *
 * Creates a JavaScript object that mimics HTML5 MediaElement API
 * for browsers that don't understand HTML5 or can't play the provided codec
 * Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
 *
 * Copyright 2010-2014, John Dyer (http://j.hn)
 * License: MIT
 *
 */
// Namespace
var mejs = mejs || {};

// version number
mejs.version = '2.23.5';


// player number (for missing, same id attr)
mejs.meIndex = 0;

// media types accepted by plugins
mejs.plugins = {
	silverlight: [
		{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
	],
	flash: [
		{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a', 'audio/mp4', 'audio/mpeg', 'video/dailymotion', 'video/x-dailymotion', 'application/x-mpegURL', 'audio/ogg']}
		// 'video/youtube', 'video/x-youtube', 
		// ,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
	],
	youtube: [
		{version: null, types: ['video/youtube', 'video/x-youtube', 'audio/youtube', 'audio/x-youtube']}
	],
	vimeo: [
		{version: null, types: ['video/vimeo', 'video/x-vimeo']}
	]
};

/*
Utility methods
*/
mejs.Utility = {
	encodeUrl: function(url) {
		return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
	},
	escapeHTML: function(s) {
		return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
	},
	absolutizeUrl: function(url) {
		var el = document.createElement('div');
		el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
		return el.firstChild.href;
	},
	getScriptPath: function(scriptNames) {
		var
			i = 0,
			j,
			codePath = '',
			testname = '',
			slashPos,
			filenamePos,
			scriptUrl,
			scriptPath,			
			scriptFilename,
			scripts = document.getElementsByTagName('script'),
			il = scripts.length,
			jl = scriptNames.length;
			
		// go through all <script> tags
		for (; i < il; i++) {
			scriptUrl = scripts[i].src;
			slashPos = scriptUrl.lastIndexOf('/');
			if (slashPos > -1) {
				scriptFilename = scriptUrl.substring(slashPos + 1);
				scriptPath = scriptUrl.substring(0, slashPos + 1);
			} else {
				scriptFilename = scriptUrl;
				scriptPath = '';			
			}
			
			// see if any <script> tags have a file name that matches the 
			for (j = 0; j < jl; j++) {
				testname = scriptNames[j];
				filenamePos = scriptFilename.indexOf(testname);
				if (filenamePos > -1) {
					codePath = scriptPath;
					break;
				}
			}
			
			// if we found a path, then break and return it
			if (codePath !== '') {
				break;
			}
		}
		
		// send the best path back
		return codePath;
	},
	/*
	 * Calculate the time format to use. We have a default format set in the
	 * options but it can be imcomplete. We ajust it according to the media
	 * duration.
	 *
	 * We support format like 'hh:mm:ss:ff'.
	 */
	calculateTimeFormat: function(time, options, fps) {
		if (time < 0) {
			time = 0;
		}

		if(typeof fps == 'undefined') {
		    fps = 25;
		}

		var format = options.timeFormat,
			firstChar = format[0],
			firstTwoPlaces = (format[1] == format[0]),
			separatorIndex = firstTwoPlaces? 2: 1,
			separator = ':',
			hours = Math.floor(time / 3600) % 24,
			minutes = Math.floor(time / 60) % 60,
			seconds = Math.floor(time % 60),
			frames = Math.floor(((time % 1)*fps).toFixed(3)),
			lis = [
				[frames, 'f'],
				[seconds, 's'],
				[minutes, 'm'],
				[hours, 'h']
			];

		// Try to get the separator from the format
		if (format.length < separatorIndex) {
			separator = format[separatorIndex];
		}

		var required = false;

		for (var i=0, len=lis.length; i < len; i++) {
			if (format.indexOf(lis[i][1]) !== -1) {
				required=true;
			}
			else if (required) {
				var hasNextValue = false;
				for (var j=i; j < len; j++) {
					if (lis[j][0] > 0) {
						hasNextValue = true;
						break;
					}
				}

				if (! hasNextValue) {
					break;
				}

				if (!firstTwoPlaces) {
					format = firstChar + format;
				}
				format = lis[i][1] + separator + format;
				if (firstTwoPlaces) {
					format = lis[i][1] + format;
				}
				firstChar = lis[i][1];
			}
		}
		options.currentTimeFormat = format;
	},
	/*
	 * Prefix the given number by zero if it is lower than 10.
	 */
	twoDigitsString: function(n) {
		if (n < 10) {
			return '0' + n;
		}
		return String(n);
	},
	secondsToTimeCode: function(time, options) {
		if (time < 0) {
			time = 0;
		}

		// Maintain backward compatibility with method signature before v2.18.
		if (typeof options !== 'object') {
			var format = 'm:ss';
			format = arguments[1] ? 'hh:mm:ss' : format; // forceHours
			format = arguments[2] ? format + ':ff' : format; // showFrameCount

			options = {
				currentTimeFormat: format,
				framesPerSecond: arguments[3] || 25
			};
		}

		var fps = options.framesPerSecond;
		if(typeof fps === 'undefined') {
			fps = 25;
		}

		var format = options.currentTimeFormat,
			hours = Math.floor(time / 3600) % 24,
			minutes = Math.floor(time / 60) % 60,
			seconds = Math.floor(time % 60),
			frames = Math.floor(((time % 1)*fps).toFixed(3));
			lis = [
				[frames, 'f'],
				[seconds, 's'],
				[minutes, 'm'],
				[hours, 'h']
			];

		var res = format;
		for (i=0,len=lis.length; i < len; i++) {
			res = res.replace(lis[i][1]+lis[i][1], this.twoDigitsString(lis[i][0]));
			res = res.replace(lis[i][1], lis[i][0]);
		}
		return res;
	},
	
	timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
		if (typeof showFrameCount == 'undefined') {
		    showFrameCount=false;
		} else if(typeof fps == 'undefined') {
		    fps = 25;
		}
	
		var tc_array = hh_mm_ss_ff.split(":"),
			tc_hh = parseInt(tc_array[0], 10),
			tc_mm = parseInt(tc_array[1], 10),
			tc_ss = parseInt(tc_array[2], 10),
			tc_ff = 0,
			tc_in_seconds = 0;
		
		if (showFrameCount) {
		    tc_ff = parseInt(tc_array[3])/fps;
		}
		
		tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
		
		return tc_in_seconds;
	},
	

	convertSMPTEtoSeconds: function (SMPTE) {
		if (typeof SMPTE != 'string') 
			return false;

		SMPTE = SMPTE.replace(',', '.');
		
		var secs = 0,
			decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
			multiplier = 1;
		
		SMPTE = SMPTE.split(':').reverse();
		
		for (var i = 0; i < SMPTE.length; i++) {
			multiplier = 1;
			if (i > 0) {
				multiplier = Math.pow(60, i); 
			}
			secs += Number(SMPTE[i]) * multiplier;
		}
		return Number(secs.toFixed(decimalLen));
	},	
	
	/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
	removeSwf: function(id) {
		var obj = document.getElementById(id);
		if (obj && /object|embed/i.test(obj.nodeName)) {
			if (mejs.MediaFeatures.isIE) {
				obj.style.display = "none";
				(function(){
					if (obj.readyState == 4) {
						mejs.Utility.removeObjectInIE(id);
					} else {
						setTimeout(arguments.callee, 10);
					}
				})();
			} else {
				obj.parentNode.removeChild(obj);
			}
		}
	},
	removeObjectInIE: function(id) {
		var obj = document.getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}		
	},
    determineScheme: function(url) {
        if (url && url.indexOf("://") != -1) {
            return url.substr(0, url.indexOf("://")+3);
        }
        return "//"; // let user agent figure this out
    },

	// taken from underscore
	debounce: function(func, wait, immediate) {
		var timeout;
		return function() {
			var context = this, args = arguments;
			var later = function() {
				timeout = null;
				if (!immediate) func.apply(context, args);
			};
			var callNow = immediate && !timeout;
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
			if (callNow) func.apply(context, args);
		};
	},

	/**
	* Returns true if targetNode appears after sourceNode in the dom.
	* @param {HTMLElement} sourceNode - the source node for comparison
	* @param {HTMLElement} targetNode - the node to compare against sourceNode
	*/
	isNodeAfter: function(sourceNode, targetNode) {
		return !!(
			sourceNode &&
			targetNode &&
			typeof sourceNode.compareDocumentPosition === 'function' &&
			sourceNode.compareDocumentPosition(targetNode) & Node.DOCUMENT_POSITION_PRECEDING
		);
	}
};


// Core detector, plugins are added below
mejs.PluginDetector = {

	// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
	hasPluginVersion: function(plugin, v) {
		var pv = this.plugins[plugin];
		v[1] = v[1] || 0;
		v[2] = v[2] || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	},

	// cached values
	nav: window.navigator,
	ua: window.navigator.userAgent.toLowerCase(),

	// stored version numbers
	plugins: [],

	// runs detectPlugin() and stores the version number
	addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
		this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
	},

	// get the version number from the mimetype (all but IE) or ActiveX (IE)
	detectPlugin: function(pluginName, mimeType, activeX, axDetect) {

		var version = [0,0,0],
			description,
			i,
			ax;

		// Firefox, Webkit, Opera
		if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
			description = this.nav.plugins[pluginName].description;
			if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
				version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
				for (i=0; i<version.length; i++) {
					version[i] = parseInt(version[i].match(/\d+/), 10);
				}
			}
		// Internet Explorer / ActiveX
		} else if (typeof(window.ActiveXObject) != 'undefined') {
			try {
				ax = new ActiveXObject(activeX);
				if (ax) {
					version = axDetect(ax);
				}
			}
			catch (e) { }
		}
		return version;
	}
};

// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
	// adapted from SWFObject
	var version = [],
		d = ax.GetVariable("$version");
	if (d) {
		d = d.split(" ")[1].split(",");
		version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
	}
	return version;
});

// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
	// Silverlight cannot report its version number to IE
	// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
	// adapted from http://www.silverlightversion.com/
	var v = [0,0,0,0],
		loopMatch = function(ax, v, i, n) {
			while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
				v[i]+=n;
			}
			v[i] -= n;
		};
	loopMatch(ax, v, 0, 1);
	loopMatch(ax, v, 1, 1);
	loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
	loopMatch(ax, v, 2, 1000);
	loopMatch(ax, v, 2, 100);
	loopMatch(ax, v, 2, 10);
	loopMatch(ax, v, 2, 1);
	loopMatch(ax, v, 3, 1);

	return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
	var version = [],
		d = ax.GetVersions().split(',')[0].split('=')[1].split('.');

	if (d) {
		version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
	}
	return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
	init: function() {
		var
			t = this,
			d = document,
			nav = mejs.PluginDetector.nav,
			ua = mejs.PluginDetector.ua.toLowerCase(),
			i,
			v,
			html5Elements = ['source','track','audio','video'];

		// detect browsers (only the ones that have some kind of quirk we need to work around)
		t.isiPad = (ua.match(/ipad/i) !== null);
		t.isiPhone = (ua.match(/iphone/i) !== null);
		t.isiOS = t.isiPhone || t.isiPad;
		t.isAndroid = (ua.match(/android/i) !== null);
		t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
		t.isBustedNativeHTTPS = (location.protocol === 'https:' && (ua.match(/android [12]\./) !== null || ua.match(/macintosh.* version.* safari/) !== null));
		t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1 || nav.appName.toLowerCase().match(/trident/gi) !== null);
		t.isChrome = (ua.match(/chrome/gi) !== null);
		t.isChromium = (ua.match(/chromium/gi) !== null);
		t.isFirefox = (ua.match(/firefox/gi) !== null);
		t.isWebkit = (ua.match(/webkit/gi) !== null);
		t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit && !t.isIE;
		t.isOpera = (ua.match(/opera/gi) !== null);
		t.hasTouch = ('ontouchstart' in window); //  && window.ontouchstart != null); // this breaks iOS 7

		// Borrowed from `Modernizr.svgasimg`, sources:
		// - https://github.com/Modernizr/Modernizr/issues/687
		// - https://github.com/Modernizr/Modernizr/pull/1209/files
		t.svgAsImg = !!document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');

		// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
		for (i=0; i<html5Elements.length; i++) {
			v = document.createElement(html5Elements[i]);
		}

		t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);

		// Fix for IE9 on Windows 7N / Windows 7KN (Media Player not installer)
		try{
			v.canPlayType("video/mp4");
		}catch(e){
			t.supportsMediaTag = false;
		}

		t.supportsPointerEvents = (function() {
			// TAKEN FROM MODERNIZR
			var element = document.createElement('x'),
				documentElement = document.documentElement,
				getComputedStyle = window.getComputedStyle,
				supports;
			if(!('pointerEvents' in element.style)){
				return false;
			}
			element.style.pointerEvents = 'auto';
			element.style.pointerEvents = 'x';
			documentElement.appendChild(element);
			supports = getComputedStyle &&
				getComputedStyle(element, '').pointerEvents === 'auto';
			documentElement.removeChild(element);
			return !!supports;
		})();


		 // Older versions of Firefox can't move plugins around without it resetting,
		t.hasFirefoxPluginMovingProblem = false;

		// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)

		// iOS
		t.hasiOSFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');

		// W3C
		t.hasNativeFullscreen = (typeof v.requestFullscreen !== 'undefined');

		// webkit/firefox/IE11+
		t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
		t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
		t.hasMsNativeFullScreen = (typeof v.msRequestFullscreen !== 'undefined');

		t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen || t.hasMsNativeFullScreen);
		t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;

		// Enabled?
		if (t.hasMozNativeFullScreen) {
			t.nativeFullScreenEnabled = document.mozFullScreenEnabled;
		} else if (t.hasMsNativeFullScreen) {
			t.nativeFullScreenEnabled = document.msFullscreenEnabled;
		}

		if (t.isChrome) {
			t.hasiOSFullScreen = false;
		}

		if (t.hasTrueNativeFullScreen) {

			t.fullScreenEventName = '';
			if (t.hasWebkitNativeFullScreen) {
				t.fullScreenEventName = 'webkitfullscreenchange';

			} else if (t.hasMozNativeFullScreen) {
				t.fullScreenEventName = 'mozfullscreenchange';

			} else if (t.hasMsNativeFullScreen) {
				t.fullScreenEventName = 'MSFullscreenChange';
			}

			t.isFullScreen = function() {
				if (t.hasMozNativeFullScreen) {
					return d.mozFullScreen;

				} else if (t.hasWebkitNativeFullScreen) {
					return d.webkitIsFullScreen;

				} else if (t.hasMsNativeFullScreen) {
					return d.msFullscreenElement !== null;
				}
			}

			t.requestFullScreen = function(el) {

				if (t.hasWebkitNativeFullScreen) {
					el.webkitRequestFullScreen();

				} else if (t.hasMozNativeFullScreen) {
					el.mozRequestFullScreen();

				} else if (t.hasMsNativeFullScreen) {
					el.msRequestFullscreen();

				}
			}

			t.cancelFullScreen = function() {
				if (t.hasWebkitNativeFullScreen) {
					document.webkitCancelFullScreen();

				} else if (t.hasMozNativeFullScreen) {
					document.mozCancelFullScreen();

				} else if (t.hasMsNativeFullScreen) {
					document.msExitFullscreen();

				}
			}

		}


		// OS X 10.5 can't do this even if it says it can :(
		if (t.hasiOSFullScreen && ua.match(/mac os x 10_5/i)) {
			t.hasNativeFullScreen = false;
			t.hasiOSFullScreen = false;
		}

	}
};
mejs.MediaFeatures.init();

/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
	pluginType: 'native',
	isFullScreen: false,

	setCurrentTime: function (time) {
		this.currentTime = time;
	},

	setMuted: function (muted) {
		this.muted = muted;
	},

	setVolume: function (volume) {
		this.volume = volume;
	},

	// for parity with the plugin versions
	stop: function () {
		this.pause();
	},

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		
		// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
		var 
			existingSources = this.getElementsByTagName('source');
		while (existingSources.length > 0){
			this.removeChild(existingSources[0]);
		}
	
		if (typeof url == 'string') {
			this.src = url;
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.src = media.src;
					break;
				}
			}
		}
	},

	setVideoSize: function (width, height) {
		this.width = width;
		this.height = height;
	}
};

/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
	this.id = pluginid;
	this.pluginType = pluginType;
	this.src = mediaUrl;
	this.events = {};
	this.attributes = {};
};

// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {

	// special
	pluginElement: null,
	pluginType: '',
	isFullScreen: false,

	// not implemented :(
	playbackRate: -1,
	defaultPlaybackRate: -1,
	seekable: [],
	played: [],

	// HTML5 read-only properties
	paused: true,
	ended: false,
	seeking: false,
	duration: 0,
	error: null,
	tagName: '',

	// HTML5 get/set properties, but only set (updated by event handlers)
	muted: false,
	volume: 1,
	currentTime: 0,

	// HTML5 methods
	play: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.playVideo();
			} else {
				this.pluginApi.playMedia();
			}
			this.paused = false;
		}
	},
	load: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
			} else {
				this.pluginApi.loadMedia();
			}
			
			this.paused = false;
		}
	},
	pause: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
		        if( this.pluginApi.getPlayerState() == 1 ) {
				    this.pluginApi.pauseVideo();
                }
			} else {
				this.pluginApi.pauseMedia();
			}			
			
			
			this.paused = true;
		}
	},
	stop: function () {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.stopVideo();
			} else {
				this.pluginApi.stopMedia();
			}	
			this.paused = true;
		}
	},
	canPlayType: function(type) {
		var i,
			j,
			pluginInfo,
			pluginVersions = mejs.plugins[this.pluginType];

		for (i=0; i<pluginVersions.length; i++) {
			pluginInfo = pluginVersions[i];

			// test if user has the correct plugin version
			if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {

				// test for plugin playback types
				for (j=0; j<pluginInfo.types.length; j++) {
					// find plugin that can play the type
					if (type == pluginInfo.types[j]) {
						return 'probably';
					}
				}
			}
		}

		return '';
	},
	
	positionFullscreenButton: function(x,y,visibleAndAbove) {
		if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
			this.pluginApi.positionFullscreenButton(Math.floor(x),Math.floor(y),visibleAndAbove);
		}
	},
	
	hideFullscreenButton: function() {
		if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
			this.pluginApi.hideFullscreenButton();
		}		
	},	
	

	// custom methods since not all JavaScript implementations support get/set

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
			this.src = mejs.Utility.absolutizeUrl(url);
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
					this.src = mejs.Utility.absolutizeUrl(media.src);
					break;
				}
			}
		}

	},
	setCurrentTime: function (time) {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube' || this.pluginType == 'vimeo') {
				this.pluginApi.seekTo(time);
			} else {
				this.pluginApi.setCurrentTime(time);
			}				
			
			
			
			this.currentTime = time;
		}
	},
	setVolume: function (volume) {
		if (this.pluginApi != null) {
			// same on YouTube and MEjs
			if (this.pluginType == 'youtube') {
				this.pluginApi.setVolume(volume * 100);
			} else {
				this.pluginApi.setVolume(volume);
			}
			this.volume = volume;
		}
	},
	setMuted: function (muted) {
		if (this.pluginApi != null) {
			if (this.pluginType == 'youtube') {
				if (muted) {
					this.pluginApi.mute();
				} else {
					this.pluginApi.unMute();
				}
				this.muted = muted;
				this.dispatchEvent({type:'volumechange'});
			} else {
				this.pluginApi.setMuted(muted);
			}
			this.muted = muted;
		}
	},

	// additional non-HTML5 methods
	setVideoSize: function (width, height) {
		
		//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
			if (this.pluginElement && this.pluginElement.style) {
				this.pluginElement.style.width = width + 'px';
				this.pluginElement.style.height = height + 'px';
			}
			if (this.pluginApi != null && this.pluginApi.setVideoSize) {
				this.pluginApi.setVideoSize(width, height);
			}
		//}
	},

	setFullscreen: function (fullscreen) {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.pluginApi.setFullscreen(fullscreen);
		}
	},
	
	enterFullScreen: function() {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.setFullscreen(true);
		}		
		
	},
	
	exitFullScreen: function() {
		if (this.pluginApi != null && this.pluginApi.setFullscreen) {
			this.setFullscreen(false);
		}
	},	

	// start: fake events
	addEventListener: function (eventName, callback, bubble) {
		this.events[eventName] = this.events[eventName] || [];
		this.events[eventName].push(callback);
	},
	removeEventListener: function (eventName, callback) {
		if (!eventName) { this.events = {}; return true; }
		var callbacks = this.events[eventName];
		if (!callbacks) return true;
		if (!callback) { this.events[eventName] = []; return true; }
		for (var i = 0; i < callbacks.length; i++) {
			if (callbacks[i] === callback) {
				this.events[eventName].splice(i, 1);
				return true;
			}
		}
		return false;
	},	
	dispatchEvent: function (event) {
		var i,
			args,
			callbacks = this.events[event.type];

		if (callbacks) {
			for (i = 0; i < callbacks.length; i++) {
				callbacks[i].apply(this, [event]);
			}
		}
	},
	// end: fake events
	
	// fake DOM attribute methods
	hasAttribute: function(name){
		return (name in this.attributes);  
	},
	removeAttribute: function(name){
		delete this.attributes[name];
	},
	getAttribute: function(name){
		if (this.hasAttribute(name)) {
			return this.attributes[name];
		}
		return null;
	},
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},

	remove: function() {
		mejs.Utility.removeSwf(this.pluginElement.id);
	}
};

/*
Default options
*/
mejs.MediaElementDefaults = {
	// allows testing on HTML5, flash, silverlight
	// auto: attempts to detect what the browser can do
	// auto_plugin: prefer plugins and then attempt native HTML5
	// native: forces HTML5 playback
	// shim: disallows HTML5, will attempt either Flash or Silverlight
	// none: forces fallback view
	mode: 'auto',
	// remove or reorder to change plugin priority and availability
	plugins: ['flash','silverlight','youtube','vimeo'],
	// shows debug errors on screen
	enablePluginDebug: false,
	// use plugin for browsers that have trouble with Basic Authentication on HTTPS sites
	httpsBasicAuthSite: false,
	// overrides the type specified, useful for dynamic instantiation
	type: '',
	// path to Flash and Silverlight plugins
	pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
	// name of flash file
	flashName: 'flashmediaelement.swf',
	// streamer for RTMP streaming
	flashStreamer: '',
	// set to 'always' for CDN version
	flashScriptAccess: 'sameDomain',	
	// turns on the smoothing filter in Flash
	enablePluginSmoothing: false,
	// enabled pseudo-streaming (seek) on .mp4 files
	enablePseudoStreaming: false,
	// start query parameter sent to server for pseudo-streaming
	pseudoStreamingStartQueryParam: 'start',
	// name of silverlight file
	silverlightName: 'silverlightmediaelement.xap',
	// default if the <video width> is not specified
	defaultVideoWidth: 480,
	// default if the <video height> is not specified
	defaultVideoHeight: 270,
	// overrides <video width>
	pluginWidth: -1,
	// overrides <video height>
	pluginHeight: -1,
	// additional plugin variables in 'key=value' form
	pluginVars: [],	
	// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
	// larger number is less accurate, but less strain on plugin->JavaScript bridge
	timerRate: 250,
	// initial volume for player
	startVolume: 0.8,
	// custom error message in case media cannot be played; otherwise, Download File
	// link will be displayed
	customError: "",
	success: function () { },
	error: function () { }
};

/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
	return mejs.HtmlMediaElementShim.create(el,o);
};

mejs.HtmlMediaElementShim = {

	create: function(el, o) {
		var
			options = {},
			htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
			tagName = htmlMediaElement.tagName.toLowerCase(),
			isMediaTag = (tagName === 'audio' || tagName === 'video'),
			src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
			poster = htmlMediaElement.getAttribute('poster'),
			autoplay =  htmlMediaElement.getAttribute('autoplay'),
			preload =  htmlMediaElement.getAttribute('preload'),
			controls =  htmlMediaElement.getAttribute('controls'),
			playback,
			prop;

		// extend options
		for (prop in mejs.MediaElementDefaults) {
			options[prop] = mejs.MediaElementDefaults[prop];
		}
		for (prop in o) {
			options[prop] = o[prop];
		}		
		

		// clean up attributes
		src = 		(typeof src == 'undefined' 	|| src === null || src == '') ? null : src;		
		poster =	(typeof poster == 'undefined' 	|| poster === null) ? '' : poster;
		preload = 	(typeof preload == 'undefined' 	|| preload === null || preload === 'false') ? 'none' : preload;
		autoplay = 	!(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
		controls = 	!(typeof controls == 'undefined' || controls === null || controls === 'false');

		// test for HTML5 and plugin capabilities
		playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
		playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
        	playback.scheme = mejs.Utility.determineScheme(playback.url);

		if (playback.method == 'native') {
			// second fix for android
			if (mejs.MediaFeatures.isBustedAndroid) {
				htmlMediaElement.src = playback.url;
				htmlMediaElement.addEventListener('click', function() {
					htmlMediaElement.play();
				}, false);
			}
		
			// add methods to native HTMLMediaElement
			return this.updateNative(playback, options, autoplay, preload);
		} else if (playback.method !== '') {
			// create plugin to mimic HTMLMediaElement
			
			return this.createPlugin( playback,  options, poster, autoplay, preload, controls);
		} else {
			// boo, no HTML5, no Flash, no Silverlight.
			this.createErrorMessage( playback, options, poster );
			
			return this;
		}
	},
	
	determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
		var
			mediaFiles = [],
			i,
			j,
			k,
			l,
			n,
			type,
			result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() !== 'audio'), scheme: ''},
			pluginName,
			pluginVersions,
			pluginInfo,
			dummy,
			media;
			
		// STEP 1: Get URL and type from <video src> or <source src>

		// supplied type overrides <video type> and <source type>
		if (typeof options.type != 'undefined' && options.type !== '') {
			
			// accept either string or array of types
			if (typeof options.type == 'string') {
				mediaFiles.push({type:options.type, url:src});
			} else {
				
				for (i=0; i<options.type.length; i++) {
					mediaFiles.push({type:options.type[i], url:src});
				}
			}

		// test for src attribute first
		} else if (src !== null) {
			type = this.formatType(src, htmlMediaElement.getAttribute('type'));
			mediaFiles.push({type:type, url:src});

		// then test for <source> elements
		} else {
			// test <source> types to see if they are usable
			for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
				n = htmlMediaElement.childNodes[i];
				if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
					src = n.getAttribute('src');
					type = this.formatType(src, n.getAttribute('type'));
					media = n.getAttribute('media');

					if (!media || !window.matchMedia || (window.matchMedia && window.matchMedia(media).matches)) {
						mediaFiles.push({type:type, url:src});
					}
				}
			}
		}
		
		// in the case of dynamicly created players
		// check for audio types
		if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
			result.isVideo = false;
		}
		

		// STEP 2: Test for playback method
		
		// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
		if (result.isVideo && mejs.MediaFeatures.isBustedAndroid) {
			htmlMediaElement.canPlayType = function(type) {
				return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
			};
		}		
		
		// special case for Chromium to specify natively supported video codecs (i.e. WebM and Theora) 
		if (result.isVideo && mejs.MediaFeatures.isChromium) {
			htmlMediaElement.canPlayType = function(type) { 
				return (type.match(/video\/(webm|ogv|ogg)/gi) !== null) ? 'maybe' : '';
			}; 
		}

		// test for native playback first
		if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')  && !(mejs.MediaFeatures.isBustedNativeHTTPS && options.httpsBasicAuthSite === true)) {
						
			if (!isMediaTag) {

				// create a real HTML5 Media Element 
				dummy = document.createElement( result.isVideo ? 'video' : 'audio');			
				htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
				htmlMediaElement.style.display = 'none';
				
				// use this one from now on
				result.htmlMediaElement = htmlMediaElement = dummy;
			}
				
			for (i=0; i<mediaFiles.length; i++) {
				// normal check
				if (mediaFiles[i].type == "video/m3u8" || htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
					// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
					|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== ''
					// special case for m4a supported by detecting mp4 support
					|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/m4a/,'mp4')).replace(/no/, '') !== '') {
					result.method = 'native';
					result.url = mediaFiles[i].url;
					break;
				}
			}			
			
			if (result.method === 'native') {
				if (result.url !== null) {
					htmlMediaElement.src = result.url;
				}
			
				// if `auto_plugin` mode, then cache the native result but try plugins.
				if (options.mode !== 'auto_plugin') {
					return result;
				}
			}
		}

		// if native playback didn't work, then test plugins
		if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
			for (i=0; i<mediaFiles.length; i++) {
				type = mediaFiles[i].type;

				// test all plugins in order of preference [silverlight, flash]
				for (j=0; j<options.plugins.length; j++) {

					pluginName = options.plugins[j];
			
					// test version of plugin (for future features)
					pluginVersions = mejs.plugins[pluginName];				
					
					for (k=0; k<pluginVersions.length; k++) {
						pluginInfo = pluginVersions[k];
					
						// test if user has the correct plugin version
						
						// for youtube/vimeo
						if (pluginInfo.version == null || 
							
							mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {

							// test for plugin playback types
							for (l=0; l<pluginInfo.types.length; l++) {
								// find plugin that can play the type
								if (type.toLowerCase() == pluginInfo.types[l].toLowerCase()) {
									result.method = pluginName;
									result.url = mediaFiles[i].url;
									return result;
								}
							}
						}
					}
				}
			}
		}
		
		// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
		// if we have native support then return that.
		if (options.mode === 'auto_plugin' && result.method === 'native') {
			return result;
		}

		// what if there's nothing to play? just grab the first available
		if (result.method === '' && mediaFiles.length > 0) {
			result.url = mediaFiles[0].url;
		}

		return result;
	},

	formatType: function(url, type) {
		// if no type is supplied, fake it with the extension
		if (url && !type) {		
			return this.getTypeFromFile(url);
		} else {
			// only return the mime part of the type in case the attribute contains the codec
			// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
			// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
			
			if (type && ~type.indexOf(';')) {
				return type.substr(0, type.indexOf(';')); 
			} else {
				return type;
			}
		}
	},
	
	getTypeFromFile: function(url) {
		url = url.split('?')[0];
		var
			ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase(),
			av = /(mp4|m4v|ogg|ogv|m3u8|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video/' : 'audio/';
		return this.getTypeFromExtension(ext, av);
	},
	
	getTypeFromExtension: function(ext, av) {
		av = av || '';
		
		switch (ext) {
			case 'mp4':
			case 'm4v':
			case 'm4a':
			case 'f4v':
			case 'f4a':
				return av + 'mp4';
			case 'flv':
				return av + 'x-flv';
			case 'webm':
			case 'webma':
			case 'webmv':	
				return av + 'webm';
			case 'ogg':
			case 'oga':
			case 'ogv':	
				return av + 'ogg';
			case 'm3u8':
				return 'application/x-mpegurl';
			case 'ts':
				return av + 'mp2t';
			default:
				return av + ext;
		}
	},

	createErrorMessage: function(playback, options, poster) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			errorContainer = document.createElement('div'),
			errorContent = options.customError;
			
		errorContainer.className = 'me-cannotplay';

		try {
			errorContainer.style.width = htmlMediaElement.width + 'px';
			errorContainer.style.height = htmlMediaElement.height + 'px';
		} catch (e) {}

		if (!errorContent) {
			errorContent = '<a href="' + playback.url + '">';

			if (poster !== '') {
				errorContent += '<img src="' + poster + '" width="100%" height="100%" alt="" />';
			}

			errorContent += '<span>' + mejs.i18n.t('mejs.download-file') + '</span></a>';
		}

		errorContainer.innerHTML = errorContent;

		htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
		htmlMediaElement.style.display = 'none';

		options.error(htmlMediaElement);
	},

	createPlugin:function(playback, options, poster, autoplay, preload, controls) {
		var 
			htmlMediaElement = playback.htmlMediaElement,
			width = 1,
			height = 1,
			pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
			pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
			container = document.createElement('div'),
			specialIEContainer,
			node,
			initVars;

		// copy tagName from html media element
		pluginMediaElement.tagName = htmlMediaElement.tagName;

		// copy attributes from html media element to plugin media element
		for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
			var attribute = htmlMediaElement.attributes[i];
			if (attribute.specified) {
				pluginMediaElement.setAttribute(attribute.name, attribute.value);
			}
		}

		// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
		node = htmlMediaElement.parentNode;

		while (node !== null && node.tagName != null && node.tagName.toLowerCase() !== 'body' && 
				node.parentNode != null && node.parentNode.tagName != null && node.parentNode.constructor != null && node.parentNode.constructor.name === "ShadowRoot") {
			if (node.parentNode.tagName.toLowerCase() === 'p') {
				node.parentNode.parentNode.insertBefore(node, node.parentNode);
				break;
			}
			node = node.parentNode;
		}

		if (playback.isVideo) {
			width = (options.pluginWidth > 0) ? options.pluginWidth : (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
			height = (options.pluginHeight > 0) ? options.pluginHeight : (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
		
			// in case of '%' make sure it's encoded
			width = mejs.Utility.encodeUrl(width);
			height = mejs.Utility.encodeUrl(height);
		
		} else {
			if (options.enablePluginDebug) {
				width = 320;
				height = 240;
			}
		}

		// register plugin
		pluginMediaElement.success = options.success;
		
		// add container (must be added to DOM before inserting HTML for IE)
		container.className = 'me-plugin';
		container.id = pluginid + '_container';
		
		if (playback.isVideo) {
				htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
		} else {
				document.body.insertBefore(container, document.body.childNodes[0]);
		}
		
		if (playback.method === 'flash' || playback.method === 'silverlight') {

			var canPlayVideo = htmlMediaElement.getAttribute('type') === 'audio/mp4',
				childrenSources = htmlMediaElement.getElementsByTagName('source');

			if (childrenSources && !canPlayVideo) {
				for (var i = 0, total = childrenSources.length; i < total; i++) {
					if (childrenSources[i].getAttribute('type') === 'audio/mp4') {
						canPlayVideo = true;
					}
				}
			}

			// flash/silverlight vars
			initVars = [
				'id=' + pluginid,
				'isvideo=' + ((playback.isVideo || canPlayVideo) ? "true" : "false"),
				'autoplay=' + ((autoplay) ? "true" : "false"),
				'preload=' + preload,
				'width=' + width,
				'startvolume=' + options.startVolume,
				'timerrate=' + options.timerRate,
				'flashstreamer=' + options.flashStreamer,
				'height=' + height,
				'pseudostreamstart=' + options.pseudoStreamingStartQueryParam];
	
			if (playback.url !== null) {
				if (playback.method == 'flash') {
					initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
				} else {
					initVars.push('file=' + playback.url);
				}
			}
			if (options.enablePluginDebug) {
				initVars.push('debug=true');
			}
			if (options.enablePluginSmoothing) {
				initVars.push('smoothing=true');
			}
			if (options.enablePseudoStreaming) {
				initVars.push('pseudostreaming=true');
			}
			if (controls) {
				initVars.push('controls=true'); // shows controls in the plugin if desired
			}
			if (options.pluginVars) {
				initVars = initVars.concat(options.pluginVars);
			}		
			
			// call from plugin
			window[pluginid + '_init'] = function() {
				switch (pluginMediaElement.pluginType) {
					case 'flash':
						pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(pluginid);
						break;
					case 'silverlight':
						pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
						pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
						break;
				}
	
				if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
					pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
				}
			};
			
			// event call from plugin
			window[pluginid + '_event'] = function(eventName, values) {
		
				var
					e,
					i,
					bufferedTime;
		        
				// fake event object to mimic real HTML media event.
				e = {
					type: eventName,
					target: pluginMediaElement
				};
		
				// attach all values to element and event object
				for (i in values) {
					pluginMediaElement[i] = values[i];
					e[i] = values[i];
				}
		
				// fake the newer W3C buffered TimeRange (loaded and total have been removed)
				bufferedTime = values.bufferedTime || 0;
		
				e.target.buffered = e.buffered = {
					start: function(index) {
						return 0;
					},
					end: function (index) {
						return bufferedTime;
					},
					length: 1
				};
		
				pluginMediaElement.dispatchEvent(e);
			}			
			
			
		}

		switch (playback.method) {
			case 'silverlight':
				container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
					break;

			case 'flash':

				if (mejs.MediaFeatures.isIE) {
					specialIEContainer = document.createElement('div');
					container.appendChild(specialIEContainer);
					specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '" class="mejs-shim">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?' + (new Date().getTime()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&amp;') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '" />' +
'<param name="allowFullScreen" value="true" />' +
'<param name="scale" value="default" />' + 
'</object>';

				} else {

					container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="' + options.flashScriptAccess + '" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'scale="default"' + 
'class="mejs-shim"></embed>';
				}
				break;
			
			case 'youtube':
			
				
				var videoId;
				// youtu.be url from share button
				if (playback.url.lastIndexOf("youtu.be") != -1) {
					videoId = playback.url.substr(playback.url.lastIndexOf('/')+1);
					if (videoId.indexOf('?') != -1) {
						videoId = videoId.substr(0, videoId.indexOf('?'));
					}
				}
				else {
					// https://www.youtube.com/watch?v=
					var videoIdMatch = playback.url.match( /[?&]v=([^&#]+)|&|#|$/ );
					if ( videoIdMatch ) {
						videoId = videoIdMatch[1];
					}
				}
				youtubeSettings = {
						container: container,
						containerId: container.id,
						pluginMediaElement: pluginMediaElement,
						pluginId: pluginid,
						videoId: videoId,
						height: height,
						width: width,
                        scheme: playback.scheme,
						variables: options.youtubeIframeVars
					};				
				
				// favor iframe version of YouTube
				if (window.postMessage) {
					mejs.YouTubeApi.enqueueIframe(youtubeSettings);		
				} else if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
					mejs.YouTubeApi.createFlash(youtubeSettings, options);
				}
				break;
			
			// DEMO Code. Does NOT work.
			case 'vimeo':
				var player_id = pluginid + "_player";
				pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
				
				container.innerHTML ='<iframe src="' + playback.scheme + 'player.vimeo.com/video/' + pluginMediaElement.vimeoid + '?api=1&portrait=0&byline=0&title=0&player_id=' + player_id + '" width="' + width +'" height="' + height +'" frameborder="0" class="mejs-shim" id="' + player_id + '" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
				if (typeof($f) == 'function') { // froogaloop available
					var player = $f(container.childNodes[0]),
						playerState = -1;
					
					player.addEvent('ready', function() {
		
						player.playVideo = function() {
							player.api( 'play' );
						};
						player.stopVideo = function() {
							player.api( 'unload' );
						};
						player.pauseVideo = function() {
							player.api( 'pause' );
						};
						player.seekTo = function( seconds ) {
							player.api( 'seekTo', seconds );
						};
						player.setVolume = function( volume ) {
							player.api( 'setVolume', volume );
						};
						player.setMuted = function( muted ) {
							if( muted ) {
								player.lastVolume = player.api( 'getVolume' );
								player.api( 'setVolume', 0 );
							} else {
								player.api( 'setVolume', player.lastVolume );
								delete player.lastVolume;
							}
						};
						// parity with YT player
						player.getPlayerState = function() {
							return playerState;
						};

						function createEvent(player, pluginMediaElement, eventName, e) {
							var event = {
								type: eventName,
								target: pluginMediaElement
							};
							if (eventName == 'timeupdate') {
								pluginMediaElement.currentTime = event.currentTime = e.seconds;
								pluginMediaElement.duration = event.duration = e.duration;
							}
							pluginMediaElement.dispatchEvent(event);
						}

						player.addEvent('play', function() {
							playerState = 1;
							createEvent(player, pluginMediaElement, 'play');
							createEvent(player, pluginMediaElement, 'playing');
						});

						player.addEvent('pause', function() {
							playerState = 2;							
							createEvent(player, pluginMediaElement, 'pause');
						});

						player.addEvent('finish', function() {
							playerState = 0;							
							createEvent(player, pluginMediaElement, 'ended');
						});

						player.addEvent('playProgress', function(e) {
							createEvent(player, pluginMediaElement, 'timeupdate', e);
						});
						
						player.addEvent('seek', function(e) {
							playerState = 3;
							createEvent(player, pluginMediaElement, 'seeked', e);
						});	
						
						player.addEvent('loadProgress', function(e) {
							playerState = 3;
							createEvent(player, pluginMediaElement, 'progress', e);
						});												

						pluginMediaElement.pluginElement = container;
						pluginMediaElement.pluginApi = player;

						pluginMediaElement.success(pluginMediaElement, pluginMediaElement.pluginElement);						
					});
				}
				else {
					console.warn("You need to include froogaloop for vimeo to work");
				}
				break;			
		}
		// hide original element
		htmlMediaElement.style.display = 'none';
		// prevent browser from autoplaying when using a plugin
		htmlMediaElement.removeAttribute('autoplay');
		
		return pluginMediaElement;
	},

	updateNative: function(playback, options, autoplay, preload) {
		
		var htmlMediaElement = playback.htmlMediaElement,
			m;
		
		
		// add methods to video object to bring it into parity with Flash Object
		for (m in mejs.HtmlMediaElement) {
			htmlMediaElement[m] = mejs.HtmlMediaElement[m];
		}

		/*
		Chrome now supports preload="none"
		if (mejs.MediaFeatures.isChrome) {
		
			// special case to enforce preload attribute (Chrome doesn't respect this)
			if (preload === 'none' && !autoplay) {
			
				// forces the browser to stop loading (note: fails in IE9)
				htmlMediaElement.src = '';
				htmlMediaElement.load();
				htmlMediaElement.canceledPreload = true;

				htmlMediaElement.addEventListener('play',function() {
					if (htmlMediaElement.canceledPreload) {
						htmlMediaElement.src = playback.url;
						htmlMediaElement.load();
						htmlMediaElement.play();
						htmlMediaElement.canceledPreload = false;
					}
				}, false);
			// for some reason Chrome forgets how to autoplay sometimes.
			} else if (autoplay) {
				htmlMediaElement.load();
				htmlMediaElement.play();
			}
		}
		*/

		// fire success code
		options.success(htmlMediaElement, htmlMediaElement);
		
		return htmlMediaElement;
	}
};

/*
 - test on IE (object vs. embed)
 - determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
 - fullscreen?
*/

// YouTube Flash and Iframe API
mejs.YouTubeApi = {
	isIframeStarted: false,
	isIframeLoaded: false,
	loadIframeApi: function(yt) {
		if (!this.isIframeStarted) {
			var tag = document.createElement('script');
			tag.src = yt.scheme + "www.youtube.com/player_api";
			var firstScriptTag = document.getElementsByTagName('script')[0];
			firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			this.isIframeStarted = true;
		}
	},
	iframeQueue: [],
	enqueueIframe: function(yt) {
		
		if (this.isLoaded) {
			this.createIframe(yt);
		} else {
			this.loadIframeApi(yt);
			this.iframeQueue.push(yt);
		}
	},
	createIframe: function(settings) {

		var
		pluginMediaElement = settings.pluginMediaElement,
		defaultVars = {controls:0, wmode:'transparent'},
		player = new YT.Player(settings.containerId, {
			height: settings.height,
			width: settings.width,
			videoId: settings.videoId,
			playerVars: mejs.$.extend({}, defaultVars, settings.variables),
			events: {
				'onReady': function(e) {
					
					// wrapper to match
					player.setVideoSize = function(width, height) {
						player.setSize(width, height);
					};
					
					// hook up iframe object to MEjs
					settings.pluginMediaElement.pluginApi = player;
					settings.pluginMediaElement.pluginElement = document.getElementById(settings.containerId);
					
					// init mejs
					pluginMediaElement.success(pluginMediaElement, pluginMediaElement.pluginElement);

					mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
					
					// create timer
					setInterval(function() {
						mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
					}, 250);

					if (typeof pluginMediaElement.attributes.autoplay !== 'undefined') {
						player.playVideo();
					}
				},
				'onStateChange': function(e) {
					
					mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
					
				}
			}
		});
	},
	
	createEvent: function (player, pluginMediaElement, eventName) {
		var event = {
			type: eventName,
			target: pluginMediaElement
		};

		if (player && player.getDuration) {
			
			// time 
			pluginMediaElement.currentTime = event.currentTime = player.getCurrentTime();
			pluginMediaElement.duration = event.duration = player.getDuration();
			
			// state
			event.paused = pluginMediaElement.paused;
			event.ended = pluginMediaElement.ended;			
			
			// sound
			event.muted = player.isMuted();
			event.volume = player.getVolume() / 100;
			
			// progress
			event.bytesTotal = player.getVideoBytesTotal();
			event.bufferedBytes = player.getVideoBytesLoaded();
			
			// fake the W3C buffered TimeRange
			var bufferedTime = event.bufferedBytes / event.bytesTotal * event.duration;
			
			event.target.buffered = event.buffered = {
				start: function(index) {
					return 0;
				},
				end: function (index) {
					return bufferedTime;
				},
				length: 1
			};

		}
		
		// send event up the chain
		pluginMediaElement.dispatchEvent(event);
	},	
	
	iFrameReady: function() {
		
		this.isLoaded = true;
		this.isIframeLoaded = true;
		
		while (this.iframeQueue.length > 0) {
			var settings = this.iframeQueue.pop();
			this.createIframe(settings);
		}	
	},
	
	// FLASH!
	flashPlayers: {},
	createFlash: function(settings) {
		
		this.flashPlayers[settings.pluginId] = settings;
		
		/*
		settings.container.innerHTML =
			'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + settings.scheme + 'www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId  + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0" ' +
				'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
				'<param name="allowScriptAccess" value="sameDomain">' +
				'<param name="wmode" value="transparent">' +
			'</object>';
		*/

		var specialIEContainer,
			youtubeUrl = settings.scheme + 'www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId  + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0';
			
		if (mejs.MediaFeatures.isIE) {
			
			specialIEContainer = document.createElement('div');
			settings.container.appendChild(specialIEContainer);
			specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + settings.scheme + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '" class="mejs-shim">' +
	'<param name="movie" value="' + youtubeUrl + '" />' +
	'<param name="wmode" value="transparent" />' +
	'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '" />' +
	'<param name="allowFullScreen" value="true" />' +
'</object>';
		} else {
		settings.container.innerHTML =
			'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
				'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; " class="mejs-shim">' +
				'<param name="allowScriptAccess" value="' + options.flashScriptAccess + '">' +
				'<param name="wmode" value="transparent">' +
			'</object>';
		}		
		
	},
	
	flashReady: function(id) {
		var
			settings = this.flashPlayers[id],
			player = document.getElementById(id),
			pluginMediaElement = settings.pluginMediaElement;
		
		// hook up and return to MediaELementPlayer.success	
		pluginMediaElement.pluginApi = 
		pluginMediaElement.pluginElement = player;
		
		settings.success(pluginMediaElement, pluginMediaElement.pluginElement);
		
		// load the youtube video
		player.cueVideoById(settings.videoId);
		
		var callbackName = settings.containerId + '_callback';
		
		window[callbackName] = function(e) {
			mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
		};
		
		player.addEventListener('onStateChange', callbackName);
		
		setInterval(function() {
			mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
		}, 250);
		
		mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'canplay');
	},
	
	handleStateChange: function(youTubeState, player, pluginMediaElement) {
		switch (youTubeState) {
			case -1: // not started
				pluginMediaElement.paused = true;
				pluginMediaElement.ended = true;
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
				//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
				break;
			case 0:
				pluginMediaElement.paused = false;
				pluginMediaElement.ended = true;
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
				break;
			case 1:
				pluginMediaElement.paused = false;
				pluginMediaElement.ended = false;				
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
				break;
			case 2:
				pluginMediaElement.paused = true;
				pluginMediaElement.ended = false;				
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
				break;
			case 3: // buffering
				mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
				break;
			case 5:
				// cued?
				break;						
			
		}			
		
	}
}
// IFRAME
window.onYouTubePlayerAPIReady = function() {
	mejs.YouTubeApi.iFrameReady();
};
// FLASH
window.onYouTubePlayerReady = function(id) {
	mejs.YouTubeApi.flashReady(id);
};

window.mejs = mejs;
window.MediaElement = mejs.MediaElement;

/**
 * Localize strings
 *
 * Include translations from JS files and method to pluralize properly strings.
 *
 */
(function (doc, win, mejs, undefined) {

	var i18n = {
		/**
		 * @type {String}
		 */
		'default': 'en',

		/**
		 * @type {String[]}
		 */
		locale: {
			language: (mejs.i18n && mejs.i18n.locale.language) || '',
			strings: (mejs.i18n && mejs.i18n.locale.strings) || {}
		},

		/**
		 * Filters for available languages.
		 *
		 * This plural forms are grouped in family groups based on
		 * https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules
		 * with some additions and corrections according to the Localization Guide list
		 * (http://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html)
		 *
		 * Arguments are dynamic following the structure:
		 * - argument1 : Number to determine form
		 * - argument2...argumentN: Possible matches
		 *
		 * @type {Function[]}
		 */
		pluralForms: [
			// 0: Chinese, Japanese, Korean, Persian, Turkish, Thai, Lao, Aymará,
			// Tibetan, Chiga, Dzongkha, Indonesian, Lojban, Georgian, Kazakh, Khmer, Kyrgyz, Malay,
			// Burmese, Yakut, Sundanese, Tatar, Uyghur, Vietnamese, Wolof
			function () {
				return arguments[1];
			},
			// 1: Danish, Dutch, English, Faroese, Frisian, German, Norwegian, Swedish, Estonian, Finnish,
			// Hungarian, Basque, Greek, Hebrew, Italian, Portuguese, Spanish, Catalan, Afrikaans,
			// Angika, Assamese, Asturian, Azerbaijani, Bulgarian, Bengali, Bodo, Aragonese, Dogri,
			// Esperanto, Argentinean Spanish, Fulah, Friulian, Galician, Gujarati, Hausa,
			// Hindi, Chhattisgarhi, Armenian, Interlingua, Greenlandic, Kannada, Kurdish, Letzeburgesch,
			// Maithili, Malayalam, Mongolian, Manipuri, Marathi, Nahuatl, Neapolitan, Norwegian Bokmal,
			// Nepali, Norwegian Nynorsk, Norwegian (old code), Northern Sotho, Oriya, Punjabi, Papiamento,
			// Piemontese, Pashto, Romansh, Kinyarwanda, Santali, Scots, Sindhi, Northern Sami, Sinhala,
			// Somali, Songhay, Albanian, Swahili, Tamil, Telugu, Turkmen, Urdu, Yoruba
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 2: French, Brazilian Portuguese, Acholi, Akan, Amharic, Mapudungun, Breton, Filipino,
			// Gun, Lingala, Mauritian Creole, Malagasy, Maori, Occitan, Tajik, Tigrinya, Uzbek, Walloon
			function () {
				var args = arguments;
				if ([0, 1].indexOf(args[0]) > -1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 3: Latvian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] !== 0) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 4: Scottish Gaelic
			function () {
				var args = arguments;
				if (args[0] === 1 || args[0] === 11) {
					return args[1];
				} else if (args[0] === 2 || args[0] === 12) {
					return args[2];
				} else if (args[0] > 2 && args[0] < 20) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 5:  Romanian
			function () {
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 0 || (args[0] % 100 > 0 && args[0] % 100 < 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 6: Lithuanian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] % 10 >= 2 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return [3];
				}
			},
			// 7: Belarusian, Bosnian, Croatian, Serbian, Russian, Ukrainian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1 && args[0] % 100 !== 11) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 8:  Slovak, Czech
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] >= 2 && args[0] <= 4) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 9: Polish
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 10: Slovenian
			function () {
				var args = arguments;
				if (args[0] % 100 === 1) {
					return args[2];
				} else if (args[0] % 100 === 2) {
					return args[3];
				} else if (args[0] % 100 === 3 || args[0] % 100 === 4) {
					return args[4];
				} else {
					return args[1];
				}
			},
			// 11: Irish Gaelic
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] > 2 && args[0] < 7) {
					return args[3];
				} else if (args[0] > 6 && args[0] < 11) {
					return args[4];
				} else {
					return args[5];
				}
			},
			// 12: Arabic
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else if (args[0] === 1) {
					return args[2];
				} else if (args[0] === 2) {
					return args[3];
				} else if (args[0] % 100 >= 3 && args[0] % 100 <= 10) {
					return args[4];
				} else if (args[0] % 100 >= 11) {
					return args[5];
				} else {
					return args[6];
				}
			},
			// 13: Maltese
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 0 || (args[0] % 100 > 1 && args[0] % 100 < 11)) {
					return args[2];
				} else if (args[0] % 100 > 10 && args[0] % 100 < 20) {
					return args[3];
				} else {
					return args[4];
				}

			},
			// 14: Macedonian
			function () {
				var args = arguments;
				if (args[0] % 10 === 1) {
					return args[1];
				} else if (args[0] % 10 === 2) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 15:  Icelandic
			function () {
				var args = arguments;
				if (args[0] !== 11 && args[0] % 10 === 1) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// New additions

			// 16:  Kashubian
			// Note: in https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules
			// Breton is listed as #16 but in the Localization Guide it belongs to the group 2
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] % 10 >= 2 && args[0] % 10 <= 4 && (args[0] % 100 < 10 || args[0] % 100 >= 20)) {
					return args[2];
				} else {
					return args[3];
				}
			},
			// 17:  Welsh
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] !== 8 && args[0] !== 11) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 18:  Javanese
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else {
					return args[2];
				}
			},
			// 19:  Cornish
			function () {
				var args = arguments;
				if (args[0] === 1) {
					return args[1];
				} else if (args[0] === 2) {
					return args[2];
				} else if (args[0] === 3) {
					return args[3];
				} else {
					return args[4];
				}
			},
			// 20:  Mandinka
			function () {
				var args = arguments;
				if (args[0] === 0) {
					return args[1];
				} else if (args[0] === 1) {
					return args[2];
				} else {
					return args[3];
				}
			}
		],
		/**
		 * Get specified language
		 *
		 */
		getLanguage: function () {
			var language = i18n.locale.language || i18n['default'];
			return /^(x\-)?[a-z]{2,}(\-\w{2,})?(\-\w{2,})?$/.exec(language) ? language : i18n['default'];
		},

		/**
		 * Translate a string to a specified language, including optionally a number to pluralize translation
		 *
		 * @param {String} message
		 * @param {Number} pluralParam
		 * @return {String}
		 */
		t: function (message, pluralParam) {

			if (typeof message === 'string' && message.length) {

				var
					language = i18n.getLanguage(),
					str,
					pluralForm,
					/**
					 * Modify string using algorithm to detect plural forms.
					 *
					 * @private
					 * @see http://stackoverflow.com/questions/1353408/messageformat-in-javascript-parameters-in-localized-ui-strings
					 * @param {String|String[]} input   - String or array of strings to pick the plural form
					 * @param {Number} number           - Number to determine the proper plural form
					 * @param {Number} form             - Number of language family to apply plural form
					 * @return {String}
					 */
					plural = function (input, number, form) {

						if (typeof input !== 'object' || typeof number !== 'number' || typeof form !== 'number') {
							return input;
						}

						if (typeof input === 'string') {
							return input;
						}

						// Perform plural form or return original text
						return i18n.pluralForms[form].apply(null, [number].concat(input));
					},
					/**
					 *
					 * @param {String} input
					 * @return {String}
					 */
					escapeHTML = function (input) {
						var map = {
							'&': '&amp;',
							'<': '&lt;',
							'>': '&gt;',
							'"': '&quot;'
						};

						return input.replace(/[&<>"]/g, function(c) {
							return map[c];
						});
					}
				;

				// Fetch the localized version of the string
				if (i18n.locale.strings && i18n.locale.strings[language]) {
					str = i18n.locale.strings[language][message];
					if (typeof pluralParam === 'number') {
						pluralForm = i18n.locale.strings[language]['mejs.plural-form'];
						str = plural.apply(null, [str, pluralParam, pluralForm]);
					}
				}

				// Fallback to default language if requested uid is not translated
				if (!str && i18n.locale.strings && i18n.locale.strings[i18n['default']]) {
					str = i18n.locale.strings[i18n['default']][message];
					if (typeof pluralParam === 'number') {
						pluralForm = i18n.locale.strings[i18n['default']]['mejs.plural-form'];
						str = plural.apply(null, [str, pluralParam, pluralForm]);

					}
				}

				// As a last resort, use the requested uid, to mimic original behavior of i18n utils (in which uid was the english text)
				str = str || message;

				// Replace token
				if (typeof pluralParam === 'number') {
					str = str.replace('%1', pluralParam);
				}

				return escapeHTML(str);

			}

			return message;
		}

	};

	// i18n fixes for compatibility with WordPress
	if (typeof mejsL10n !== 'undefined') {
		i18n.locale.language = mejsL10n.language;
	}

	// Register variable
	mejs.i18n = i18n;


}(document, window, mejs));

// i18n fixes for compatibility with WordPress
;(function (mejs, undefined) {

	"use strict";

	if (typeof mejsL10n !== 'undefined') {
		mejs[mejsL10n.language] = mejsL10n.strings;
	}

}(mejs.i18n.locale.strings));
/*!
 * This is a i18n.locale language object.
 *
 * English; This can serve as a template for other languages to translate
 *
 * @author
 *   TBD
 *   Sascha Greuel (Twitter: @SoftCreatR)
 *
 * @see
 *   me-i18n.js
 *
 * @params
 *  - exports - CommonJS, window ..
 */
(function (exports) {
    "use strict";

    if (exports.en === undefined) {
        exports.en = {
            "mejs.plural-form": 1,

            // me-shim
            "mejs.download-file": "Download File",

            // mep-feature-contextmenu
            "mejs.fullscreen-off": "Turn off Fullscreen",
            "mejs.fullscreen-on": "Go Fullscreen",
            "mejs.download-video": "Download Video",

            // mep-feature-fullscreen
            "mejs.fullscreen": "Fullscreen",

            // mep-feature-jumpforward
            "mejs.time-jump-forward": ["Jump forward 1 second", "Jump forward %1 seconds"],

            // mep-feature-playpause
            "mejs.play": "Play",
            "mejs.pause": "Pause",

            // mep-feature-postroll
            "mejs.close": "Close",

            // mep-feature-progress
            "mejs.time-slider": "Time Slider",
            "mejs.time-help-text": "Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.",

            // mep-feature-skipback
            "mejs.time-skip-back": ["Skip back 1 second", "Skip back %1 seconds"],

            // mep-feature-tracks
            "mejs.captions-subtitles": "Captions/Subtitles",
            "mejs.none": "None",

            // mep-feature-volume
            "mejs.mute-toggle": "Mute Toggle",
            "mejs.volume-help-text": "Use Up/Down Arrow keys to increase or decrease volume.",
            "mejs.unmute": "Unmute",
            "mejs.mute": "Mute",
            "mejs.volume-slider": "Volume Slider",

            // mep-player
            "mejs.video-player": "Video Player",
            "mejs.audio-player": "Audio Player",

            // mep-feature-ads
            "mejs.ad-skip": "Skip ad",
            "mejs.ad-skip-info": ["Skip in 1 second", "Skip in %1 seconds"],

            // mep-feature-sourcechooser
            "mejs.source-chooser": "Source Chooser"
        };
    }
}(mejs.i18n.locale.strings));
/*!
 *
 * MediaElementPlayer
 * http://mediaelementjs.com/
 *
 * Creates a controller bar for HTML5 <video> add <audio> tags
 * using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
 *
 * Copyright 2010-2013, John Dyer (http://j.hn/)
 * License: MIT
 *
 */
if (typeof jQuery != 'undefined') {
	mejs.$ = jQuery;
} else if (typeof Zepto != 'undefined') {
	mejs.$ = Zepto;

	// define `outerWidth` method which has not been realized in Zepto
	Zepto.fn.outerWidth = function(includeMargin) {
		var width = $(this).width();
		if (includeMargin) {
			width += parseInt($(this).css('margin-right'), 10);
			width += parseInt($(this).css('margin-left'), 10);
		}
		return width
	}

} else if (typeof ender != 'undefined') {
	mejs.$ = ender;
}
(function ($) {

	// default player values
	mejs.MepDefaults = {
		// url to poster (to fix iOS 3.x)
		poster: '',
		// When the video is ended, we can show the poster.
		showPosterWhenEnded: false,
		// default if the <video width> is not specified
		defaultVideoWidth: 480,
		// default if the <video height> is not specified
		defaultVideoHeight: 270,
		// if set, overrides <video width>
		videoWidth: -1,
		// if set, overrides <video height>
		videoHeight: -1,
		// default if the user doesn't specify
		defaultAudioWidth: 400,
		// default if the user doesn't specify
		defaultAudioHeight: 30,
		// default amount to move back when back key is pressed
		defaultSeekBackwardInterval: function(media) {
			return (media.duration * 0.05);
		},
		// default amount to move forward when forward key is pressed
		defaultSeekForwardInterval: function(media) {
			return (media.duration * 0.05);
		},
		// set dimensions via JS instead of CSS
		setDimensions: true,
		// width of audio player
		audioWidth: -1,
		// height of audio player
		audioHeight: -1,
		// initial volume when the player starts (overrided by user cookie)
		startVolume: 0.8,
		// useful for <audio> player loops
		loop: false,
		// rewind to beginning when media ends
		autoRewind: true,
		// resize to media dimensions
		enableAutosize: true,
		/*
		 * Time format to use. Default: 'mm:ss'
		 * Supported units:
		 *   h: hour
		 *   m: minute
		 *   s: second
		 *   f: frame count
		 * When using 'hh', 'mm', 'ss' or 'ff' we always display 2 digits.
		 * If you use 'h', 'm', 's' or 'f' we display 1 digit if possible.
		 *
		 * Example to display 75 seconds:
		 * Format 'mm:ss': 01:15
		 * Format 'm:ss': 1:15
		 * Format 'm:s': 1:15
		 */
		timeFormat: '',
		// forces the hour marker (##:00:00)
		alwaysShowHours: false,
		// show framecount in timecode (##:00:00:00)
		showTimecodeFrameCount: false,
		// used when showTimecodeFrameCount is set to true
		framesPerSecond: 25,
		// automatically calculate the width of the progress bar based on the sizes of other elements
		autosizeProgress : true,
		// Hide controls when playing and mouse is not over the video
		alwaysShowControls: false,
		// Display the video control
		hideVideoControlsOnLoad: false,
		// Enable click video element to toggle play/pause
		clickToPlayPause: true,
		// Time in ms to hide controls
		controlsTimeoutDefault: 1500,
		// Time in ms to trigger the timer when mouse moves
		controlsTimeoutMouseEnter: 2500,
		// Time in ms to trigger the timer when mouse leaves
		controlsTimeoutMouseLeave: 1000,
		// force iPad's native controls
		iPadUseNativeControls: false,
		// force iPhone's native controls
		iPhoneUseNativeControls: false,
		// force Android's native controls
		AndroidUseNativeControls: false,
		// features to show
		features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
		// only for dynamic
		isVideo: true,
		// stretching modes (auto, fill, responsive, none)
		stretching: 'auto',
		// turns keyboard support on and off for this instance
		enableKeyboard: true,
		// when this player starts, it will pause other players
		pauseOtherPlayers: true,
		// array of keyboard actions such as play pause
		keyActions: [
				{
						keys: [
								32, // SPACE
								179 // GOOGLE play/pause button
								 ],
						action: function(player, media, key, event) {

							if (!mejs.MediaFeatures.isFirefox) {
								if (media.paused || media.ended) {
									media.play();
								} else {
									media.pause();
								}
							}
						}
				},
				{
						keys: [38], // UP
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}

								var newVolume = Math.min(media.volume + 0.1, 1);
								media.setVolume(newVolume);
						}
				},
				{
						keys: [40], // DOWN
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}

								var newVolume = Math.max(media.volume - 0.1, 0);
								media.setVolume(newVolume);
						}
				},
				{
						keys: [
								37, // LEFT
								227 // Google TV rewind
						],
						action: function(player, media, key, event) {
								if (!isNaN(media.duration) && media.duration > 0) {
										if (player.isVideo) {
												player.showControls();
												player.startControlsTimer();
										}

										// 5%
										var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
										media.setCurrentTime(newTime);
								}
						}
				},
				{
						keys: [
								39, // RIGHT
								228 // Google TV forward
						],
						action: function(player, media, key, event) {
								if (!isNaN(media.duration) && media.duration > 0) {
										if (player.isVideo) {
												player.showControls();
												player.startControlsTimer();
										}

										// 5%
										var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
										media.setCurrentTime(newTime);
								}
						}
				},
				{
						keys: [70], // F
						action: function(player, media, key, event) {
								if (typeof player.enterFullScreen != 'undefined') {
										if (player.isFullScreen) {
												player.exitFullScreen();
										} else {
												player.enterFullScreen();
										}
								}
						}
				},
				{
						keys: [77], // M
						action: function(player, media, key, event) {
								player.container.find('.mejs-volume-slider').css('display','block');
								if (player.isVideo) {
										player.showControls();
										player.startControlsTimer();
								}
								if (player.media.muted) {
										player.setMuted(false);
								} else {
										player.setMuted(true);
								}
						}
				}
		]
	};

	mejs.mepIndex = 0;

	mejs.players = {};

	// wraps a MediaElement object in player controls
	mejs.MediaElementPlayer = function(node, o) {
		// enforce object, even without "new" (via John Resig)
		if ( !(this instanceof mejs.MediaElementPlayer) ) {
			return new mejs.MediaElementPlayer(node, o);
		}

		var t = this;

		// these will be reset after the MediaElement.success fires
		t.$media = t.$node = $(node);
		t.node = t.media = t.$media[0];

		if(!t.node) {
			return;
		}

		// check for existing player
		if (typeof t.node.player != 'undefined') {
			return t.node.player;
		}


		// try to get options from data-mejsoptions
		if (typeof o == 'undefined') {
			o = t.$node.data('mejsoptions');
		}

		// extend default options
		t.options = $.extend({},mejs.MepDefaults,o);

		if (!t.options.timeFormat) {
			// Generate the time format according to options
			t.options.timeFormat = 'mm:ss';
			if (t.options.alwaysShowHours) {
				t.options.timeFormat = 'hh:mm:ss';
			}
			if (t.options.showTimecodeFrameCount) {
				t.options.timeFormat += ':ff';
			}
		}

		mejs.Utility.calculateTimeFormat(0, t.options, t.options.framesPerSecond || 25);

		// unique ID
		t.id = 'mep_' + mejs.mepIndex++;

		// add to player array (for focus events)
		mejs.players[t.id] = t;

		// start up
		t.init();

		return t;
	};

	// actual player
	mejs.MediaElementPlayer.prototype = {

		hasFocus: false,

		controlsAreVisible: true,

		init: function() {

			var
				t = this,
				mf = mejs.MediaFeatures,
				// options for MediaElement (shim)
				meOptions = $.extend(true, {}, t.options, {
					success: function(media, domNode) { t.meReady(media, domNode); },
					error: function(e) { t.handleError(e);}
				}),
				tagName = t.media.tagName.toLowerCase();

			t.isDynamic = (tagName !== 'audio' && tagName !== 'video');

			if (t.isDynamic) {
				// get video from src or href?
				t.isVideo = t.options.isVideo;
			} else {
				t.isVideo = (tagName !== 'audio' && t.options.isVideo);
			}

			// use native controls in iPad, iPhone, and Android
			if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {

				// add controls and stop
				t.$media.attr('controls', 'controls');

				// attempt to fix iOS 3 bug
				//t.$media.removeAttr('poster');
								// no Issue found on iOS3 -ttroxell

				// override Apple's autoplay override for iPads
				if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
					t.play();
				}

			} else if (mf.isAndroid && t.options.AndroidUseNativeControls) {

				// leave default player

			} else if (t.isVideo || (!t.isVideo && t.options.features.length)) {

				// DESKTOP: use MediaElementPlayer controls

				// remove native controls
				t.$media.removeAttr('controls');
				var videoPlayerTitle = t.isVideo ?
					mejs.i18n.t('mejs.video-player') : mejs.i18n.t('mejs.audio-player');
				// insert description for screen readers
				$('<span class="mejs-offscreen">' + videoPlayerTitle + '</span>').insertBefore(t.$media);
				// build container
				t.container =
					$('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svgAsImg ? 'svg' : 'no-svg') +
					  '" tabindex="0" role="application" aria-label="' + videoPlayerTitle + '">'+
						'<div class="mejs-inner">'+
							'<div class="mejs-mediaelement"></div>'+
							'<div class="mejs-layers"></div>'+
							'<div class="mejs-controls"></div>'+
							'<div class="mejs-clear"></div>'+
						'</div>' +
					'</div>')
					.addClass(t.$media[0].className)
					.insertBefore(t.$media)
					.focus(function ( e ) {
						if( !t.controlsAreVisible && !t.hasFocus && t.controlsEnabled) {
							t.showControls(true);
							// In versions older than IE11, the focus causes the playbar to be displayed
							// if user clicks on the Play/Pause button in the control bar once it attempts
							// to hide it
							if (!t.hasMsNativeFullScreen) {
								// If e.relatedTarget appears before container, send focus to play button,
								// else send focus to last control button.
								var btnSelector = '.mejs-playpause-button > button';

								if (mejs.Utility.isNodeAfter(e.relatedTarget, t.container[0])) {
									btnSelector = '.mejs-controls .mejs-button:last-child > button';
								}

								var button = t.container.find(btnSelector);
								button.focus();
							}
						}
					});

				// When no elements in controls, hide bar completely
				if (!t.options.features.length) {
					t.container.css('background', 'transparent').find('.mejs-controls').hide();
				}
 
				if (t.isVideo && t.options.stretching === 'fill' && !t.container.parent('mejs-fill-container').length) {
					// outer container
					t.outerContainer = t.$media.parent();
					t.container.wrap('<div class="mejs-fill-container"/>');
				}

				// add classes for user and content
				t.container.addClass(
					(mf.isAndroid ? 'mejs-android ' : '') +
					(mf.isiOS ? 'mejs-ios ' : '') +
					(mf.isiPad ? 'mejs-ipad ' : '') +
					(mf.isiPhone ? 'mejs-iphone ' : '') +
					(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
				);


				// move the <video/video> tag into the right spot
				t.container.find('.mejs-mediaelement').append(t.$media);

				// needs to be assigned here, after iOS remap
				t.node.player = t;

				// find parts
				t.controls = t.container.find('.mejs-controls');
				t.layers = t.container.find('.mejs-layers');

				// determine the size

				/* size priority:
					(1) videoWidth (forced),
					(2) style="width;height;"
					(3) width attribute,
					(4) defaultVideoWidth (for unspecified cases)
				*/

				var tagType = (t.isVideo ? 'video' : 'audio'),
					capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);



				if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
					t.width = t.options[tagType + 'Width'];
				} else if (t.media.style.width !== '' && t.media.style.width !== null) {
					t.width = t.media.style.width;
				} else if (t.media.getAttribute('width') !== null) {
					t.width = t.$media.attr('width');
				} else {
					t.width = t.options['default' + capsTagName + 'Width'];
				}

				if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
					t.height = t.options[tagType + 'Height'];
				} else if (t.media.style.height !== '' && t.media.style.height !== null) {
					t.height = t.media.style.height;
				} else if (t.$media[0].getAttribute('height') !== null) {
					t.height = t.$media.attr('height');
				} else {
					t.height = t.options['default' + capsTagName + 'Height'];
				}

				// set the size, while we wait for the plugins to load below
				t.setPlayerSize(t.width, t.height);

				// create MediaElementShim
				meOptions.pluginWidth = t.width;
				meOptions.pluginHeight = t.height;
			}
			// Hide media completely for audio that doesn't have any features
			else if (!t.isVideo && !t.options.features.length) {
				t.$media.hide();
			}

			// create MediaElement shim
			mejs.MediaElement(t.$media[0], meOptions);

			if (typeof(t.container) !== 'undefined' && t.options.features.length && t.controlsAreVisible) {
				// controls are shown when loaded
				t.container.trigger('controlsshown');
			}
		},

		showControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (t.controlsAreVisible)
				return;

			if (doAnimation) {
				t.controls
					.removeClass('mejs-offscreen')
					.stop(true, true).fadeIn(200, function() {
						t.controlsAreVisible = true;
						t.container.trigger('controlsshown');
					});

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.removeClass('mejs-offscreen')
					.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});

			} else {
				t.controls
					.removeClass('mejs-offscreen')
					.css('display','block');

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.removeClass('mejs-offscreen')
					.css('display','block');

				t.controlsAreVisible = true;
				t.container.trigger('controlsshown');
			}

			t.setControlsSize();

		},

		hideControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (!t.controlsAreVisible || t.options.alwaysShowControls || t.keyboardAction || t.media.paused || t.media.ended)
				return;

			if (doAnimation) {
				// fade out main controls
				t.controls.stop(true, true).fadeOut(200, function() {
					$(this)
						.addClass('mejs-offscreen')
						.css('display','block');

					t.controlsAreVisible = false;
					t.container.trigger('controlshidden');
				});

				// any additional controls people might add and want to hide
				t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
					$(this)
						.addClass('mejs-offscreen')
						.css('display','block');
				});
			} else {

				// hide main controls
				t.controls
					.addClass('mejs-offscreen')
					.css('display','block');

				// hide others
				t.container.find('.mejs-control')
					.addClass('mejs-offscreen')
					.css('display','block');

				t.controlsAreVisible = false;
				t.container.trigger('controlshidden');
			}
		},

		controlsTimer: null,

		startControlsTimer: function(timeout) {

			var t = this;

			timeout = typeof timeout != 'undefined' ? timeout : t.options.controlsTimeoutDefault;

			t.killControlsTimer('start');

			t.controlsTimer = setTimeout(function() {
				//
				t.hideControls();
				t.killControlsTimer('hide');
			}, timeout);
		},

		killControlsTimer: function(src) {

			var t = this;

			if (t.controlsTimer !== null) {
				clearTimeout(t.controlsTimer);
				delete t.controlsTimer;
				t.controlsTimer = null;
			}
		},

		controlsEnabled: true,

		disableControls: function() {
			var t= this;

			t.killControlsTimer();
			t.hideControls(false);
			this.controlsEnabled = false;
		},

		enableControls: function() {
			var t= this;

			t.showControls(false);

			t.controlsEnabled = true;
		},

		// Sets up all controls and events
		meReady: function(media, domNode) {
			
			var
				t = this,
				mf = mejs.MediaFeatures,
				autoplayAttr = domNode.getAttribute('autoplay'),
				autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
				featureIndex,
				feature;

			// make sure it can't create itself again if a plugin reloads
			if (t.created) {
				return;
			} else {
				t.created = true;
			}

			t.media = media;
			t.domNode = domNode;

			if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {

				// In the event that no features are specified for audio,
				// create only MediaElement instance rather than
				// doing all the work to create a full player
				if (!t.isVideo && !t.options.features.length) {

					// force autoplay for HTML5
					if (autoplay && media.pluginType == 'native') {
						t.play();
					}


					if (t.options.success) {

						if (typeof t.options.success == 'string') {
							window[t.options.success](t.media, t.domNode, t);
						} else {
							t.options.success(t.media, t.domNode, t);
						}
					}

					return;
				}

				// two built in features
				t.buildposter(t, t.controls, t.layers, t.media);
				t.buildkeyboard(t, t.controls, t.layers, t.media);
				t.buildoverlays(t, t.controls, t.layers, t.media);

				// grab for use by features
				t.findTracks();

				// add user-defined features/controls
				for (featureIndex in t.options.features) {
					feature = t.options.features[featureIndex];
					if (t['build' + feature]) {
						try {
							t['build' + feature](t, t.controls, t.layers, t.media);
						} catch (e) {
							// TODO: report control error
							//throw e;
							
							
						}
					}
				}

				t.container.trigger('controlsready');

				// reset all layers and controls
				t.setPlayerSize(t.width, t.height);
				t.setControlsSize();


				// controls fade
				if (t.isVideo) {

					if (mejs.MediaFeatures.hasTouch && !t.options.alwaysShowControls) {

						// for touch devices (iOS, Android)
						// show/hide without animation on touch

						t.$media.bind('touchstart', function() {

							// toggle controls
							if (t.controlsAreVisible) {
								t.hideControls(false);
							} else {
								if (t.controlsEnabled) {
									t.showControls(false);
								}
							}
						});

					} else {

						// create callback here since it needs access to current
						// MediaElement object
						t.clickToPlayPauseCallback = function() {
							//

							if (t.options.clickToPlayPause) {
								if (t.media.paused) {
									t.play();
								} else {
									t.pause();
								}

								var button = t.$media.closest('.mejs-container').find('.mejs-overlay-button'),
									pressed = button.attr('aria-pressed');
								button.attr('aria-pressed', !pressed);
							}
						};

						// click to play/pause
						t.media.addEventListener('click', t.clickToPlayPauseCallback, false);

						// show/hide controls
						t.container
							.bind('mouseenter', function () {
								if (t.controlsEnabled) {
									if (!t.options.alwaysShowControls ) {
										t.killControlsTimer('enter');
										t.showControls();
										t.startControlsTimer(t.options.controlsTimeoutMouseEnter);
									}
								}
							})
							.bind('mousemove', function() {
								if (t.controlsEnabled) {
									if (!t.controlsAreVisible) {
										t.showControls();
									}
									if (!t.options.alwaysShowControls) {
										t.startControlsTimer(t.options.controlsTimeoutMouseEnter);
									}
								}
							})
							.bind('mouseleave', function () {
								if (t.controlsEnabled) {
									if (!t.media.paused && !t.options.alwaysShowControls) {
										t.startControlsTimer(t.options.controlsTimeoutMouseLeave);
									}
								}
							});
					}

					if(t.options.hideVideoControlsOnLoad) {
						t.hideControls(false);
					}

					// check for autoplay
					if (autoplay && !t.options.alwaysShowControls) {
						t.hideControls();
					}

					// resizer
					if (t.options.enableAutosize) {
						t.media.addEventListener('loadedmetadata', function(e) {
							// if the <video height> was not set and the options.videoHeight was not set
							// then resize to the real dimensions
							if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
								t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
								t.setControlsSize();
								t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
							}
						}, false);
					}
				}

				// EVENTS

				// FOCUS: when a video starts playing, it takes focus from other players (possibly pausing them)
				t.media.addEventListener('play', function() {
					var playerIndex;

					// go through all other players
					for (playerIndex in mejs.players) {
						var p = mejs.players[playerIndex];
						if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
							p.pause();
						}
						p.hasFocus = false;
					}

					t.hasFocus = true;
				},false);


				// ended for all
				t.media.addEventListener('ended', function (e) {
					if(t.options.autoRewind) {
						try{
							t.media.setCurrentTime(0);
							// Fixing an Android stock browser bug, where "seeked" isn't fired correctly after ending the video and jumping to the beginning
							window.setTimeout(function(){
								$(t.container).find('.mejs-overlay-loading').parent().hide();
							}, 20);
						} catch (exp) {

						}
					}
					if (t.media.pluginType === 'youtube') {
						t.media.stop();
					} else {
						t.media.pause();
					}

					if (t.setProgressRail) {
						t.setProgressRail();
					}
					if (t.setCurrentRail) {
						t.setCurrentRail();
					}

					if (t.options.loop) {
						t.play();
					} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
						t.showControls();
					}
				}, false);

				// resize on the first play
				t.media.addEventListener('loadedmetadata', function() {

					mejs.Utility.calculateTimeFormat(t.duration, t.options, t.options.framesPerSecond || 25);

					if (t.updateDuration) {
						t.updateDuration();
					}
					if (t.updateCurrent) {
						t.updateCurrent();
					}

					if (!t.isFullScreen) {
						t.setPlayerSize(t.width, t.height);
						t.setControlsSize();
					}
				}, false);

				// Only change the time format when necessary
				var duration = null;
				t.media.addEventListener('timeupdate',function() {
					if (duration !== this.duration) {
						duration = this.duration;
						mejs.Utility.calculateTimeFormat(duration, t.options, t.options.framesPerSecond || 25);
						
						// make sure to fill in and resize the controls (e.g., 00:00 => 01:13:15
						if (t.updateDuration) {
							t.updateDuration();
						}
						if (t.updateCurrent) {
							t.updateCurrent();
						}
						t.setControlsSize();
						
					}
				}, false);

				t.container.focusout(function (e) {
					if( e.relatedTarget ) { //FF is working on supporting focusout https://bugzilla.mozilla.org/show_bug.cgi?id=687787
						var $target = $(e.relatedTarget);
						if (t.keyboardAction && $target.parents('.mejs-container').length === 0) {
							t.keyboardAction = false;
							if (t.isVideo && !t.options.alwaysShowControls) {
								t.hideControls(true);
							}

						}
					}
				});

				// webkit has trouble doing this without a delay
				setTimeout(function () {
					t.setPlayerSize(t.width, t.height);
					t.setControlsSize();
				}, 50);

				// adjust controls whenever window sizes (used to be in fullscreen only)
				t.globalBind('resize', function() {

					// don't resize for fullscreen mode
					if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
						t.setPlayerSize(t.width, t.height);
					}

					// always adjust controls
					t.setControlsSize();
				});

				// This is a work-around for a bug in the YouTube iFrame player, which means
				//	we can't use the play() API for the initial playback on iOS or Android;
				//	user has to start playback directly by tapping on the iFrame.
				if (t.media.pluginType == 'youtube' && ( mf.isiOS || mf.isAndroid ) ) {
					t.container.find('.mejs-overlay-play').hide();
					t.container.find('.mejs-poster').hide();
				}
			}

			// force autoplay for HTML5
			if (autoplay && media.pluginType == 'native') {
				t.play();
			}


			if (t.options.success) {

				if (typeof t.options.success == 'string') {
					window[t.options.success](t.media, t.domNode, t);
				} else {
					t.options.success(t.media, t.domNode, t);
				}
			}
		},

		handleError: function(e) {
			var t = this;

			if (t.controls) {
				t.controls.hide();
			}

			// Tell user that the file cannot be played
			if (t.options.error) {
				t.options.error(e);
			}
		},

		setPlayerSize: function(width,height) {
			var t = this;

			if( !t.options.setDimensions ) {
				return false;
			}

			if (typeof width != 'undefined') {
				t.width = width;
			}

			if (typeof height != 'undefined') {
				t.height = height;
			}
 
			// check stretching modes
			switch (t.options.stretching) {
				case 'fill':
					// The 'fill' effect only makes sense on video; for audio we will set the dimensions
					if (t.isVideo) {
						this.setFillMode();
					} else {
						this.setDimensions(t.width, t.height);
					}
					break;
				case 'responsive':
					this.setResponsiveMode();
					break;
				case 'none':
					this.setDimensions(t.width, t.height);
					break;
				// This is the 'auto' mode
				default:
					if (this.hasFluidMode() === true) {
						this.setResponsiveMode();
					} else {
						this.setDimensions(t.width, t.height);
					}
					break;
			}
		},
 
		hasFluidMode: function() {
			var t = this;
	 
			// detect 100% mode - use currentStyle for IE since css() doesn't return percentages
			return (t.height.toString().indexOf('%') > 0 || (t.$node.css('max-width') !== 'none' && t.$node.css('max-width') !== 't.width') || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%'));
		},
 
		setResponsiveMode: function() {
			var t = this;
		
			// do we have the native dimensions yet?
			var nativeWidth = (function() {
				if (t.isVideo) {
					if (t.media.videoWidth && t.media.videoWidth > 0) {
						return t.media.videoWidth;
					} else if (t.media.getAttribute('width') !== null) {
						return t.media.getAttribute('width');
					} else {
						return t.options.defaultVideoWidth;
					}
				} else {
					return t.options.defaultAudioWidth;
				}
			})();
		
			var nativeHeight = (function() {
				if (t.isVideo) {
					if (t.media.videoHeight && t.media.videoHeight > 0) {
						return t.media.videoHeight;
					} else if (t.media.getAttribute('height') !== null) {
						return t.media.getAttribute('height');
					} else {
						return t.options.defaultVideoHeight;
					}
				} else {
					return t.options.defaultAudioHeight;
				}
			})();
		
			var parentWidth = t.container.parent().closest(':visible').width(),
			parentHeight = t.container.parent().closest(':visible').height(),
			newHeight = t.isVideo || !t.options.autosizeProgress ? parseInt(parentWidth * nativeHeight/nativeWidth, 10) : nativeHeight;
			
			// When we use percent, the newHeight can't be calculated so we get the container height
			if (isNaN(newHeight) || ( parentHeight !== 0 && newHeight > parentHeight && parentHeight > nativeHeight)) {
				newHeight = parentHeight;
			}
		
			if (t.container.parent().length > 0 && t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
				parentWidth = $(window).width();
				newHeight = $(window).height();
			}
		
			if ( newHeight && parentWidth ) {
			
				// set outer container size
				t.container
					.width(parentWidth)
					.height(newHeight);
				
				// set native <video> or <audio> and shims
				t.$media.add(t.container.find('.mejs-shim'))
					.width('100%')
					.height('100%');
				
				// if shim is ready, send the size to the embeded plugin
				if (t.isVideo) {
					if (t.media.setVideoSize) {
						t.media.setVideoSize(parentWidth, newHeight);
					}
				}
		
				// set the layers
				t.layers.children('.mejs-layer')
					.width('100%')
					.height('100%');
			}
		},
 
		setFillMode: function() {
			var t = this,
				parent = t.outerContainer;
 
			if (!parent.width()) {
				parent.height(t.$media.width());
			}
 
			if (!parent.height()) {
				parent.height(t.$media.height());
			}
 
			var parentWidth = parent.width(),
				parentHeight = parent.height();
			
			t.setDimensions('100%', '100%');
			
			// This prevents an issue when displaying poster
			t.container.find('.mejs-poster img').css('display', 'block');
			
			targetElement = t.container.find('object, embed, iframe, video');
			
			// calculate new width and height
			var initHeight = t.height,
				initWidth = t.width,
				// scale to the target width
				scaleX1 = parentWidth,
				scaleY1 = (initHeight * parentWidth) / initWidth,
				// scale to the target height
				scaleX2 = (initWidth * parentHeight) / initHeight,
				scaleY2 = parentHeight,
				// now figure out which one we should use
				bScaleOnWidth = !(scaleX2 > parentWidth),
				finalWidth = bScaleOnWidth ? Math.floor(scaleX1) : Math.floor(scaleX2),
				finalHeight = bScaleOnWidth ? Math.floor(scaleY1) : Math.floor(scaleY2);
			
			if (bScaleOnWidth) {
				targetElement.height(finalHeight).width(parentWidth);
				if (t.media.setVideoSize) {
					t.media.setVideoSize(parentWidth, finalHeight);
				}
			} else {
				targetElement.height(parentHeight).width(finalWidth);
				if (t.media.setVideoSize) {
					t.media.setVideoSize(finalWidth, parentHeight);
				}
			}
			
			targetElement.css({
				'margin-left': Math.floor((parentWidth - finalWidth) / 2),
				'margin-top': 0
			});
		},
	 
		setDimensions: function(width, height) {
			var t = this;
			
			t.container
				.width(width)
				.height(height);
			
			t.layers.children('.mejs-layer')
				.width(width)
				.height(height);
		},

		setControlsSize: function() {
			var t = this,
				usedWidth = 0,
				railWidth = 0,
				rail = t.controls.find('.mejs-time-rail'),
				total = t.controls.find('.mejs-time-total'),
				others = rail.siblings(),
				lastControl = others.last(),
				lastControlPosition = null,
				avoidAutosizeProgress = t.options && !t.options.autosizeProgress;

			// skip calculation if hidden
			if (!t.container.is(':visible') || !rail.length || !rail.is(':visible')) {
				return;
			}

			// allow the size to come from custom CSS
			if (avoidAutosizeProgress) {
				// Also, frontends devs can be more flexible
				// due the opportunity of absolute positioning.
				railWidth = parseInt(rail.css('width'), 10);
			}

			// attempt to autosize
			if (railWidth === 0 || !railWidth) {

				// find the size of all the other controls besides the rail
				others.each(function() {
					var $this = $(this);
					if ($this.css('position') != 'absolute' && $this.is(':visible')) {
						usedWidth += $(this).outerWidth(true);
					}
				});

				// fit the rail into the remaining space
				railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
			}

			// resize the rail,
			// but then check if the last control (say, the fullscreen button) got pushed down
			// this often happens when zoomed
			do {
				// outer area
				// we only want to set an inline style with the width of the rail
				// if we're trying to autosize.
				if (!avoidAutosizeProgress) {
					rail.width(railWidth);
				}

				// dark space
				total.width(railWidth - (total.outerWidth(true) - total.width()));

				if (lastControl.css('position') != 'absolute') {
					lastControlPosition = lastControl.length ? lastControl.position() : null;
					railWidth--;
				}
			} while (lastControlPosition !== null && lastControlPosition.top.toFixed(2) > 0 && railWidth > 0);

			t.container.trigger('controlsresize');
		},


		buildposter: function(player, controls, layers, media) {
			var t = this,
				poster =
				$('<div class="mejs-poster mejs-layer">' +
				'</div>')
					.appendTo(layers),
				posterUrl = player.$media.attr('poster');

			// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
			if (player.options.poster !== '') {
				posterUrl = player.options.poster;
			}

			// second, try the real poster
			if ( posterUrl ) {
				t.setPoster(posterUrl);
			} else {
				poster.hide();
			}

			media.addEventListener('play',function() {
				poster.hide();
			}, false);

			if(player.options.showPosterWhenEnded && player.options.autoRewind){
				media.addEventListener('ended',function() {
					poster.show();
				}, false);
			}
		},

		setPoster: function(url) {
			var t = this,
				posterDiv = t.container.find('.mejs-poster'),
				posterImg = posterDiv.find('img');

			if (posterImg.length === 0) {
				posterImg = $('<img width="100%" height="100%" alt="" />').appendTo(posterDiv);
			}

			posterImg.attr('src', url);
			posterDiv.css({'background-image' : 'url(' + url + ')'});
		},

		buildoverlays: function(player, controls, layers, media) {
			var t = this;
			if (!player.isVideo)
				return;

			var
			loading =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-loading"><span></span></div>'+
				'</div>')
				.hide() // start out hidden
				.appendTo(layers),
			error =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-error"></div>'+
				'</div>')
				.hide() // start out hidden
				.appendTo(layers),
			// this needs to come last so it's on top
			bigPlay =
				$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
					'<div class="mejs-overlay-button" role="button" aria-label="' + mejs.i18n.t('mejs.play') + '" aria-pressed="false"></div>'+
				'</div>')
				.appendTo(layers)
				.bind('click', function() {	 // Removed 'touchstart' due issues on Samsung Android devices where a tap on bigPlay started and immediately stopped the video
					if (t.options.clickToPlayPause) {
						if (media.paused) {
							media.play();
						}

						var button = $(this).find('.mejs-overlay-button'),
							pressed = button.attr('aria-pressed');
						button.attr('aria-pressed', !!pressed);
					}
				});

			/*
			if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
				bigPlay.remove();
				loading.remove();
			}
			*/


			// show/hide big play button
			media.addEventListener('play',function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('playing', function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('seeking', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);

			media.addEventListener('seeked', function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
			}, false);

			media.addEventListener('pause',function() {
				if (!mejs.MediaFeatures.isiPhone) {
					bigPlay.show();
				}
			}, false);

			media.addEventListener('waiting', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);


			// show/hide loading
			media.addEventListener('loadeddata',function() {
				// for some reason Chrome is firing this event
				//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
				//	return;

				loading.show();
				controls.find('.mejs-time-buffering').show();
				// Firing the 'canplay' event after a timeout which isn't getting fired on some Android 4.1 devices (https://github.com/johndyer/mediaelement/issues/1305)
				if (mejs.MediaFeatures.isAndroid) {
					media.canplayTimeout = window.setTimeout(
						function() {
							if (document.createEvent) {
								var evt = document.createEvent('HTMLEvents');
								evt.initEvent('canplay', true, true);
								return media.dispatchEvent(evt);
							}
						}, 300
					);
				}
			}, false);
			media.addEventListener('canplay',function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				clearTimeout(media.canplayTimeout); // Clear timeout inside 'loadeddata' to prevent 'canplay' to fire twice
			}, false);

			// error handling
			media.addEventListener('error',function(e) {
				t.handleError(e);
				loading.hide();
				bigPlay.hide();
				error.show();
				error.find('.mejs-overlay-error').html("Error loading this resource");
			}, false);

			media.addEventListener('keydown', function(e) {
				t.onkeydown(player, media, e);
			}, false);
		},

		buildkeyboard: function(player, controls, layers, media) {

				var t = this;

				t.container.keydown(function () {
					t.keyboardAction = true;
				});

				// listen for key presses
				t.globalBind('keydown', function(event) {
					player.hasFocus = $(event.target).closest('.mejs-container').length !== 0
						&& $(event.target).closest('.mejs-container').attr('id') === player.$media.closest('.mejs-container').attr('id');
					return t.onkeydown(player, media, event);
				});


				// check if someone clicked outside a player region, then kill its focus
				t.globalBind('click', function(event) {
					player.hasFocus = $(event.target).closest('.mejs-container').length !== 0;
				});

		},
		onkeydown: function(player, media, e) {
			if (player.hasFocus && player.options.enableKeyboard) {
				// find a matching key
				for (var i = 0, il = player.options.keyActions.length; i < il; i++) {
					var keyAction = player.options.keyActions[i];

					for (var j = 0, jl = keyAction.keys.length; j < jl; j++) {
						if (e.keyCode == keyAction.keys[j]) {
							if (typeof(e.preventDefault) == "function") e.preventDefault();
							keyAction.action(player, media, e.keyCode, e);
							return false;
						}
					}
				}
			}

			return true;
		},

		findTracks: function() {
			var t = this,
				tracktags = t.$media.find('track');

			// store for use by plugins
			t.tracks = [];
			tracktags.each(function(index, track) {

				track = $(track);

				t.tracks.push({
					srclang: (track.attr('srclang')) ? track.attr('srclang').toLowerCase() : '',
					src: track.attr('src'),
					kind: track.attr('kind'),
					label: track.attr('label') || '',
					entries: [],
					isLoaded: false
				});
			});
		},
		changeSkin: function(className) {
			this.container[0].className = 'mejs-container ' + className;
			this.setPlayerSize(this.width, this.height);
			this.setControlsSize();
		},
		play: function() {
			this.load();
			this.media.play();
		},
		pause: function() {
			try {
				this.media.pause();
			} catch (e) {}
		},
		load: function() {
			if (!this.isLoaded) {
				this.media.load();
			}

			this.isLoaded = true;
		},
		setMuted: function(muted) {
			this.media.setMuted(muted);
		},
		setCurrentTime: function(time) {
			this.media.setCurrentTime(time);
		},
		getCurrentTime: function() {
			return this.media.currentTime;
		},
		setVolume: function(volume) {
			this.media.setVolume(volume);
		},
		getVolume: function() {
			return this.media.volume;
		},
		setSrc: function(src) {
			var
				t = this;

			// If using YouTube, its API is different to load a specific source
			if (t.media.pluginType === 'youtube') {
				var videoId;

				if (typeof src !== 'string') {
					var i, media;

					for (i=0; i<src.length; i++) {
						media = src[i];
						if (this.canPlayType(media.type)) {
							src = media.src;
							break;
						}
					}
				}

				// youtu.be url from share button
				if (src.lastIndexOf('youtu.be') !== -1) {
					videoId = src.substr(src.lastIndexOf('/') + 1);

					if (videoId.indexOf('?') !== -1) {
						videoId = videoId.substr(0, videoId.indexOf('?'));
					}

				} else {
					// https://www.youtube.com/watch?v=
					var videoIdMatch = src.match(/[?&]v=([^&#]+)|&|#|$/);

					if (videoIdMatch) {
						videoId = videoIdMatch[1];
					}
				}

				if (t.media.getAttribute('autoplay') !== null) {
					t.media.pluginApi.loadVideoById(videoId);
				} else {
					t.media.pluginApi.cueVideoById(videoId);
				}

			}
			else {
				t.media.setSrc(src);
			}
		},
		remove: function() {
			var t = this, featureIndex, feature;

			t.container.prev('.mejs-offscreen').remove();

			// invoke features cleanup
			for (featureIndex in t.options.features) {
				feature = t.options.features[featureIndex];
				if (t['clean' + feature]) {
					try {
						t['clean' + feature](t);
					} catch (e) {
						// TODO: report control error
						//throw e;
						//
						//
					}
				}
			}

			// grab video and put it back in place
			if (!t.isDynamic) {
				t.$media.prop('controls', true);
				// detach events from the video
				// TODO: detach event listeners better than this;
				//		 also detach ONLY the events attached by this plugin!
				t.$node.clone().insertBefore(t.container).show();
				t.$node.remove();
			} else {
				t.$node.insertBefore(t.container);
			}

			if (t.media.pluginType !== 'native') {
				t.media.remove();
			}

			// Remove the player from the mejs.players object so that pauseOtherPlayers doesn't blow up when trying to pause a non existance flash api.
			delete mejs.players[t.id];

			if (typeof t.container == 'object') {
				t.container.remove();
			}
			t.globalUnbind();
			delete t.node.player;
		},
		rebuildtracks: function(){
			var t = this;
			t.findTracks();
			t.buildtracks(t, t.controls, t.layers, t.media);
		},
		resetSize: function(){
			var t = this;
			// webkit has trouble doing this without a delay
			setTimeout(function () {
				//
				t.setPlayerSize(t.width, t.height);
				t.setControlsSize();
			}, 50);
		}
	};

	(function(){
		var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;

		function splitEvents(events, id) {
			// add player ID as an event namespace so it's easier to unbind them all later
			var ret = {d: [], w: []};
			$.each((events || '').split(' '), function(k, v){
				var eventname = v + '.' + id;
				if (eventname.indexOf('.') === 0) {
					ret.d.push(eventname);
					ret.w.push(eventname);
				}
				else {
					ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
				}
			});
			ret.d = ret.d.join(' ');
			ret.w = ret.w.join(' ');
			return ret;
		}

		mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
			var t = this;
			var doc = t.node ? t.node.ownerDocument : document;

			events = splitEvents(events, t.id);
			if (events.d) $(doc).bind(events.d, data, callback);
			if (events.w) $(window).bind(events.w, data, callback);
		};

		mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
			var t = this;
			var doc = t.node ? t.node.ownerDocument : document;

			events = splitEvents(events, t.id);
			if (events.d) $(doc).unbind(events.d, callback);
			if (events.w) $(window).unbind(events.w, callback);
		};
	})();

	// turn into jQuery plugin
	if (typeof $ != 'undefined') {
		$.fn.mediaelementplayer = function (options) {
			if (options === false) {
				this.each(function () {
					var player = $(this).data('mediaelementplayer');
					if (player) {
						player.remove();
					}
					$(this).removeData('mediaelementplayer');
				});
			}
			else {
				this.each(function () {
					$(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
				});
			}
			return this;
		};


		$(document).ready(function() {
			// auto enable using JSON attribute
			$('.mejs-player').mediaelementplayer();
		});
	}

	// push out to window
	window.MediaElementPlayer = mejs.MediaElementPlayer;

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		playText: '',
		pauseText: ''
	});


	// PLAY/pause BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildplaypause: function(player, controls, layers, media) {
			var 
				t = this,
				op = t.options,
				playTitle = op.playText ? op.playText : mejs.i18n.t('mejs.play'),
				pauseTitle = op.pauseText ? op.pauseText : mejs.i18n.t('mejs.pause'),
				play =
				$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
					'<button type="button" aria-controls="' + t.id + '" title="' + playTitle + '" aria-label="' + pauseTitle + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function(e) {
					e.preventDefault();
				
					if (media.paused) {
						media.play();
					} else {
						media.pause();
					}
					
					return false;
				}),
				play_btn = play.find('button');


			function togglePlayPause(which) {
				if ('play' === which) {
					play.removeClass('mejs-play').addClass('mejs-pause');
					play_btn.attr({
						'title': pauseTitle,
						'aria-label': pauseTitle
					});
				} else {
					play.removeClass('mejs-pause').addClass('mejs-play');
					play_btn.attr({
						'title': playTitle,
						'aria-label': playTitle
					});
				}
			};
			togglePlayPause('pse');


			media.addEventListener('play',function() {
				togglePlayPause('play');
			}, false);
			media.addEventListener('playing',function() {
				togglePlayPause('play');
			}, false);


			media.addEventListener('pause',function() {
				togglePlayPause('pse');
			}, false);
			media.addEventListener('paused',function() {
				togglePlayPause('pse');
			}, false);
		}
	});
	
})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		stopText: 'Stop'
	});

	// STOP BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildstop: function(player, controls, layers, media) {
			var t = this;

			$('<div class="mejs-button mejs-stop-button mejs-stop">' +
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '" aria-label="' + t.options.stopText + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function() {
					if (!media.paused) {
						media.pause();
					}
					if (media.currentTime > 0) {
						media.setCurrentTime(0);
                        media.pause();
						controls.find('.mejs-time-current').width('0px');
						controls.find('.mejs-time-handle').css('left', '0px');
						controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0, player.options));
						controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0, player.options));
						layers.find('.mejs-poster').show();
					}
				});
		}
	});
	
})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		// Enable tooltip that shows time in progress bar
		enableProgressTooltip: true,
		progressHelpText: ''
	});

	// progress/loaded bar
	$.extend(MediaElementPlayer.prototype, {
		buildprogress: function(player, controls, layers, media) {

			var
				t = this,
				mouseIsDown = false,
				mouseIsOver = false,
				lastKeyPressTime = 0,
				startedPaused = false,
				autoRewindInitial = player.options.autoRewind,
				progressTitle = t.options.progressHelpText ? t.options.progressHelpText : mejs.i18n.t('mejs.time-help-text'),
				tooltip = player.options.enableProgressTooltip ? '<span class="mejs-time-float">' +
					'<span class="mejs-time-float-current">00:00</span>' +
					'<span class="mejs-time-float-corner"></span>' +
				'</span>' : "";

			$('<div class="mejs-time-rail">' +
				'<span  class="mejs-time-total mejs-time-slider">' +
				//'<span class="mejs-offscreen">' + progressTitle + '</span>' +
					'<span class="mejs-time-buffering"></span>' +
					'<span class="mejs-time-loaded"></span>' +
					'<span class="mejs-time-current"></span>' +
					'<span class="mejs-time-handle"></span>' +
					 tooltip +
				'</span>' +
			'</div>')
				.appendTo(controls);
			controls.find('.mejs-time-buffering').hide();

			t.total = controls.find('.mejs-time-total');
			t.loaded  = controls.find('.mejs-time-loaded');
			t.current  = controls.find('.mejs-time-current');
			t.handle  = controls.find('.mejs-time-handle');
			t.timefloat  = controls.find('.mejs-time-float');
			t.timefloatcurrent  = controls.find('.mejs-time-float-current');
			t.slider = controls.find('.mejs-time-slider');

			var handleMouseMove = function (e) {

					var offset = t.total.offset(),
						width = t.total.width(),
						percentage = 0,
						newTime = 0,
						pos = 0,
						x;

					// mouse or touch position relative to the object
					if (e.originalEvent && e.originalEvent.changedTouches) {
						x = e.originalEvent.changedTouches[0].pageX;
					} else if (e.changedTouches) { // for Zepto
						x = e.changedTouches[0].pageX;
					} else {
						x = e.pageX;
					}

					if (media.duration) {
						if (x < offset.left) {
							x = offset.left;
						} else if (x > width + offset.left) {
							x = width + offset.left;
						}

						pos = x - offset.left;
						percentage = (pos / width);
						newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;

						// seek to where the mouse is
						if (mouseIsDown && newTime !== media.currentTime) {
							media.setCurrentTime(newTime);
						}

						// position floating time box
						if (!mejs.MediaFeatures.hasTouch) {
							t.timefloat.css('left', pos);
							t.timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime, player.options) );
							t.timefloat.show();
						}
					}
				},
				// Accessibility for slider
				updateSlider = function (e) {

					var seconds = media.currentTime,
						timeSliderText = mejs.i18n.t('mejs.time-slider'),
						time = mejs.Utility.secondsToTimeCode(seconds, player.options),
						duration = media.duration;

					t.slider.attr({
						'aria-label': timeSliderText,
						'aria-valuemin': 0,
						'aria-valuemax': duration,
						'aria-valuenow': seconds,
						'aria-valuetext': time,
						'role': 'slider',
						'tabindex': 0
					});

				},
				restartPlayer = function () {
					var now = new Date();
					if (now - lastKeyPressTime >= 1000) {
						media.play();
					}
				};

			t.slider.bind('focus', function (e) {
				player.options.autoRewind = false;
			});

			t.slider.bind('blur', function (e) {
				player.options.autoRewind = autoRewindInitial;
			});

			t.slider.bind('keydown', function (e) {

				if ((new Date() - lastKeyPressTime) >= 1000) {
					startedPaused = media.paused;
				}

				var keyCode = e.keyCode,
					duration = media.duration,
					seekTime = media.currentTime,
					seekForward  = player.options.defaultSeekForwardInterval(media),
					seekBackward = player.options.defaultSeekBackwardInterval(media);

				switch (keyCode) {
					case 37: // left
					case 40: // Down
						seekTime -= seekBackward;
						break;
					case 39: // Right
					case 38: // Up
						seekTime += seekForward;
						break;
					case 36: // Home
						seekTime = 0;
						break;
					case 35: // end
						seekTime = duration;
						break;
					case 32: // space
					case 13: // enter
						media.paused ? media.play() : media.pause();
						return;
					default:
						return;
				}

				seekTime = seekTime < 0 ? 0 : (seekTime >= duration ? duration : Math.floor(seekTime));
				lastKeyPressTime = new Date();
				if (!startedPaused) {
					media.pause();
				}

				if (seekTime < media.duration && !startedPaused) {
					setTimeout(restartPlayer, 1100);
				}

				media.setCurrentTime(seekTime);

				e.preventDefault();
				e.stopPropagation();
				return false;
			});


			// handle clicks
			//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
			t.total
				.bind('mousedown touchstart', function (e) {
					// only handle left clicks or touch
					if (e.which === 1 || e.which === 0) {
						mouseIsDown = true;
						handleMouseMove(e);
						t.globalBind('mousemove.dur touchmove.dur', function(e) {
							handleMouseMove(e);
						});
						t.globalBind('mouseup.dur touchend.dur', function (e) {
							mouseIsDown = false;
							if (typeof t.timefloat !== 'undefined') {
								t.timefloat.hide();
							}
							t.globalUnbind('.dur');
						});
					}
				})
				.bind('mouseenter', function(e) {
					mouseIsOver = true;
					t.globalBind('mousemove.dur', function(e) {
						handleMouseMove(e);
					});
					if (typeof t.timefloat !== 'undefined' && !mejs.MediaFeatures.hasTouch) {
						t.timefloat.show();
					}
				})
				.bind('mouseleave',function(e) {
					mouseIsOver = false;
					if (!mouseIsDown) {
						t.globalUnbind('.dur');
						if (typeof t.timefloat !== 'undefined') {
							t.timefloat.hide();
						}
					}
				});

			// loading
			media.addEventListener('progress', function (e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			}, false);

			// current time
			media.addEventListener('timeupdate', function(e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
				updateSlider(e);
			}, false);

			t.container.on('controlsresize', function(e) {
				player.setProgressRail(e);
				player.setCurrentRail(e);
			});
		},
		setProgressRail: function(e) {

			var
				t = this,
				target = (e !== undefined) ? e.target : t.media,
				percent = null;

			// newest HTML5 spec has buffered array (FF4, Webkit)
			if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
				// account for a real array with multiple values - always read the end of the last buffer
				percent = target.buffered.end(target.buffered.length - 1) / target.duration;
			} 
			// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
			// to be anything other than 0. If the byte count is available we use this instead.
			// Browsers that support the else if do not seem to have the bufferedBytes value and
			// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
			else if (target && target.bytesTotal !== undefined && target.bytesTotal > 0 && target.bufferedBytes !== undefined) {
				percent = target.bufferedBytes / target.bytesTotal;
			}
			// Firefox 3 with an Ogg file seems to go this way
			else if (e && e.lengthComputable && e.total !== 0) {
				percent = e.loaded / e.total;
			}

			// finally update the progress bar
			if (percent !== null) {
				percent = Math.min(1, Math.max(0, percent));
				// update loaded bar
				if (t.loaded && t.total) {
					t.loaded.width(t.total.width() * percent);
				}
			}
		},
		setCurrentRail: function() {

			var t = this;
		
			if (t.media.currentTime !== undefined && t.media.duration) {

				// update bar and handle
				if (t.total && t.handle) {
					var 
						newWidth = Math.round(t.total.width() * t.media.currentTime / t.media.duration),
						handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);

					t.current.width(newWidth);
					t.handle.css('left', handlePos);
				}
			}

		}
	});
})(mejs.$);

(function($) {
	
	// options
	$.extend(mejs.MepDefaults, {
		duration: -1,
		timeAndDurationSeparator: '<span> | </span>'
	});


	// current and duration 00:00 / 00:00
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;
			
			$('<div class="mejs-time" role="timer" aria-live="off">' +
					'<span class="mejs-currenttime">' + 
						mejs.Utility.secondsToTimeCode(0, player.options) +
                    '</span>'+
				'</div>')
			.appendTo(controls);
			
			t.currenttime = t.controls.find('.mejs-currenttime');

			media.addEventListener('timeupdate',function() {
				if (t.controlsAreVisible) {
					player.updateCurrent();
				}

			}, false);
		},


		buildduration: function(player, controls, layers, media) {
			var t = this;
			
			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'<span class="mejs-duration">' + 
						mejs.Utility.secondsToTimeCode(t.options.duration, t.options) +
					'</span>')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
				
				$('<div class="mejs-time mejs-duration-container">'+
					'<span class="mejs-duration">' + 
						mejs.Utility.secondsToTimeCode(t.options.duration, t.options) +
					'</span>' +
				'</div>')
				.appendTo(controls);
			}
			
			t.durationD = t.controls.find('.mejs-duration');

			media.addEventListener('timeupdate',function() {
				if (t.controlsAreVisible) {
					player.updateDuration();
				}
			}, false);
		},
		
		updateCurrent:  function() {
			var t = this;
			
			var currentTime = t.media.currentTime;
			
			if (isNaN(currentTime)) {
				currentTime = 0;
			}

			if (t.currenttime) {
				t.currenttime.html(mejs.Utility.secondsToTimeCode(currentTime, t.options));
			}
		},
		
		updateDuration: function() {
			var t = this;
			
			var duration = t.media.duration;
			if (t.options.duration > 0) {
				duration = t.options.duration;
			}
			
			if (isNaN(duration)) {
				duration = 0;
			}

			//Toggle the long video class if the video is longer than an hour.
			t.container.toggleClass("mejs-long-video", duration > 3600);
			
			if (t.durationD && duration > 0) {
				t.durationD.html(mejs.Utility.secondsToTimeCode(duration, t.options));
			}		
		}
	});

})(mejs.$);

(function ($) {

	$.extend(mejs.MepDefaults, {
		muteText: mejs.i18n.t('mejs.mute-toggle'),
		allyVolumeControlText: mejs.i18n.t('mejs.volume-help-text'),
		hideVolumeOnTouchDevices: true,

		audioVolume: 'horizontal',
		videoVolume: 'vertical'
	});

	$.extend(MediaElementPlayer.prototype, {
		buildvolume: function (player, controls, layers, media) {

			// Android and iOS don't support volume controls
			if ((mejs.MediaFeatures.isAndroid || mejs.MediaFeatures.isiOS) && this.options.hideVolumeOnTouchDevices)
				return;

			var t = this,
				mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
				mute = (mode == 'horizontal') ?

					// horizontal version
					$('<div class="mejs-button mejs-volume-button mejs-mute">' +
						'<button type="button" aria-controls="' + t.id +
						'" title="' + t.options.muteText +
						'" aria-label="' + t.options.muteText +
						'"></button>' +
						'</div>' +
						'<a href="javascript:void(0);" class="mejs-horizontal-volume-slider">' + // outer background
						'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
						'<div class="mejs-horizontal-volume-total"></div>' + // line background
						'<div class="mejs-horizontal-volume-current"></div>' + // current volume
						'<div class="mejs-horizontal-volume-handle"></div>' + // handle
						'</a>'
					)
					.appendTo(controls) :

					// vertical version
					$('<div class="mejs-button mejs-volume-button mejs-mute">' +
						'<button type="button" aria-controls="' + t.id +
						'" title="' + t.options.muteText +
						'" aria-label="' + t.options.muteText +
						'"></button>' +
						'<a href="javascript:void(0);" class="mejs-volume-slider">' + // outer background
						'<span class="mejs-offscreen">' + t.options.allyVolumeControlText + '</span>' +
						'<div class="mejs-volume-total"></div>' + // line background
						'<div class="mejs-volume-current"></div>' + // current volume
						'<div class="mejs-volume-handle"></div>' + // handle
						'</a>' +
						'</div>')
					.appendTo(controls),
				volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
				volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
				volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
				volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),

				positionVolumeHandle = function (volume, secondTry) {

					if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
						volumeSlider.show();
						positionVolumeHandle(volume, true);
						volumeSlider.hide();
						return;
					}

					// correct to 0-1
					volume = Math.max(0, volume);
					volume = Math.min(volume, 1);

					// adjust mute button style
					if (volume === 0) {
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
						mute.children('button').attr('title', mejs.i18n.t('mejs.unmute')).attr('aria-label', mejs.i18n.t('mejs.unmute'));
					} else {
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
						mute.children('button').attr('title', mejs.i18n.t('mejs.mute')).attr('aria-label', mejs.i18n.t('mejs.mute'));
					}

					// top/left of full size volume slider background
					var totalPosition = volumeTotal.position();
					// position slider
					if (mode == 'vertical') {
						var
							// height of the full size volume slider background
							totalHeight = volumeTotal.height(),

							// the new top position based on the current volume
							// 70% volume on 100px height == top:30px
							newTop = totalHeight - (totalHeight * volume);

						// handle
						volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));

						// show the current visibility
						volumeCurrent.height(totalHeight - newTop);
						volumeCurrent.css('top', totalPosition.top + newTop);
					} else {
						var
							// height of the full size volume slider background
							totalWidth = volumeTotal.width(),

							// the new left position based on the current volume
							newLeft = totalWidth * volume;

						// handle
						volumeHandle.css('left', Math.round(totalPosition.left + newLeft - (volumeHandle.width() / 2)));

						// rezize the current part of the volume bar
						volumeCurrent.width(Math.round(newLeft));
					}
				},
				handleVolumeMove = function (e) {

					var volume = null,
						totalOffset = volumeTotal.offset();

					// calculate the new volume based on the moust position
					if (mode === 'vertical') {

						var
							railHeight = volumeTotal.height(),
							newY = e.pageY - totalOffset.top;

						volume = (railHeight - newY) / railHeight;

						// the controls just hide themselves (usually when mouse moves too far up)
						if (totalOffset.top === 0 || totalOffset.left === 0) {
							return;
						}

					} else {
						var
							railWidth = volumeTotal.width(),
							newX = e.pageX - totalOffset.left;

						volume = newX / railWidth;
					}

					// ensure the volume isn't outside 0-1
					volume = Math.max(0, volume);
					volume = Math.min(volume, 1);

					// position the slider and handle
					positionVolumeHandle(volume);

					// set the media object (this will trigger the volumechanged event)
					if (volume === 0) {
						media.setMuted(true);
					} else {
						media.setMuted(false);
					}
					media.setVolume(volume);
				},
				mouseIsDown = false,
				mouseIsOver = false;

			// SLIDER

			mute
			.hover(function () {
				volumeSlider.show();
				mouseIsOver = true;
			}, function () {
				mouseIsOver = false;

				if (!mouseIsDown && mode == 'vertical') {
					volumeSlider.hide();
				}
			});

			var updateVolumeSlider = function (e) {

				var volume = Math.floor(media.volume * 100);

				volumeSlider.attr({
					'aria-label': mejs.i18n.t('mejs.volume-slider'),
					'aria-valuemin': 0,
					'aria-valuemax': 100,
					'aria-valuenow': volume,
					'aria-valuetext': volume + '%',
					'role': 'slider',
					'tabindex': 0
				});

			};

			volumeSlider
			.bind('mouseover', function () {
				mouseIsOver = true;
			})
			.bind('mousedown', function (e) {
				handleVolumeMove(e);
				t.globalBind('mousemove.vol', function (e) {
					handleVolumeMove(e);
				});
				t.globalBind('mouseup.vol', function () {
					mouseIsDown = false;
					t.globalUnbind('.vol');

					if (!mouseIsOver && mode == 'vertical') {
						volumeSlider.hide();
					}
				});
				mouseIsDown = true;

				return false;
			})
			.bind('keydown', function (e) {
				var keyCode = e.keyCode;
				var volume = media.volume;
				switch (keyCode) {
					case 38: // Up
						volume = Math.min(volume + 0.1, 1);
						break;
					case 40: // Down
						volume = Math.max(0, volume - 0.1);
						break;
					default:
						return true;
				}

				mouseIsDown = false;
				positionVolumeHandle(volume);
				media.setVolume(volume);
				return false;
			});

			// MUTE button
			mute.find('button').click(function () {
				media.setMuted(!media.muted);
			});

			//Keyboard input
			mute.find('button').bind('focus', function () {
				volumeSlider.show();
			});

			// listen for volume change events from other sources
			media.addEventListener('volumechange', function (e) {
				if (!mouseIsDown) {
					if (media.muted) {
						positionVolumeHandle(0);
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
					} else {
						positionVolumeHandle(media.volume);
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
					}
				}
				updateVolumeSlider(e);
			}, false);

			// mutes the media and sets the volume icon muted if the initial volume is set to 0
			if (player.options.startVolume === 0) {
				media.setMuted(true);
			}

			// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
			if (media.pluginType === 'native') {
				media.setVolume(player.options.startVolume);
			}

			t.container.on('controlsresize', function () {
				if (media.muted) {
					positionVolumeHandle(0);
					mute.removeClass('mejs-mute').addClass('mejs-unmute');
				} else {
					positionVolumeHandle(media.volume);
					mute.removeClass('mejs-unmute').addClass('mejs-mute');
				}
			});
		}
	});

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		usePluginFullScreen: true,
		newWindowCallback: function() { return '';},
		fullscreenText: ''
	});

	$.extend(MediaElementPlayer.prototype, {

		isFullScreen: false,

		isNativeFullScreen: false,

		isInIframe: false,
							
		// Possible modes
		// (1) 'native-native' 	HTML5 video  + browser fullscreen (IE10+, etc.)
		// (2) 'plugin-native' 	plugin video + browser fullscreen (fails in some versions of Firefox)
		// (3) 'fullwindow' 	Full window (retains all UI)
		// usePluginFullScreen = true
		// (4) 'plugin-click' 	Flash 1 - click through with pointer events
		// (5) 'plugin-hover' 	Flash 2 - hover popup in flash (IE6-8)		
		fullscreenMode: '',

		buildfullscreen: function(player, controls, layers, media) {

			if (!player.isVideo)
				return;
				
			player.isInIframe = (window.location != window.parent.location);	
		
			// detect on start
			media.addEventListener('loadstart', function() { player.detectFullscreenMode(); });
				
			// build button
			var t = this,
				hideTimeout = null,
				fullscreenTitle = t.options.fullscreenText ? t.options.fullscreenText : mejs.i18n.t('mejs.fullscreen'),
				fullscreenBtn =
					$('<div class="mejs-button mejs-fullscreen-button">' +
						'<button type="button" aria-controls="' + t.id + '" title="' + fullscreenTitle + '" aria-label="' + fullscreenTitle + '"></button>' +
					'</div>')
					.appendTo(controls)
					.on('click', function() {
						
						// toggle fullscreen
						var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
	
						if (isFullScreen) {
							player.exitFullScreen();
						} else {
							player.enterFullScreen();
						}
					})										
					.on('mouseover', function() {
						
						// very old browsers with a plugin
						if (t.fullscreenMode == 'plugin-hover') {						
							if (hideTimeout !== null) {
								clearTimeout(hideTimeout);
								delete hideTimeout;
							}
	
							var buttonPos = fullscreenBtn.offset(),
								containerPos = player.container.offset();
	
							media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
						}

					})
					.on('mouseout', function() {

						if (t.fullscreenMode == 'plugin-hover') {						
							if (hideTimeout !== null) {
								clearTimeout(hideTimeout);
								delete hideTimeout;
							}
	
							hideTimeout = setTimeout(function() {
								media.hideFullscreenButton();
							}, 1500);
						}

					});

					

			player.fullscreenBtn = fullscreenBtn;

			t.globalBind('keydown',function (e) {
				if (e.keyCode == 27 && ((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen)) {
					player.exitFullScreen();
				}
			});
			
			t.normalHeight = 0;
			t.normalWidth = 0;					
					
			// setup native fullscreen event
			if (mejs.MediaFeatures.hasTrueNativeFullScreen) {

				// chrome doesn't alays fire this in an iframe
				var fullscreenChanged = function(e) {
					if (player.isFullScreen) {
						if (mejs.MediaFeatures.isFullScreen()) {
							player.isNativeFullScreen = true;
							// reset the controls once we are fully in full screen
							player.setControlsSize();
						} else {
							player.isNativeFullScreen = false;
							// when a user presses ESC
							// make sure to put the player back into place
							player.exitFullScreen();
						}
					}
				};

				player.globalBind(mejs.MediaFeatures.fullScreenEventName, fullscreenChanged);
			}

		},
		
		detectFullscreenMode: function() {
			
			var t = this,
				mode = '',
				features = mejs.MediaFeatures;
			
			if (features.hasTrueNativeFullScreen && t.media.pluginType === 'native') {
				mode = 'native-native';
			} else if (features.hasTrueNativeFullScreen && t.media.pluginType !== 'native' && !features.hasFirefoxPluginMovingProblem) {
				mode = 'plugin-native';					
			} else if (t.usePluginFullScreen) { 
				if (mejs.MediaFeatures.supportsPointerEvents) {
					mode = 'plugin-click';
					// this needs some special setup
					t.createPluginClickThrough();				
				} else { 
					mode = 'plugin-hover';
				}
				
			} else {
				mode = 'fullwindow';
			}
			
			
			t.fullscreenMode = mode;		
			return mode;
		},
		
		isPluginClickThroughCreated: false,
		
		createPluginClickThrough: function() {
				
			var t = this;
			
			// don't build twice
			if (t.isPluginClickThroughCreated) {
				return;
			}	

			// allows clicking through the fullscreen button and controls down directly to Flash

			/*
			 When a user puts his mouse over the fullscreen button, we disable the controls so that mouse events can go down to flash (pointer-events)
			 We then put a divs over the video and on either side of the fullscreen button
			 to capture mouse movement and restore the controls once the mouse moves outside of the fullscreen button
			*/

			var fullscreenIsDisabled = false,
				restoreControls = function() {
					if (fullscreenIsDisabled) {
						// hide the hovers
						for (var i in hoverDivs) {
							hoverDivs[i].hide();
						}

						// restore the control bar
						t.fullscreenBtn.css('pointer-events', '');
						t.controls.css('pointer-events', '');

						// prevent clicks from pausing video
						t.media.removeEventListener('click', t.clickToPlayPauseCallback);

						// store for later
						fullscreenIsDisabled = false;
					}
				},
				hoverDivs = {},
				hoverDivNames = ['top', 'left', 'right', 'bottom'],
				i, len,
				positionHoverDivs = function() {
					var fullScreenBtnOffsetLeft = fullscreenBtn.offset().left - t.container.offset().left,
						fullScreenBtnOffsetTop = fullscreenBtn.offset().top - t.container.offset().top,
						fullScreenBtnWidth = fullscreenBtn.outerWidth(true),
						fullScreenBtnHeight = fullscreenBtn.outerHeight(true),
						containerWidth = t.container.width(),
						containerHeight = t.container.height();

					for (i in hoverDivs) {
						hoverDivs[i].css({position: 'absolute', top: 0, left: 0}); //, backgroundColor: '#f00'});
					}

					// over video, but not controls
					hoverDivs['top']
						.width( containerWidth )
						.height( fullScreenBtnOffsetTop );

					// over controls, but not the fullscreen button
					hoverDivs['left']
						.width( fullScreenBtnOffsetLeft )
						.height( fullScreenBtnHeight )
						.css({top: fullScreenBtnOffsetTop});

					// after the fullscreen button
					hoverDivs['right']
						.width( containerWidth - fullScreenBtnOffsetLeft - fullScreenBtnWidth )
						.height( fullScreenBtnHeight )
						.css({top: fullScreenBtnOffsetTop,
							 left: fullScreenBtnOffsetLeft + fullScreenBtnWidth});

					// under the fullscreen button
					hoverDivs['bottom']
						.width( containerWidth )
						.height( containerHeight - fullScreenBtnHeight - fullScreenBtnOffsetTop )
						.css({top: fullScreenBtnOffsetTop + fullScreenBtnHeight});
				};

			t.globalBind('resize', function() {
				positionHoverDivs();
			});

			for (i = 0, len = hoverDivNames.length; i < len; i++) {
				hoverDivs[hoverDivNames[i]] = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls).hide();
			}

			// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
			fullscreenBtn.on('mouseover',function() {

				if (!t.isFullScreen) {

					var buttonPos = fullscreenBtn.offset(),
						containerPos = player.container.offset();

					// move the button in Flash into place
					media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);

					// allows click through
					t.fullscreenBtn.css('pointer-events', 'none');
					t.controls.css('pointer-events', 'none');

					// restore click-to-play
					t.media.addEventListener('click', t.clickToPlayPauseCallback);

					// show the divs that will restore things
					for (i in hoverDivs) {
						hoverDivs[i].show();
					}

					positionHoverDivs();

					fullscreenIsDisabled = true;
				}

			});

			// restore controls anytime the user enters or leaves fullscreen
			media.addEventListener('fullscreenchange', function(e) {
				t.isFullScreen = !t.isFullScreen;
				// don't allow plugin click to pause video - messes with
				// plugin's controls
				if (t.isFullScreen) {
					t.media.removeEventListener('click', t.clickToPlayPauseCallback);
				} else {
					t.media.addEventListener('click', t.clickToPlayPauseCallback);
				}
				restoreControls();
			});


			// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
			// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button

			t.globalBind('mousemove', function(e) {

				// if the mouse is anywhere but the fullsceen button, then restore it all
				if (fullscreenIsDisabled) {

					var fullscreenBtnPos = fullscreenBtn.offset();


					if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
						e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
						) {

						fullscreenBtn.css('pointer-events', '');
						t.controls.css('pointer-events', '');

						fullscreenIsDisabled = false;
					}
				}
			});


			t.isPluginClickThroughCreated = true;
		},		

		cleanfullscreen: function(player) {
			player.exitFullScreen();
		},

        containerSizeTimeout: null,

		enterFullScreen: function() {

			var t = this;

			if (mejs.MediaFeatures.isiOS && mejs.MediaFeatures.hasiOSFullScreen && typeof t.media.webkitEnterFullscreen === 'function') {
			    t.media.webkitEnterFullscreen();
				return;
			}

			// set it to not show scroll bars so 100% will work
            $(document.documentElement).addClass('mejs-fullscreen');

			// store sizing
			t.normalHeight = t.container.height();
			t.normalWidth = t.container.width();



			// attempt to do true fullscreen
			if (t.fullscreenMode === 'native-native' || t.fullscreenMode === 'plugin-native') {

				mejs.MediaFeatures.requestFullScreen(t.container[0]);
				//return;

				if (t.isInIframe) {
					// sometimes exiting from fullscreen doesn't work
					// notably in Chrome <iframe>. Fixed in version 17
					setTimeout(function checkFullscreen() {

						if (t.isNativeFullScreen) {
							var percentErrorMargin = 0.002, // 0.2%
								windowWidth = $(window).width(),
								screenWidth = screen.width,
								absDiff = Math.abs(screenWidth - windowWidth),
								marginError = screenWidth * percentErrorMargin;

							// check if the video is suddenly not really fullscreen
							if (absDiff > marginError) {
								// manually exit
								t.exitFullScreen();
							} else {
								// test again
								setTimeout(checkFullscreen, 500);
							}
						}
						
					}, 1000);
				}
				
			} else if (t.fullscreeMode == 'fullwindow') {				
				// move into position
				
			}			
			
			// make full size
			t.container
				.addClass('mejs-container-fullscreen')
				.width('100%')
				.height('100%');
				//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});

			// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
			// Actually, it seems to be needed for IE8, too
			//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
				t.containerSizeTimeout = setTimeout(function() {
					t.container.css({width: '100%', height: '100%'});
					t.setControlsSize();
				}, 500);
			//}

			if (t.media.pluginType === 'native') {
				t.$media
					.width('100%')
					.height('100%');
			} else {
				t.container.find('.mejs-shim')
					.width('100%')
					.height('100%');	
				
				setTimeout(function() {
					var win = $(window),
						winW = win.width(),
						winH = win.height();
							
					t.media.setVideoSize(winW,winH);			
				}, 500);
			}

			t.layers.children('div')
				.width('100%')
				.height('100%');

			if (t.fullscreenBtn) {
				t.fullscreenBtn
					.removeClass('mejs-fullscreen')
					.addClass('mejs-unfullscreen');
			}

			t.setControlsSize();
			t.isFullScreen = true;

			var zoomFactor = Math.min(screen.width / t.width, screen.height / t.height);
			t.container.find('.mejs-captions-text').css('font-size', zoomFactor * 100 + '%');
			t.container.find('.mejs-captions-text').css('line-height', 'normal');
			t.container.find('.mejs-captions-position').css('bottom', '45px');

			t.container.trigger('enteredfullscreen');
		},

		exitFullScreen: function() {

			var t = this;

            // Prevent container from attempting to stretch a second time
            clearTimeout(t.containerSizeTimeout);

			// firefox can't adjust plugins
			/*
			if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
				t.media.setFullscreen(false);
				//player.isFullScreen = false;
				return;
			}
			*/

			// come out of native fullscreen
			if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
				mejs.MediaFeatures.cancelFullScreen();
			}

			// restore scroll bars to document
            $(document.documentElement).removeClass('mejs-fullscreen');

			t.container
				.removeClass('mejs-container-fullscreen')
				.width(t.normalWidth)
				.height(t.normalHeight);

			if (t.media.pluginType === 'native') {
				t.$media
					.width(t.normalWidth)
					.height(t.normalHeight);
			} else {
				t.container.find('.mejs-shim')
					.width(t.normalWidth)
					.height(t.normalHeight);

				t.media.setVideoSize(t.normalWidth, t.normalHeight);
			}

			t.layers.children('div')
				.width(t.normalWidth)
				.height(t.normalHeight);

			t.fullscreenBtn
				.removeClass('mejs-unfullscreen')
				.addClass('mejs-fullscreen');

			t.setControlsSize();
			t.isFullScreen = false;

			t.container.find('.mejs-captions-text').css('font-size','');
			t.container.find('.mejs-captions-text').css('line-height', '');
			t.container.find('.mejs-captions-position').css('bottom', '');

			t.container.trigger('exitedfullscreen');
		}
	});

})(mejs.$);

(function($) {

	// Speed
	$.extend(mejs.MepDefaults, {

		// We also support to pass object like this:
		// [{name: 'Slow', value: '0.75'}, {name: 'Normal', value: '1.00'}, ...]
		speeds: ['2.00', '1.50', '1.25', '1.00', '0.75'],

		defaultSpeed: '1.00',
		
		speedChar: 'x'

	});

	$.extend(MediaElementPlayer.prototype, {

		buildspeed: function(player, controls, layers, media) {
			var t = this;

			if (t.media.pluginType == 'native') {
				var 
					speedButton = null,
					speedSelector = null,
					playbackSpeed = null,
					inputId = null;

				var speeds = [];
				var defaultInArray = false;
				for (var i=0, len=t.options.speeds.length; i < len; i++) {
					var s = t.options.speeds[i];
					if (typeof(s) === 'string'){
						speeds.push({
							name: s + t.options.speedChar,
							value: s
						});
						if(s === t.options.defaultSpeed) {
							defaultInArray = true;
						}
					}
					else {
						speeds.push(s);
						if(s.value === t.options.defaultSpeed) {
							defaultInArray = true;
						}
					}
				}

				if (!defaultInArray) {
					speeds.push({
						name: t.options.defaultSpeed + t.options.speedChar,
						value: t.options.defaultSpeed
					});
				}

				speeds.sort(function(a, b) {
					return parseFloat(b.value) - parseFloat(a.value);
				});

				var getSpeedNameFromValue = function(value) {
					for(i=0,len=speeds.length; i <len; i++) {
						if (speeds[i].value === value) {
							return speeds[i].name;
						}
					}
				};

				var html = '<div class="mejs-button mejs-speed-button">' +
							'<button type="button">' + getSpeedNameFromValue(t.options.defaultSpeed) + '</button>' +
							'<div class="mejs-speed-selector">' +
							'<ul>';

				for (i = 0, il = speeds.length; i<il; i++) {
					inputId = t.id + '-speed-' + speeds[i].value;
					html += '<li>' + 
								'<input type="radio" name="speed" ' + 
											'value="' + speeds[i].value + '" ' +
											'id="' + inputId + '" ' +
											(speeds[i].value === t.options.defaultSpeed ? ' checked' : '') +
											' />' +
								'<label for="' + inputId + '" ' +
											(speeds[i].value === t.options.defaultSpeed ? ' class="mejs-speed-selected"' : '') +
											'>' + speeds[i].name + '</label>' +
							'</li>';
				}
				html += '</ul></div></div>';

				speedButton = $(html).appendTo(controls);
				speedSelector = speedButton.find('.mejs-speed-selector');

				playbackSpeed = t.options.defaultSpeed;

				media.addEventListener('loadedmetadata', function(e) {
					if (playbackSpeed) {
						media.playbackRate = parseFloat(playbackSpeed);
					}
				}, true);

				speedSelector
					.on('click', 'input[type="radio"]', function() {
						var newSpeed = $(this).attr('value');
						playbackSpeed = newSpeed;
						media.playbackRate = parseFloat(newSpeed);
						speedButton.find('button').html(getSpeedNameFromValue(newSpeed));
						speedButton.find('.mejs-speed-selected').removeClass('mejs-speed-selected');
						speedButton.find('input[type="radio"]:checked').next().addClass('mejs-speed-selected');
					});
				speedButton
					.one( 'mouseenter focusin', function() {
						speedSelector
							.height(
								speedButton.find('.mejs-speed-selector ul').outerHeight(true) +
								speedButton.find('.mejs-speed-translations').outerHeight(true))
							.css('top', (-1 * speedSelector.height()) + 'px');
					});
			}
		}
	});

})(mejs.$);

(function($) {

	// add extra default options
	$.extend(mejs.MepDefaults, {
		// this will automatically turn on a <track>
		startLanguage: '',

		tracksText: '',

		// By default, no WAI-ARIA live region - don't make a
		// screen reader speak captions over an audio track.
		tracksAriaLive: false,

		// option to remove the [cc] button when no <track kind="subtitles"> are present
		hideCaptionsButtonWhenEmpty: true,

		// If true and we only have one track, change captions to popup
		toggleCaptionsButtonWhenOnlyOne: false,

		// #id or .class
		slidesSelector: ''
	});

	$.extend(MediaElementPlayer.prototype, {

		hasChapters: false,

		cleartracks: function(player, controls, layers, media){
			if(player) {
				if(player.captions) player.captions.remove();
				if(player.chapters) player.chapters.remove();
				if(player.captionsText) player.captionsText.remove();
				if(player.captionsButton) player.captionsButton.remove();
			}
		},
		buildtracks: function(player, controls, layers, media) {
			if (player.tracks.length === 0)
				return;

			var t = this,
				attr = t.options.tracksAriaLive ?
					'role="log" aria-live="assertive" aria-atomic="false"' : '',
				tracksTitle = t.options.tracksText ? t.options.tracksText : mejs.i18n.t('mejs.captions-subtitles'),
				i,
				kind;

			if (t.domNode.textTracks) { // if browser will do native captions, prefer mejs captions, loop through tracks and hide
				for (i = t.domNode.textTracks.length - 1; i >= 0; i--) {
					t.domNode.textTracks[i].mode = "hidden";
				}
			}
			t.cleartracks(player, controls, layers, media);
			player.chapters =
					$('<div class="mejs-chapters mejs-layer"></div>')
						.prependTo(layers).hide();
			player.captions =
					$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover" ' +
					attr + '><span class="mejs-captions-text"></span></div></div>')
						.prependTo(layers).hide();
			player.captionsText = player.captions.find('.mejs-captions-text');
			player.captionsButton =
					$('<div class="mejs-button mejs-captions-button">'+
						'<button type="button" aria-controls="' + t.id + '" title="' + tracksTitle + '" aria-label="' + tracksTitle + '"></button>'+
						'<div class="mejs-captions-selector">'+
							'<ul>'+
								'<li>'+
									'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
									'<label for="' + player.id + '_captions_none">' + mejs.i18n.t('mejs.none') +'</label>'+
								'</li>'	+
							'</ul>'+
						'</div>'+
					'</div>')
						.appendTo(controls);


			var subtitleCount = 0;
			for (i=0; i<player.tracks.length; i++) {
				kind = player.tracks[i].kind;
				if (kind === 'subtitles' || kind === 'captions') {
					subtitleCount++;
				}
			}

			// if only one language then just make the button a toggle
			if (t.options.toggleCaptionsButtonWhenOnlyOne && subtitleCount == 1){
				// click
				player.captionsButton.on('click',function() {
					if (player.selectedTrack === null) {
						lang = player.tracks[0].srclang;
					} else {
						lang = 'none';
					}
					player.setTrack(lang);
				});
			} else {
				// hover or keyboard focus
				player.captionsButton.on( 'mouseenter focusin', function() {
					$(this).find('.mejs-captions-selector').removeClass('mejs-offscreen');
				})

				// handle clicks to the language radio buttons
				.on('click','input[type=radio]',function() {
					lang = this.value;
					player.setTrack(lang);
				});

				player.captionsButton.on( 'mouseleave focusout', function() {
					$(this).find(".mejs-captions-selector").addClass("mejs-offscreen");
				});

			}

			if (!player.options.alwaysShowControls) {
				// move with controls
				player.container
					.bind('controlsshown', function () {
						// push captions above controls
						player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');

					})
					.bind('controlshidden', function () {
						if (!media.paused) {
							// move back to normal place
							player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
						}
					});
			} else {
				player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
			}

			player.trackToLoad = -1;
			player.selectedTrack = null;
			player.isLoadingTrack = false;

			// add to list
			for (i=0; i<player.tracks.length; i++) {
				kind = player.tracks[i].kind;
				if (kind === 'subtitles' || kind === 'captions') {
					player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
				}
			}

			// start loading tracks
			player.loadNextTrack();

			media.addEventListener('timeupdate',function() {
				player.displayCaptions();
			}, false);

			if (player.options.slidesSelector !== '') {
				player.slidesContainer = $(player.options.slidesSelector);

				media.addEventListener('timeupdate',function() {
					player.displaySlides();
				}, false);

			}

			media.addEventListener('loadedmetadata', function() {
				player.displayChapters();
			}, false);

			player.container.hover(
				function () {
					// chapters
					if (player.hasChapters) {
						player.chapters.removeClass('mejs-offscreen');
						player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
					}
				},
				function () {
					if (player.hasChapters && !media.paused) {
						player.chapters.fadeOut(200, function() {
							$(this).addClass('mejs-offscreen');
							$(this).css('display','block');
						});
					}
				});

			t.container.on('controlsresize', function() {
				t.adjustLanguageBox();
			});

			// check for autoplay
			if (player.node.getAttribute('autoplay') !== null) {
				player.chapters.addClass('mejs-offscreen');
			}
		},

		setTrack: function(lang){

			var t = this,
				i;

			if (lang == 'none') {
				t.selectedTrack = null;
				t.captionsButton.removeClass('mejs-captions-enabled');
			} else {
				for (i=0; i<t.tracks.length; i++) {
					if (t.tracks[i].srclang == lang) {
						if (t.selectedTrack === null)
							t.captionsButton.addClass('mejs-captions-enabled');
						t.selectedTrack = t.tracks[i];
						t.captions.attr('lang', t.selectedTrack.srclang);
						t.displayCaptions();
						break;
					}
				}
			}
		},

		loadNextTrack: function() {
			var t = this;

			t.trackToLoad++;
			if (t.trackToLoad < t.tracks.length) {
				t.isLoadingTrack = true;
				t.loadTrack(t.trackToLoad);
			} else {
				// add done?
				t.isLoadingTrack = false;

				t.checkForTracks();
			}
		},

		loadTrack: function(index){
			var
				t = this,
				track = t.tracks[index],
				after = function() {

					track.isLoaded = true;

					t.enableTrackButton(track.srclang, track.label);

					t.loadNextTrack();

				};


			if (track.src !== undefined || track.src !== "") {
				$.ajax({
					url: track.src,
					dataType: "text",
					success: function(d) {

						// parse the loaded file
						if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
							track.entries = mejs.TrackFormatParser.dfxp.parse(d);
						} else {
							track.entries = mejs.TrackFormatParser.webvtt.parse(d);
						}

						after();

						if (track.kind == 'chapters') {
							t.media.addEventListener('play', function() {
								if (t.media.duration > 0) {
									t.displayChapters(track);
								}
							}, false);
						}

						if (track.kind == 'slides') {
							t.setupSlides(track);
						}
					},
					error: function() {
						t.removeTrackButton(track.srclang);
						t.loadNextTrack();
					}
				});
			}
		},

		enableTrackButton: function(lang, label) {
			var t = this;

			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}

			t.captionsButton
				.find('input[value=' + lang + ']')
					.prop('disabled',false)
				.siblings('label')
					.html( label );

			// auto select
			if (t.options.startLanguage == lang) {
				$('#' + t.id + '_captions_' + lang).prop('checked', true).trigger('click');
			}

			t.adjustLanguageBox();
		},

		removeTrackButton: function(lang) {
			var t = this;

			t.captionsButton.find('input[value=' + lang + ']').closest('li').remove();

			t.adjustLanguageBox();
		},

		addTrackButton: function(lang, label) {
			var t = this;
			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}

			t.captionsButton.find('ul').append(
				$('<li>'+
					'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
					'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
				'</li>')
			);

			t.adjustLanguageBox();

			// remove this from the dropdownlist (if it exists)
			t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
		},

		adjustLanguageBox:function() {
			var t = this;
			// adjust the size of the outer box
			t.captionsButton.find('.mejs-captions-selector').height(
				t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
				t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
			);
		},

		checkForTracks: function() {
			var
				t = this,
				hasSubtitles = false;

			// check if any subtitles
			if (t.options.hideCaptionsButtonWhenEmpty) {
				for (var i=0; i<t.tracks.length; i++) {
					var kind = t.tracks[i].kind;
					if ((kind === 'subtitles' || kind === 'captions') && t.tracks[i].isLoaded) {
						hasSubtitles = true;
						break;
					}
				}

				if (!hasSubtitles) {
					t.captionsButton.hide();
					t.setControlsSize();
				}
			}
		},

		displayCaptions: function() {

			if (typeof this.tracks == 'undefined')
				return;

			var
				t = this,
				i,
				track = t.selectedTrack;

			if (track !== null && track.isLoaded) {
				for (i=0; i<track.entries.times.length; i++) {
					if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop) {
						// Set the line before the timecode as a class so the cue can be targeted if needed
						t.captionsText.html(track.entries.text[i]).attr('class', 'mejs-captions-text ' + (track.entries.times[i].identifier || ''));
						t.captions.show().height(0);
						return; // exit out if one is visible;
					}
				}
				t.captions.hide();
			} else {
				t.captions.hide();
			}
		},

		setupSlides: function(track) {
			var t = this;

			t.slides = track;
			t.slides.entries.imgs = [t.slides.entries.text.length];
			t.showSlide(0);

		},

		showSlide: function(index) {
			if (typeof this.tracks == 'undefined' || typeof this.slidesContainer == 'undefined') {
				return;
			}

			var t = this,
				url = t.slides.entries.text[index],
				img = t.slides.entries.imgs[index];

			if (typeof img == 'undefined' || typeof img.fadeIn == 'undefined') {

				t.slides.entries.imgs[index] = img = $('<img src="' + url + '">')
						.on('load', function() {
							img.appendTo(t.slidesContainer)
								.hide()
								.fadeIn()
								.siblings(':visible')
									.fadeOut();

						});

			} else {

				if (!img.is(':visible') && !img.is(':animated')) {

					//

					img.fadeIn()
						.siblings(':visible')
							.fadeOut();
				}
			}

		},

		displaySlides: function() {

			if (typeof this.slides == 'undefined')
				return;

			var
				t = this,
				slides = t.slides,
				i;

			for (i=0; i<slides.entries.times.length; i++) {
				if (t.media.currentTime >= slides.entries.times[i].start && t.media.currentTime <= slides.entries.times[i].stop){

					t.showSlide(i);

					return; // exit out if one is visible;
				}
			}
		},

		displayChapters: function() {
			var
				t = this,
				i;

			for (i=0; i<t.tracks.length; i++) {
				if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
					t.drawChapters(t.tracks[i]);
					t.hasChapters = true;
					break;
				}
			}
		},

		drawChapters: function(chapters) {
			var
				t = this,
				i,
				dur,
				//width,
				//left,
				percent = 0,
				usedPercent = 0;

			t.chapters.empty();

			for (i=0; i<chapters.entries.times.length; i++) {
				dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
				percent = Math.floor(dur / t.media.duration * 100);
				if (percent + usedPercent > 100 || // too large
					i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
					{
					percent = 100 - usedPercent;
				}
				//width = Math.floor(t.width * dur / t.media.duration);
				//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
				//if (left + width > t.width) {
				//	width = t.width - left;
				//}

				t.chapters.append( $(
					'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
						'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
							'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
							'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start, t.options) + '&ndash;' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop, t.options) + '</span>' +
						'</div>' +
					'</div>'));
				usedPercent += percent;
			}

			t.chapters.find('div.mejs-chapter').click(function() {
				t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
				if (t.media.paused) {
					t.media.play();
				}
			});

			t.chapters.show();
		}
	});



	mejs.language = {
		codes:  {
			af:'Afrikaans',
			sq:'Albanian',
			ar:'Arabic',
			be:'Belarusian',
			bg:'Bulgarian',
			ca:'Catalan',
			zh:'Chinese',
			'zh-cn':'Chinese Simplified',
			'zh-tw':'Chinese Traditional',
			hr:'Croatian',
			cs:'Czech',
			da:'Danish',
			nl:'Dutch',
			en:'English',
			et:'Estonian',
			fl:'Filipino',
			fi:'Finnish',
			fr:'French',
			gl:'Galician',
			de:'German',
			el:'Greek',
			ht:'Haitian Creole',
			iw:'Hebrew',
			hi:'Hindi',
			hu:'Hungarian',
			is:'Icelandic',
			id:'Indonesian',
			ga:'Irish',
			it:'Italian',
			ja:'Japanese',
			ko:'Korean',
			lv:'Latvian',
			lt:'Lithuanian',
			mk:'Macedonian',
			ms:'Malay',
			mt:'Maltese',
			no:'Norwegian',
			fa:'Persian',
			pl:'Polish',
			pt:'Portuguese',
			// 'pt-pt':'Portuguese (Portugal)',
			ro:'Romanian',
			ru:'Russian',
			sr:'Serbian',
			sk:'Slovak',
			sl:'Slovenian',
			es:'Spanish',
			sw:'Swahili',
			sv:'Swedish',
			tl:'Tagalog',
			th:'Thai',
			tr:'Turkish',
			uk:'Ukrainian',
			vi:'Vietnamese',
			cy:'Welsh',
			yi:'Yiddish'
		}
	};

	/*
	Parses WebVTT format which should be formatted as
	================================
	WEBVTT

	1
	00:00:01,1 --> 00:00:05,000
	A line of text

	2
	00:01:15,1 --> 00:02:05,000
	A second line of text

	===============================

	Adapted from: http://www.delphiki.com/html5/playr
	*/
	mejs.TrackFormatParser = {
		webvtt: {
			pattern_timecode: /^((?:[0-9]{1,2}:)?[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ((?:[0-9]{1,2}:)?[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,

			parse: function(trackText) {
				var
					i = 0,
					lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
					entries = {text:[], times:[]},
					timecode,
					text,
					identifier;
				for(; i<lines.length; i++) {
					timecode = this.pattern_timecode.exec(lines[i]);

					if (timecode && i<lines.length) {
						if ((i - 1) >= 0 && lines[i - 1] !== '') {
							identifier = lines[i - 1];
						}
						i++;
						// grab all the (possibly multi-line) text that follows
						text = lines[i];
						i++;
						while(lines[i] !== '' && i<lines.length){
							text = text + '\n' + lines[i];
							i++;
						}
						text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
						// Text is in a different array so I can use .join
						entries.text.push(text);
						entries.times.push(
						{
							identifier: identifier,
							start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) === 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
							stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
							settings: timecode[5]
						});
					}
					identifier = '';
				}
				return entries;
			}
		},
		// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
		dfxp: {
			parse: function(trackText) {
				trackText = $(trackText).filter("tt");
				var
					i = 0,
					container = trackText.children("div").eq(0),
					lines = container.find("p"),
					styleNode = trackText.find("#" + container.attr("style")),
					styles,
					text,
					entries = {text:[], times:[]};


				if (styleNode.length) {
					var attributes = styleNode.removeAttr("id").get(0).attributes;
					if (attributes.length) {
						styles = {};
						for (i = 0; i < attributes.length; i++) {
							styles[attributes[i].name.split(":")[1]] = attributes[i].value;
						}
					}
				}

				for(i = 0; i<lines.length; i++) {
					var style;
					var _temp_times = {
						start: null,
						stop: null,
						style: null
					};
					if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
					if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
					if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
					if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
					if (styles) {
						style = "";
						for (var _style in styles) {
							style += _style + ":" + styles[_style] + ";";
						}
					}
					if (style) _temp_times.style = style;
					if (_temp_times.start === 0) _temp_times.start = 0.200;
					entries.times.push(_temp_times);
					text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
					entries.text.push(text);
				}
				return entries;
			}
		},
		split2: function (text, regex) {
			// normal version for compliant browsers
			// see below for IE fix
			return text.split(regex);
		}
	};

	// test for browsers with bad String.split method.
	if ('x\n\ny'.split(/\n/gi).length != 3) {
		// add super slow IE8 and below version
		mejs.TrackFormatParser.split2 = function(text, regex) {
			var
				parts = [],
				chunk = '',
				i;

			for (i=0; i<text.length; i++) {
				chunk += text.substring(i,i+1);
				if (regex.test(chunk)) {
					parts.push(chunk.replace(regex, ''));
					chunk = '';
				}
			}
			parts.push(chunk);
			return parts;
		};
	}

})(mejs.$);

// Source Chooser Plugin
(function($) {

	$.extend(mejs.MepDefaults, {
		sourcechooserText: ''
	});

	$.extend(MediaElementPlayer.prototype, {
		buildsourcechooser: function(player, controls, layers, media) {

			var
				t = this,
				sourceTitle = t.options.sourcechooserText ? t.options.sourcechooserText : mejs.i18n.t('mejs.source-chooser'),
				hoverTimeout
			;

			player.sourcechooserButton =
				$('<div class="mejs-button mejs-sourcechooser-button">'+
						'<button type="button" role="button" aria-haspopup="true" aria-owns="' + t.id + '" title="' + sourceTitle + '" aria-label="' + sourceTitle + '"></button>'+
						'<div class="mejs-sourcechooser-selector mejs-offscreen" role="menu" aria-expanded="false" aria-hidden="true">'+
							'<ul>'+
							'</ul>'+
						'</div>'+
					'</div>')
					.appendTo(controls)

					// hover
					.hover(function() {
						clearTimeout(hoverTimeout);
						player.showSourcechooserSelector();
					}, function() {
						var self = $(this);
						hoverTimeout = setTimeout(function () {
						player.hideSourcechooserSelector();
						}, 500);
					})

					// keyboard menu activation
					.on('keydown', function (e) {
						var keyCode = e.keyCode;

						switch (keyCode) {
							case 32: // space
								if (!mejs.MediaFeatures.isFirefox) { // space sends the click event in Firefox
									player.showSourcechooserSelector();
								}
								$(this).find('.mejs-sourcechooser-selector')
									.find('input[type=radio]:checked').first().focus();
								break;
							case 13: // enter
								player.showSourcechooserSelector();
								$(this).find('.mejs-sourcechooser-selector')
									.find('input[type=radio]:checked').first().focus();
								break;
							case 27: // esc
								player.hideSourcechooserSelector();
								$(this).find('button').focus();
								break;
							default:
								return true;
								}
							})

					// close menu when tabbing away
					.on('focusout', mejs.Utility.debounce(function (e) { // Safari triggers focusout multiple times
						// Firefox does NOT support e.relatedTarget to see which element
						// just lost focus, so wait to find the next focused element
						setTimeout(function () {
							var parent = $(document.activeElement).closest('.mejs-sourcechooser-selector');
							if (!parent.length) {
								// focus is outside the control; close menu
								player.hideSourcechooserSelector();
							}
						}, 0);
					}, 100))

					// handle clicks to the source radio buttons
					.delegate('input[type=radio]', 'click', function() {
						// set aria states
						$(this).attr('aria-selected', true).attr('checked', 'checked');
						$(this).closest('.mejs-sourcechooser-selector').find('input[type=radio]').not(this).attr('aria-selected', 'false').removeAttr('checked');

						var src = this.value;

						if (media.currentSrc != src) {
							var currentTime = media.currentTime;
							var paused = media.paused;
							media.pause();
							media.setSrc(src);

							media.addEventListener('loadedmetadata', function(e) {
								media.currentTime = currentTime;
							}, true);

							var canPlayAfterSourceSwitchHandler = function(e) {
								if (!paused) {
									media.play();
								}
								media.removeEventListener("canplay", canPlayAfterSourceSwitchHandler, true);
							};
							media.addEventListener('canplay', canPlayAfterSourceSwitchHandler, true);
							media.load();
						}
					})

					// Handle click so that screen readers can toggle the menu
					.delegate('button', 'click', function (e) {
						if ($(this).siblings('.mejs-sourcechooser-selector').hasClass('mejs-offscreen')) {
							player.showSourcechooserSelector();
							$(this).siblings('.mejs-sourcechooser-selector').find('input[type=radio]:checked').first().focus();
						} else {
							player.hideSourcechooserSelector();
						}
					});

			// add to list
			for (var i in this.node.children) {
				var src = this.node.children[i];
				if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) == 'probably' || media.canPlayType(src.type) == 'maybe')) {
					player.addSourceButton(src.src, src.title, src.type, media.src == src.src);
				}
			}
		},

		addSourceButton: function(src, label, type, isCurrent) {
			var t = this;
			if (label === '' || label == undefined) {
				label = src;
			}
			type = type.split('/')[1];

			t.sourcechooserButton.find('ul').append(
				$('<li>'+
						'<input type="radio" name="' + t.id + '_sourcechooser" id="' + t.id + '_sourcechooser_' + label + type + '" role="menuitemradio" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + 'aria-selected="' + isCurrent + '"' + ' />'+
						'<label for="' + t.id + '_sourcechooser_' + label + type + '" aria-hidden="true">' + label + ' (' + type + ')</label>'+
					'</li>')
			);

			t.adjustSourcechooserBox();

		},

		adjustSourcechooserBox: function() {
			var t = this;
			// adjust the size of the outer box
			t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
				t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
			);
		},

		hideSourcechooserSelector: function () {
			this.sourcechooserButton.find('.mejs-sourcechooser-selector')
				.addClass('mejs-offscreen')
				.attr('aria-expanded', 'false')
				.attr('aria-hidden', 'true')
				.find('input[type=radio]') // make radios not fucusable
				.attr('tabindex', '-1');
		},

		showSourcechooserSelector: function () {
			this.sourcechooserButton.find('.mejs-sourcechooser-selector')
				.removeClass('mejs-offscreen')
				.attr('aria-expanded', 'true')
				.attr('aria-hidden', 'false')
				.find('input[type=radio]')
				.attr('tabindex', '0');
		}
	});

})(mejs.$);

/*
* ContextMenu Plugin
* 
*
*/

(function($) {

$.extend(mejs.MepDefaults,
	{ 'contextMenuItems': [
		// demo of a fullscreen option
		{ 
			render: function(player) {
				
				// check for fullscreen plugin
				if (typeof player.enterFullScreen == 'undefined')
					return null;
			
				if (player.isFullScreen) {
					return mejs.i18n.t('mejs.fullscreen-off');
				} else {
					return mejs.i18n.t('mejs.fullscreen-on');
				}
			},
			click: function(player) {
				if (player.isFullScreen) {
					player.exitFullScreen();
				} else {
					player.enterFullScreen();
				}
			}
		}
		,
		// demo of a mute/unmute button
		{ 
			render: function(player) {
				if (player.media.muted) {
					return mejs.i18n.t('mejs.unmute');
				} else {
					return mejs.i18n.t('mejs.mute');
				}
			},
			click: function(player) {
				if (player.media.muted) {
					player.setMuted(false);
				} else {
					player.setMuted(true);
				}
			}
		},
		// separator
		{
			isSeparator: true
		}
		,
		// demo of simple download video
		{ 
			render: function(player) {
				return mejs.i18n.t('mejs.download-video');
			},
			click: function(player) {
				window.location.href = player.media.currentSrc;
			}
		}	
	]}
);


	$.extend(MediaElementPlayer.prototype, {
		buildcontextmenu: function(player, controls, layers, media) {
			
			// create context menu
			player.contextMenu = $('<div class="mejs-contextmenu"></div>')
								.appendTo($('body'))
								.hide();
			
			// create events for showing context menu
			player.container.bind('contextmenu', function(e) {
				if (player.isContextMenuEnabled) {
					e.preventDefault();
					player.renderContextMenu(e.clientX-1, e.clientY-1);
					return false;
				}
			});
			player.container.bind('click', function() {
				player.contextMenu.hide();
			});	
			player.contextMenu.bind('mouseleave', function() {

				//
				player.startContextMenuTimer();
				
			});		
		},

		cleancontextmenu: function(player) {
			player.contextMenu.remove();
		},
		
		isContextMenuEnabled: true,
		enableContextMenu: function() {
			this.isContextMenuEnabled = true;
		},
		disableContextMenu: function() {
			this.isContextMenuEnabled = false;
		},
		
		contextMenuTimeout: null,
		startContextMenuTimer: function() {
			//
			
			var t = this;
			
			t.killContextMenuTimer();
			
			t.contextMenuTimer = setTimeout(function() {
				t.hideContextMenu();
				t.killContextMenuTimer();
			}, 750);
		},
		killContextMenuTimer: function() {
			var timer = this.contextMenuTimer;
			
			//
			
			if (timer != null) {				
				clearTimeout(timer);
				delete timer;
				timer = null;
			}
		},		
		
		hideContextMenu: function() {
			this.contextMenu.hide();
		},
		
		renderContextMenu: function(x,y) {
			
			// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
			var t = this,
				html = '',
				items = t.options.contextMenuItems;
			
			for (var i=0, il=items.length; i<il; i++) {
				
				if (items[i].isSeparator) {
					html += '<div class="mejs-contextmenu-separator"></div>';
				} else {
				
					var rendered = items[i].render(t);
				
					// render can return null if the item doesn't need to be used at the moment
					if (rendered != null) {
						html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
					}
				}
			}
			
			// position and show the context menu
			t.contextMenu
				.empty()
				.append($(html))
				.css({top:y, left:x})
				.show();
				
			// bind events
			t.contextMenu.find('.mejs-contextmenu-item').each(function() {
							
				// which one is this?
				var $dom = $(this),
					itemIndex = parseInt( $dom.data('itemindex'), 10 ),
					item = t.options.contextMenuItems[itemIndex];
				
				// bind extra functionality?
				if (typeof item.show != 'undefined')
					item.show( $dom , t);
				
				// bind click action
				$dom.click(function() {			
					// perform click action
					if (typeof item.click != 'undefined')
						item.click(t);
					
					// close
					t.contextMenu.hide();				
				});				
			});	
			
			// stop the controls from hiding
			setTimeout(function() {
				t.killControlsTimer('rev3');	
			}, 100);
						
		}
	});
	
})(mejs.$);
(function($) {
	// skip back button

	$.extend(mejs.MepDefaults, {
		skipBackInterval: 30,
		// %1 will be replaced with skipBackInterval in this string
		skipBackText: ''
	});

	$.extend(MediaElementPlayer.prototype, {
		buildskipback: function(player, controls, layers, media) {
			var
				t = this,
				defaultTitle = mejs.i18n.t('mejs.time-skip-back', t.options.skipBackInterval),
				skipTitle = t.options.skipBackText ? t.options.skipBackText : defaultTitle,
				// create the loop button
				loop =
				$('<div class="mejs-button mejs-skip-back-button">' +
					'<button type="button" aria-controls="' + t.id + '" title="' + skipTitle + '" aria-label="' + skipTitle + '">' + t.options.skipBackInterval + '</button>' +
				'</div>')
				// append it to the toolbar
				.appendTo(controls)
				// add a click toggle event
				.click(function() {
					media.setCurrentTime(Math.max(media.currentTime - t.options.skipBackInterval, 0));
					$(this).find('button').blur();
				});
		}
	});

})(mejs.$);

/**
 * Postroll plugin
 */
(function($) {

	$.extend(mejs.MepDefaults, {
		postrollCloseText: ''
	});

	// Postroll
	$.extend(MediaElementPlayer.prototype, {
		buildpostroll: function(player, controls, layers, media) {
			var
				t = this,
				postrollTitle = t.options.postrollCloseText ? t.options.postrollCloseText : mejs.i18n.t('mejs.close'),
				postrollLink = t.container.find('link[rel="postroll"]').attr('href');

			if (typeof postrollLink !== 'undefined') {
				player.postroll =
					$('<div class="mejs-postroll-layer mejs-layer"><a class="mejs-postroll-close" onclick="$(this).parent().hide();return false;">' + postrollTitle + '</a><div class="mejs-postroll-layer-content"></div></div>').prependTo(layers).hide();

				t.media.addEventListener('ended', function (e) {
					$.ajax({
						dataType: 'html',
						url: postrollLink,
						success: function (data, textStatus) {
							layers.find('.mejs-postroll-layer-content').html(data);
						}
					});
					player.postroll.show();
				}, false);
			}
		}
	});

})(mejs.$);
/*
MediaElement-Markers is a MediaElement.js plugin that lets you add Visual Cues in the progress time rail. 
This plugin also lets you register a custom callback function that will be called everytime the play position reaches a marker. 
Marker position and a reference to the MediaElement Player object is passed to the registered callback function for any post processing. Marker color is configurable.

*/

(function ($) {
    // markers

    $.extend(mejs.MepDefaults, {
        markerColor: '#E9BC3D', //default marker color
        markers: [],
        markerCallback: function () {

        }
    });

    $.extend(MediaElementPlayer.prototype, {
        buildmarkers: function (player, controls, layers, media) {
            var t = this,
                i = 0,
                currentPos = -1,
                currentMarker = -1,
                lastPlayPos = -1, //Track backward seek
                lastMarkerCallBack = -1; //Prevents successive firing of callbacks

            for (i = 0; i < player.options.markers.length; ++i) {
                controls.find('.mejs-time-total').append('<span class="mejs-time-marker"></span>');
            }

            media.addEventListener('durationchange', function (e) {
                player.setmarkers(controls);
            });
            media.addEventListener('timeupdate', function (e) {
                currentPos = Math.floor(media.currentTime);
                if (lastPlayPos > currentPos) {
                    if (lastMarkerCallBack > currentPos) {
                        lastMarkerCallBack = -1;
                    }
                } else {
                    lastPlayPos = currentPos;
                }

                for (i = 0; i < player.options.markers.length; ++i) {
                    currentMarker = Math.floor(player.options.markers[i]); 
                    if (currentPos === currentMarker && currentMarker !== lastMarkerCallBack) {
                        player.options.markerCallback(media, media.currentTime); //Fires the callback function
                        lastMarkerCallBack = currentMarker;
                    }
                }

            }, false);

        },
        setmarkers: function (controls) {
            var t = this,
                i = 0,
                left;

            for (i = 0; i < t.options.markers.length; ++i) {
                if (Math.floor(t.options.markers[i]) <= t.media.duration && Math.floor(t.options.markers[i]) >= 0) {
                    left = 100 * Math.floor(t.options.markers[i]) / t.media.duration;
                    $(controls.find('.mejs-time-marker')[i]).css({
                        "width": "1px",
                        "left": left+"%",
                        "background": t.options.markerColor
                    });
                }
            }

        }
    });
})(mejs.$);
/* jQuery treeTable Plugin 2.2.2 - http://ludo.cubicphuse.nl/jquery-plugins/treeTable/ */
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  
  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);
    
    return this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Initialize root nodes only if possible
        if(!options.expandable || $(this)[0].className.search("child-of-") == -1) {
          initialize($(this));
        } else if(options.initialState == "collapsed") {
          this.style.display = "none"; // Performance! $(this).hide() is slow...
        }
      });
    });
  };
  
  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    treeColumn: 0
  };
  
  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    $(this).addClass("collapsed");
    
    childrenOf($(this)).each(function() {
      if(!$(this).hasClass("collapsed")) {
        $(this).collapse();
      }
      
      $(this).hide();
    });
    
    return this;
  };
  
  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    $(this).removeClass("collapsed").addClass("expanded");
    
    childrenOf($(this)).each(function() {
      initialize($(this));
      
      if($(this).is(".expanded.parent")) {
        $(this).expand();
      }
      
      $(this).show();
    });
    
    return this;
  };
  
  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);
    
    var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });
    
    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation
      
      if(parent) { node.removeClass(options.childPrefix + parent[0].id); }
      
      node.addClass(options.childPrefix + destination.id);
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);
    }
    
    return this;
  };
  
  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };
  
  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).removeClass("expanded").collapse();
    }
    
    return this;
  };
  
  // === Private functions
  
  function ancestorsOf(node) {
    var ancestors = [];
    while(node = parentOf(node)) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  };
  
  function childrenOf(node) {
    return $("table.treeTable tbody tr." + options.childPrefix + node[0].id);
  };
  
  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    var padding = parseInt(cell.css("padding-left"), 10) + value;
    
    cell.css("padding-left", + padding + "px");
    
    childrenOf(node).each(function() {
      indent($(this), value);
    });
  };
  
  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");
      
      var childNodes = childrenOf(node);
      
      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }
      
      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = parseInt(cell.css("padding-left"), 10) + options.indent;
        
        childNodes.each(function() {
          $($(this).children("td")[options.treeColumn]).css("padding-left", padding + "px");
        });
        
        if(options.expandable) {
          cell.prepend('<span style="padding-left: ' + options.indent + 'px" class="expander"></span>');
          $(cell[0].firstChild).click(function() { node.toggleBranch(); });
          
          if(options.clickableNodeNames) {
            $(cell).css('cursor', 'pointer');
            $(cell).click(function(e) {
              // Don't double-toggle if the click is on the existing expander icon
              if (e.target.className != 'expander') {
                node.toggleBranch();
              }
            });
          }
          
          // Check for a class set explicitly by the user, otherwise set the default class
          if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
            node.addClass(options.initialState);
          }

          if(node.hasClass("expanded")) {
            node.expand();
          }
        }
      }
    }
  };
  
  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() { move($(this), node[0]); });
  };
  
  function parentOf(node) {
    var classNames = node[0].className.split(' ');
    
    for(key in classNames) {
      if(classNames[key].match("child-of-")) {
        return $("#" + classNames[key].substring(9));
      }
    }
  };
})(jQuery);
;(function ($) {
  $(function () {
    // The people that made me do this deserve the most special sort
    // of hell...
    function warn () {
      var flashArea = $('.flash');
      if (flashArea.has('.error').length === 0) {
        flashArea.append('<div class="error"></div>');
      }

      var error = $('<div class="js-require-error"></div>');
      error.append($('.js-require-warning').html());

      if (flashArea.has('.error .js-require-error' ).length === 0) {
        flashArea.find('.error').append(error);
      }
    }

    $('form input[type="checkbox"].js-require-check').closest('form').submit(function(event) {
      var checkbox = $(event.target).
      find('input[type="checkbox"].js-require-check');

      var checked = checkbox.prop('checked');
      if (!checked) { checked = false; }
      if (checked === false) {
        event.preventDefault();
        warn();
        return false;
      }
    });
  });
}(jQuery));
function build_attachables_grid_filters ( options_hash ) {
  var filter_array = [
    {
      field: 'title',
      label: 'Title',
      type:  'Simple',
      advanced: true,
      hidden: options_hash.hide_title_filter
    },
    {
      field: 'tags',
      label: 'View All Correspondence Types',
      type:  'Select',
      hidden: options_hash.hide_tags_filter,
      excluded_tags: options_hash.excluded_tags
    },
    {
      field: 'associated_with',
      label: 'Search by Association',
      type:  'TypeAhead',
      advanced: true,
      hidden: options_hash.hide_associated_with_filter
    }
  ];

  return filter_array;
}


function build_attachables_grid_columns ( options_hash ) {
  var column_array = [
    {
      field: 'id',
      label: 'id',
      hidden: true
    },
    {
      field: 'created_at',
      label: 'Import Date',
      width: 25,
      hidden: options_hash.hide_created_at_column
    },
    {
      field: 'effective_date',
      label: 'Date',
      width: 25,
      hidden: options_hash.hide_effective_date_column
    },
    {
      field: 'title',
      label: 'Title',
      width: 100,
      hidden: options_hash.hide_title_column
    },
    {
      field: 'associated_with',
      label: 'Associated With',
      width: 80,
      search: false,
      sortable: false,
      hidden: options_hash.hide_associated_with_column
    },
    {
      field: 'type',
      label: 'Type',
      width: 25,
      hidden: options_hash.hide_type_column
    },
    {
      field: 'tags',
      label: 'Tags',
      width: 100,
      hidden: options_hash.hide_tag_column
    },
    {
      field: 'product_associations',
      label: 'Product',
      width: 100,
      hidden: !options_hash.show_product_column
    }
  ];

  return column_array;
};
/**
 * @licstart The following is the entire license notice for the
 * JavaScript code in this page
 *
 * Copyright 2023 Mozilla Foundation
 *
 * 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.
 *
 * @licend The above is the entire license notice for the
 * JavaScript code in this page
 */

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("pdfjs-dist/build/pdf", [], factory);
	else if(typeof exports === 'object')
		exports["pdfjs-dist/build/pdf"] = factory();
	else
		root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
})(globalThis, () => {
return /******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ([
/* 0 */,
/* 1 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
exports.arrayByteLength = arrayByteLength;
exports.arraysToBytes = arraysToBytes;
exports.assert = assert;
exports.bytesToString = bytesToString;
exports.createPromiseCapability = createPromiseCapability;
exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
exports.getModificationDate = getModificationDate;
exports.getVerbosityLevel = getVerbosityLevel;
exports.info = info;
exports.isArrayBuffer = isArrayBuffer;
exports.isArrayEqual = isArrayEqual;
exports.objectFromMap = objectFromMap;
exports.objectSize = objectSize;
exports.setVerbosityLevel = setVerbosityLevel;
exports.shadow = shadow;
exports.string32 = string32;
exports.stringToBytes = stringToBytes;
exports.stringToPDFString = stringToPDFString;
exports.stringToUTF8String = stringToUTF8String;
exports.unreachable = unreachable;
exports.utf8StringToString = utf8StringToString;
exports.warn = warn;
;
const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
const LINE_FACTOR = 1.35;
exports.LINE_FACTOR = LINE_FACTOR;
const LINE_DESCENT_FACTOR = 0.35;
exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
exports.BASELINE_FACTOR = BASELINE_FACTOR;
const RenderingIntentFlag = {
  ANY: 0x01,
  DISPLAY: 0x02,
  PRINT: 0x04,
  SAVE: 0x08,
  ANNOTATIONS_FORMS: 0x10,
  ANNOTATIONS_STORAGE: 0x20,
  ANNOTATIONS_DISABLE: 0x40,
  OPLIST: 0x100
};
exports.RenderingIntentFlag = RenderingIntentFlag;
const AnnotationMode = {
  DISABLE: 0,
  ENABLE: 1,
  ENABLE_FORMS: 2,
  ENABLE_STORAGE: 3
};
exports.AnnotationMode = AnnotationMode;
const AnnotationEditorPrefix = "pdfjs_internal_editor_";
exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
const AnnotationEditorType = {
  DISABLE: -1,
  NONE: 0,
  FREETEXT: 3,
  INK: 15
};
exports.AnnotationEditorType = AnnotationEditorType;
const AnnotationEditorParamsType = {
  FREETEXT_SIZE: 1,
  FREETEXT_COLOR: 2,
  FREETEXT_OPACITY: 3,
  INK_COLOR: 11,
  INK_THICKNESS: 12,
  INK_OPACITY: 13
};
exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
const PermissionFlag = {
  PRINT: 0x04,
  MODIFY_CONTENTS: 0x08,
  COPY: 0x10,
  MODIFY_ANNOTATIONS: 0x20,
  FILL_INTERACTIVE_FORMS: 0x100,
  COPY_FOR_ACCESSIBILITY: 0x200,
  ASSEMBLE: 0x400,
  PRINT_HIGH_QUALITY: 0x800
};
exports.PermissionFlag = PermissionFlag;
const TextRenderingMode = {
  FILL: 0,
  STROKE: 1,
  FILL_STROKE: 2,
  INVISIBLE: 3,
  FILL_ADD_TO_PATH: 4,
  STROKE_ADD_TO_PATH: 5,
  FILL_STROKE_ADD_TO_PATH: 6,
  ADD_TO_PATH: 7,
  FILL_STROKE_MASK: 3,
  ADD_TO_PATH_FLAG: 4
};
exports.TextRenderingMode = TextRenderingMode;
const ImageKind = {
  GRAYSCALE_1BPP: 1,
  RGB_24BPP: 2,
  RGBA_32BPP: 3
};
exports.ImageKind = ImageKind;
const AnnotationType = {
  TEXT: 1,
  LINK: 2,
  FREETEXT: 3,
  LINE: 4,
  SQUARE: 5,
  CIRCLE: 6,
  POLYGON: 7,
  POLYLINE: 8,
  HIGHLIGHT: 9,
  UNDERLINE: 10,
  SQUIGGLY: 11,
  STRIKEOUT: 12,
  STAMP: 13,
  CARET: 14,
  INK: 15,
  POPUP: 16,
  FILEATTACHMENT: 17,
  SOUND: 18,
  MOVIE: 19,
  WIDGET: 20,
  SCREEN: 21,
  PRINTERMARK: 22,
  TRAPNET: 23,
  WATERMARK: 24,
  THREED: 25,
  REDACT: 26
};
exports.AnnotationType = AnnotationType;
const AnnotationStateModelType = {
  MARKED: "Marked",
  REVIEW: "Review"
};
exports.AnnotationStateModelType = AnnotationStateModelType;
const AnnotationMarkedState = {
  MARKED: "Marked",
  UNMARKED: "Unmarked"
};
exports.AnnotationMarkedState = AnnotationMarkedState;
const AnnotationReviewState = {
  ACCEPTED: "Accepted",
  REJECTED: "Rejected",
  CANCELLED: "Cancelled",
  COMPLETED: "Completed",
  NONE: "None"
};
exports.AnnotationReviewState = AnnotationReviewState;
const AnnotationReplyType = {
  GROUP: "Group",
  REPLY: "R"
};
exports.AnnotationReplyType = AnnotationReplyType;
const AnnotationFlag = {
  INVISIBLE: 0x01,
  HIDDEN: 0x02,
  PRINT: 0x04,
  NOZOOM: 0x08,
  NOROTATE: 0x10,
  NOVIEW: 0x20,
  READONLY: 0x40,
  LOCKED: 0x80,
  TOGGLENOVIEW: 0x100,
  LOCKEDCONTENTS: 0x200
};
exports.AnnotationFlag = AnnotationFlag;
const AnnotationFieldFlag = {
  READONLY: 0x0000001,
  REQUIRED: 0x0000002,
  NOEXPORT: 0x0000004,
  MULTILINE: 0x0001000,
  PASSWORD: 0x0002000,
  NOTOGGLETOOFF: 0x0004000,
  RADIO: 0x0008000,
  PUSHBUTTON: 0x0010000,
  COMBO: 0x0020000,
  EDIT: 0x0040000,
  SORT: 0x0080000,
  FILESELECT: 0x0100000,
  MULTISELECT: 0x0200000,
  DONOTSPELLCHECK: 0x0400000,
  DONOTSCROLL: 0x0800000,
  COMB: 0x1000000,
  RICHTEXT: 0x2000000,
  RADIOSINUNISON: 0x2000000,
  COMMITONSELCHANGE: 0x4000000
};
exports.AnnotationFieldFlag = AnnotationFieldFlag;
const AnnotationBorderStyleType = {
  SOLID: 1,
  DASHED: 2,
  BEVELED: 3,
  INSET: 4,
  UNDERLINE: 5
};
exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
const AnnotationActionEventType = {
  E: "Mouse Enter",
  X: "Mouse Exit",
  D: "Mouse Down",
  U: "Mouse Up",
  Fo: "Focus",
  Bl: "Blur",
  PO: "PageOpen",
  PC: "PageClose",
  PV: "PageVisible",
  PI: "PageInvisible",
  K: "Keystroke",
  F: "Format",
  V: "Validate",
  C: "Calculate"
};
exports.AnnotationActionEventType = AnnotationActionEventType;
const DocumentActionEventType = {
  WC: "WillClose",
  WS: "WillSave",
  DS: "DidSave",
  WP: "WillPrint",
  DP: "DidPrint"
};
exports.DocumentActionEventType = DocumentActionEventType;
const PageActionEventType = {
  O: "PageOpen",
  C: "PageClose"
};
exports.PageActionEventType = PageActionEventType;
const VerbosityLevel = {
  ERRORS: 0,
  WARNINGS: 1,
  INFOS: 5
};
exports.VerbosityLevel = VerbosityLevel;
const CMapCompressionType = {
  NONE: 0,
  BINARY: 1
};
exports.CMapCompressionType = CMapCompressionType;
const OPS = {
  dependency: 1,
  setLineWidth: 2,
  setLineCap: 3,
  setLineJoin: 4,
  setMiterLimit: 5,
  setDash: 6,
  setRenderingIntent: 7,
  setFlatness: 8,
  setGState: 9,
  save: 10,
  restore: 11,
  transform: 12,
  moveTo: 13,
  lineTo: 14,
  curveTo: 15,
  curveTo2: 16,
  curveTo3: 17,
  closePath: 18,
  rectangle: 19,
  stroke: 20,
  closeStroke: 21,
  fill: 22,
  eoFill: 23,
  fillStroke: 24,
  eoFillStroke: 25,
  closeFillStroke: 26,
  closeEOFillStroke: 27,
  endPath: 28,
  clip: 29,
  eoClip: 30,
  beginText: 31,
  endText: 32,
  setCharSpacing: 33,
  setWordSpacing: 34,
  setHScale: 35,
  setLeading: 36,
  setFont: 37,
  setTextRenderingMode: 38,
  setTextRise: 39,
  moveText: 40,
  setLeadingMoveText: 41,
  setTextMatrix: 42,
  nextLine: 43,
  showText: 44,
  showSpacedText: 45,
  nextLineShowText: 46,
  nextLineSetSpacingShowText: 47,
  setCharWidth: 48,
  setCharWidthAndBounds: 49,
  setStrokeColorSpace: 50,
  setFillColorSpace: 51,
  setStrokeColor: 52,
  setStrokeColorN: 53,
  setFillColor: 54,
  setFillColorN: 55,
  setStrokeGray: 56,
  setFillGray: 57,
  setStrokeRGBColor: 58,
  setFillRGBColor: 59,
  setStrokeCMYKColor: 60,
  setFillCMYKColor: 61,
  shadingFill: 62,
  beginInlineImage: 63,
  beginImageData: 64,
  endInlineImage: 65,
  paintXObject: 66,
  markPoint: 67,
  markPointProps: 68,
  beginMarkedContent: 69,
  beginMarkedContentProps: 70,
  endMarkedContent: 71,
  beginCompat: 72,
  endCompat: 73,
  paintFormXObjectBegin: 74,
  paintFormXObjectEnd: 75,
  beginGroup: 76,
  endGroup: 77,
  beginAnnotation: 80,
  endAnnotation: 81,
  paintImageMaskXObject: 83,
  paintImageMaskXObjectGroup: 84,
  paintImageXObject: 85,
  paintInlineImageXObject: 86,
  paintInlineImageXObjectGroup: 87,
  paintImageXObjectRepeat: 88,
  paintImageMaskXObjectRepeat: 89,
  paintSolidColorImageMask: 90,
  constructPath: 91
};
exports.OPS = OPS;
const UNSUPPORTED_FEATURES = {
  forms: "forms",
  javaScript: "javaScript",
  signatures: "signatures",
  smask: "smask",
  shadingPattern: "shadingPattern",
  errorTilingPattern: "errorTilingPattern",
  errorExtGState: "errorExtGState",
  errorXObject: "errorXObject",
  errorFontLoadType3: "errorFontLoadType3",
  errorFontState: "errorFontState",
  errorFontMissing: "errorFontMissing",
  errorFontTranslate: "errorFontTranslate",
  errorColorSpace: "errorColorSpace",
  errorOperatorList: "errorOperatorList",
  errorFontToUnicode: "errorFontToUnicode",
  errorFontLoadNative: "errorFontLoadNative",
  errorFontBuildPath: "errorFontBuildPath",
  errorFontGetPath: "errorFontGetPath",
  errorMarkedContent: "errorMarkedContent",
  errorContentSubStream: "errorContentSubStream"
};
exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
const PasswordResponses = {
  NEED_PASSWORD: 1,
  INCORRECT_PASSWORD: 2
};
exports.PasswordResponses = PasswordResponses;
let verbosity = VerbosityLevel.WARNINGS;
function setVerbosityLevel(level) {
  if (Number.isInteger(level)) {
    verbosity = level;
  }
}
function getVerbosityLevel() {
  return verbosity;
}
function info(msg) {
  if (verbosity >= VerbosityLevel.INFOS) {
    console.log(`Info: ${msg}`);
  }
}
function warn(msg) {
  if (verbosity >= VerbosityLevel.WARNINGS) {
    console.log(`Warning: ${msg}`);
  }
}
function unreachable(msg) {
  throw new Error(msg);
}
function assert(cond, msg) {
  if (!cond) {
    unreachable(msg);
  }
}
function _isValidProtocol(url) {
  if (!url) {
    return false;
  }
  switch (url.protocol) {
    case "http:":
    case "https:":
    case "ftp:":
    case "mailto:":
    case "tel:":
      return true;
    default:
      return false;
  }
}
function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  if (!url) {
    return null;
  }
  try {
    if (options && typeof url === "string") {
      if (options.addDefaultProtocol && url.startsWith("www.")) {
        const dots = url.match(/\./g);
        if (dots && dots.length >= 2) {
          url = `http://${url}`;
        }
      }
      if (options.tryConvertEncoding) {
        try {
          url = stringToUTF8String(url);
        } catch (ex) {}
      }
    }
    const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
    if (_isValidProtocol(absoluteUrl)) {
      return absoluteUrl;
    }
  } catch (ex) {}
  return null;
}
function shadow(obj, prop, value, nonSerializable = false) {
  Object.defineProperty(obj, prop, {
    value,
    enumerable: !nonSerializable,
    configurable: true,
    writable: false
  });
  return value;
}
const BaseException = function BaseExceptionClosure() {
  function BaseException(message, name) {
    if (this.constructor === BaseException) {
      unreachable("Cannot initialize BaseException.");
    }
    this.message = message;
    this.name = name;
  }
  BaseException.prototype = new Error();
  BaseException.constructor = BaseException;
  return BaseException;
}();
exports.BaseException = BaseException;
class PasswordException extends BaseException {
  constructor(msg, code) {
    super(msg, "PasswordException");
    this.code = code;
  }
}
exports.PasswordException = PasswordException;
class UnknownErrorException extends BaseException {
  constructor(msg, details) {
    super(msg, "UnknownErrorException");
    this.details = details;
  }
}
exports.UnknownErrorException = UnknownErrorException;
class InvalidPDFException extends BaseException {
  constructor(msg) {
    super(msg, "InvalidPDFException");
  }
}
exports.InvalidPDFException = InvalidPDFException;
class MissingPDFException extends BaseException {
  constructor(msg) {
    super(msg, "MissingPDFException");
  }
}
exports.MissingPDFException = MissingPDFException;
class UnexpectedResponseException extends BaseException {
  constructor(msg, status) {
    super(msg, "UnexpectedResponseException");
    this.status = status;
  }
}
exports.UnexpectedResponseException = UnexpectedResponseException;
class FormatError extends BaseException {
  constructor(msg) {
    super(msg, "FormatError");
  }
}
exports.FormatError = FormatError;
class AbortException extends BaseException {
  constructor(msg) {
    super(msg, "AbortException");
  }
}
exports.AbortException = AbortException;
function bytesToString(bytes) {
  if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
    unreachable("Invalid argument for bytesToString");
  }
  const length = bytes.length;
  const MAX_ARGUMENT_COUNT = 8192;
  if (length < MAX_ARGUMENT_COUNT) {
    return String.fromCharCode.apply(null, bytes);
  }
  const strBuf = [];
  for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
    const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
    const chunk = bytes.subarray(i, chunkEnd);
    strBuf.push(String.fromCharCode.apply(null, chunk));
  }
  return strBuf.join("");
}
function stringToBytes(str) {
  if (typeof str !== "string") {
    unreachable("Invalid argument for stringToBytes");
  }
  const length = str.length;
  const bytes = new Uint8Array(length);
  for (let i = 0; i < length; ++i) {
    bytes[i] = str.charCodeAt(i) & 0xff;
  }
  return bytes;
}
function arrayByteLength(arr) {
  if (arr.length !== undefined) {
    return arr.length;
  }
  if (arr.byteLength !== undefined) {
    return arr.byteLength;
  }
  unreachable("Invalid argument for arrayByteLength");
}
function arraysToBytes(arr) {
  const length = arr.length;
  if (length === 1 && arr[0] instanceof Uint8Array) {
    return arr[0];
  }
  let resultLength = 0;
  for (let i = 0; i < length; i++) {
    resultLength += arrayByteLength(arr[i]);
  }
  let pos = 0;
  const data = new Uint8Array(resultLength);
  for (let i = 0; i < length; i++) {
    let item = arr[i];
    if (!(item instanceof Uint8Array)) {
      if (typeof item === "string") {
        item = stringToBytes(item);
      } else {
        item = new Uint8Array(item);
      }
    }
    const itemLength = item.byteLength;
    data.set(item, pos);
    pos += itemLength;
  }
  return data;
}
function string32(value) {
  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
}
function objectSize(obj) {
  return Object.keys(obj).length;
}
function objectFromMap(map) {
  const obj = Object.create(null);
  for (const [key, value] of map) {
    obj[key] = value;
  }
  return obj;
}
function isLittleEndian() {
  const buffer8 = new Uint8Array(4);
  buffer8[0] = 1;
  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  return view32[0] === 1;
}
function isEvalSupported() {
  try {
    new Function("");
    return true;
  } catch (e) {
    return false;
  }
}
class FeatureTest {
  static get isLittleEndian() {
    return shadow(this, "isLittleEndian", isLittleEndian());
  }
  static get isEvalSupported() {
    return shadow(this, "isEvalSupported", isEvalSupported());
  }
  static get isOffscreenCanvasSupported() {
    return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  }
  static get platform() {
    if (typeof navigator === "undefined") {
      return shadow(this, "platform", {
        isWin: false,
        isMac: false
      });
    }
    return shadow(this, "platform", {
      isWin: navigator.platform.includes("Win"),
      isMac: navigator.platform.includes("Mac")
    });
  }
}
exports.FeatureTest = FeatureTest;
const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
class Util {
  static makeHexColor(r, g, b) {
    return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  }
  static scaleMinMax(transform, minMax) {
    let temp;
    if (transform[0]) {
      if (transform[0] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[1];
        minMax[1] = temp;
      }
      minMax[0] *= transform[0];
      minMax[1] *= transform[0];
      if (transform[3] < 0) {
        temp = minMax[2];
        minMax[2] = minMax[3];
        minMax[3] = temp;
      }
      minMax[2] *= transform[3];
      minMax[3] *= transform[3];
    } else {
      temp = minMax[0];
      minMax[0] = minMax[2];
      minMax[2] = temp;
      temp = minMax[1];
      minMax[1] = minMax[3];
      minMax[3] = temp;
      if (transform[1] < 0) {
        temp = minMax[2];
        minMax[2] = minMax[3];
        minMax[3] = temp;
      }
      minMax[2] *= transform[1];
      minMax[3] *= transform[1];
      if (transform[2] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[1];
        minMax[1] = temp;
      }
      minMax[0] *= transform[2];
      minMax[1] *= transform[2];
    }
    minMax[0] += transform[4];
    minMax[1] += transform[4];
    minMax[2] += transform[5];
    minMax[3] += transform[5];
  }
  static transform(m1, m2) {
    return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  }
  static applyTransform(p, m) {
    const xt = p[0] * m[0] + p[1] * m[2] + m[4];
    const yt = p[0] * m[1] + p[1] * m[3] + m[5];
    return [xt, yt];
  }
  static applyInverseTransform(p, m) {
    const d = m[0] * m[3] - m[1] * m[2];
    const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
    const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
    return [xt, yt];
  }
  static getAxialAlignedBoundingBox(r, m) {
    const p1 = Util.applyTransform(r, m);
    const p2 = Util.applyTransform(r.slice(2, 4), m);
    const p3 = Util.applyTransform([r[0], r[3]], m);
    const p4 = Util.applyTransform([r[2], r[1]], m);
    return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  }
  static inverseTransform(m) {
    const d = m[0] * m[3] - m[1] * m[2];
    return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  }
  static singularValueDecompose2dScale(m) {
    const transpose = [m[0], m[2], m[1], m[3]];
    const a = m[0] * transpose[0] + m[1] * transpose[2];
    const b = m[0] * transpose[1] + m[1] * transpose[3];
    const c = m[2] * transpose[0] + m[3] * transpose[2];
    const d = m[2] * transpose[1] + m[3] * transpose[3];
    const first = (a + d) / 2;
    const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
    const sx = first + second || 1;
    const sy = first - second || 1;
    return [Math.sqrt(sx), Math.sqrt(sy)];
  }
  static normalizeRect(rect) {
    const r = rect.slice(0);
    if (rect[0] > rect[2]) {
      r[0] = rect[2];
      r[2] = rect[0];
    }
    if (rect[1] > rect[3]) {
      r[1] = rect[3];
      r[3] = rect[1];
    }
    return r;
  }
  static intersect(rect1, rect2) {
    const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
    const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
    if (xLow > xHigh) {
      return null;
    }
    const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
    const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
    if (yLow > yHigh) {
      return null;
    }
    return [xLow, yLow, xHigh, yHigh];
  }
  static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
    const tvalues = [],
      bounds = [[], []];
    let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
    for (let i = 0; i < 2; ++i) {
      if (i === 0) {
        b = 6 * x0 - 12 * x1 + 6 * x2;
        a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
        c = 3 * x1 - 3 * x0;
      } else {
        b = 6 * y0 - 12 * y1 + 6 * y2;
        a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
        c = 3 * y1 - 3 * y0;
      }
      if (Math.abs(a) < 1e-12) {
        if (Math.abs(b) < 1e-12) {
          continue;
        }
        t = -c / b;
        if (0 < t && t < 1) {
          tvalues.push(t);
        }
        continue;
      }
      b2ac = b * b - 4 * c * a;
      sqrtb2ac = Math.sqrt(b2ac);
      if (b2ac < 0) {
        continue;
      }
      t1 = (-b + sqrtb2ac) / (2 * a);
      if (0 < t1 && t1 < 1) {
        tvalues.push(t1);
      }
      t2 = (-b - sqrtb2ac) / (2 * a);
      if (0 < t2 && t2 < 1) {
        tvalues.push(t2);
      }
    }
    let j = tvalues.length,
      mt;
    const jlen = j;
    while (j--) {
      t = tvalues[j];
      mt = 1 - t;
      bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
      bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
    }
    bounds[0][jlen] = x0;
    bounds[1][jlen] = y0;
    bounds[0][jlen + 1] = x3;
    bounds[1][jlen + 1] = y3;
    bounds[0].length = bounds[1].length = jlen + 2;
    return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  }
}
exports.Util = Util;
const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
function stringToPDFString(str) {
  if (str[0] >= "\xEF") {
    let encoding;
    if (str[0] === "\xFE" && str[1] === "\xFF") {
      encoding = "utf-16be";
    } else if (str[0] === "\xFF" && str[1] === "\xFE") {
      encoding = "utf-16le";
    } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
      encoding = "utf-8";
    }
    if (encoding) {
      try {
        const decoder = new TextDecoder(encoding, {
          fatal: true
        });
        const buffer = stringToBytes(str);
        return decoder.decode(buffer);
      } catch (ex) {
        warn(`stringToPDFString: "${ex}".`);
      }
    }
  }
  const strBuf = [];
  for (let i = 0, ii = str.length; i < ii; i++) {
    const code = PDFStringTranslateTable[str.charCodeAt(i)];
    strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  }
  return strBuf.join("");
}
function stringToUTF8String(str) {
  return decodeURIComponent(escape(str));
}
function utf8StringToString(str) {
  return unescape(encodeURIComponent(str));
}
function isArrayBuffer(v) {
  return typeof v === "object" && v !== null && v.byteLength !== undefined;
}
function isArrayEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0, ii = arr1.length; i < ii; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}
function getModificationDate(date = new Date()) {
  const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
  return buffer.join("");
}
function createPromiseCapability() {
  const capability = Object.create(null);
  let isSettled = false;
  Object.defineProperty(capability, "settled", {
    get() {
      return isSettled;
    }
  });
  capability.promise = new Promise(function (resolve, reject) {
    capability.resolve = function (data) {
      isSettled = true;
      resolve(data);
    };
    capability.reject = function (reason) {
      isSettled = true;
      reject(reason);
    };
  });
  return capability;
}

/***/ }),
/* 2 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
exports.getDocument = getDocument;
exports.version = void 0;
var _util = __w_pdfjs_require__(1);
var _annotation_storage = __w_pdfjs_require__(3);
var _display_utils = __w_pdfjs_require__(6);
var _font_loader = __w_pdfjs_require__(9);
var _canvas = __w_pdfjs_require__(11);
var _worker_options = __w_pdfjs_require__(14);
var _is_node = __w_pdfjs_require__(10);
var _message_handler = __w_pdfjs_require__(15);
var _metadata = __w_pdfjs_require__(16);
var _optional_content_config = __w_pdfjs_require__(17);
var _transport_stream = __w_pdfjs_require__(18);
var _xfa_text = __w_pdfjs_require__(19);
const DEFAULT_RANGE_CHUNK_SIZE = 65536;
const RENDERING_CANCELLED_TIMEOUT = 100;
let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
exports.DefaultCanvasFactory = DefaultCanvasFactory;
let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
if (_is_node.isNodeJS) {
  const {
    NodeCanvasFactory,
    NodeCMapReaderFactory,
    NodeStandardFontDataFactory
  } = __w_pdfjs_require__(20);
  exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
  exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
  exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
}
let createPDFNetworkStream;
{
  if (_is_node.isNodeJS) {
    const {
      PDFNodeStream
    } = __w_pdfjs_require__(21);
    createPDFNetworkStream = params => {
      return new PDFNodeStream(params);
    };
  } else {
    const {
      PDFNetworkStream
    } = __w_pdfjs_require__(24);
    const {
      PDFFetchStream
    } = __w_pdfjs_require__(25);
    createPDFNetworkStream = params => {
      return (0, _display_utils.isValidFetchUrl)(params.url) ? new PDFFetchStream(params) : new PDFNetworkStream(params);
    };
  }
}
function getDocument(src) {
  if (typeof src === "string" || src instanceof URL) {
    src = {
      url: src
    };
  } else if ((0, _util.isArrayBuffer)(src)) {
    src = {
      data: src
    };
  } else if (src instanceof PDFDataRangeTransport) {
    (0, _display_utils.deprecated)("`PDFDataRangeTransport`-instance, " + "please use a parameter object with `range`-property instead.");
    src = {
      range: src
    };
  } else {
    if (typeof src !== "object") {
      throw new Error("Invalid parameter in getDocument, " + "need either string, URL, TypedArray, or parameter object.");
    }
  }
  if (!src.url && !src.data && !src.range) {
    throw new Error("Invalid parameter object: need either .data, .range or .url");
  }
  const task = new PDFDocumentLoadingTask();
  const url = src.url ? getUrlProp(src.url) : null;
  const data = src.data ? getDataProp(src.data) : null;
  const httpHeaders = src.httpHeaders || null;
  const withCredentials = src.withCredentials === true;
  const password = src.password ?? null;
  const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null;
  const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : DEFAULT_RANGE_CHUNK_SIZE;
  let worker = src.worker instanceof PDFWorker ? src.worker : null;
  const verbosity = src.verbosity;
  const docBaseUrl = typeof src.docBaseUrl === "string" && !(0, _display_utils.isDataScheme)(src.docBaseUrl) ? src.docBaseUrl : null;
  const cMapUrl = typeof src.cMapUrl === "string" ? src.cMapUrl : null;
  const cMapPacked = src.cMapPacked !== false;
  const CMapReaderFactory = src.CMapReaderFactory || DefaultCMapReaderFactory;
  const standardFontDataUrl = typeof src.standardFontDataUrl === "string" ? src.standardFontDataUrl : null;
  const StandardFontDataFactory = src.StandardFontDataFactory || DefaultStandardFontDataFactory;
  const ignoreErrors = src.stopAtErrors !== true;
  const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1;
  const isEvalSupported = src.isEvalSupported !== false;
  const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !_is_node.isNodeJS;
  const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : _is_node.isNodeJS;
  const fontExtraProperties = src.fontExtraProperties === true;
  const enableXfa = src.enableXfa === true;
  const ownerDocument = src.ownerDocument || globalThis.document;
  const disableRange = src.disableRange === true;
  const disableStream = src.disableStream === true;
  const disableAutoFetch = src.disableAutoFetch === true;
  const pdfBug = src.pdfBug === true;
  const length = rangeTransport ? rangeTransport.length : src.length ?? NaN;
  const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !_is_node.isNodeJS && !disableFontFace;
  const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : CMapReaderFactory === _display_utils.DOMCMapReaderFactory && StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory && (0, _display_utils.isValidFetchUrl)(cMapUrl, document.baseURI) && (0, _display_utils.isValidFetchUrl)(standardFontDataUrl, document.baseURI);
  const styleElement = null;
  (0, _util.setVerbosityLevel)(verbosity);
  const transportFactory = useWorkerFetch ? null : {
    cMapReaderFactory: new CMapReaderFactory({
      baseUrl: cMapUrl,
      isCompressed: cMapPacked
    }),
    standardFontDataFactory: new StandardFontDataFactory({
      baseUrl: standardFontDataUrl
    })
  };
  if (!worker) {
    const workerParams = {
      verbosity,
      port: _worker_options.GlobalWorkerOptions.workerPort
    };
    worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
    task._worker = worker;
  }
  const docId = task.docId;
  const fetchDocParams = {
    docId,
    apiVersion: '3.4.50',
    data,
    password,
    disableAutoFetch,
    rangeChunkSize,
    length,
    docBaseUrl,
    enableXfa,
    evaluatorOptions: {
      maxImageSize,
      disableFontFace,
      ignoreErrors,
      isEvalSupported,
      isOffscreenCanvasSupported,
      fontExtraProperties,
      useSystemFonts,
      cMapUrl: useWorkerFetch ? cMapUrl : null,
      standardFontDataUrl: useWorkerFetch ? standardFontDataUrl : null
    }
  };
  const transportParams = {
    ignoreErrors,
    isEvalSupported,
    disableFontFace,
    fontExtraProperties,
    enableXfa,
    ownerDocument,
    disableAutoFetch,
    pdfBug,
    styleElement
  };
  worker.promise.then(function () {
    if (task.destroyed) {
      throw new Error("Loading aborted");
    }
    const workerIdPromise = _fetchDocument(worker, fetchDocParams);
    const networkStreamPromise = new Promise(function (resolve) {
      let networkStream;
      if (rangeTransport) {
        networkStream = new _transport_stream.PDFDataTransportStream({
          length,
          initialData: rangeTransport.initialData,
          progressiveDone: rangeTransport.progressiveDone,
          contentDispositionFilename: rangeTransport.contentDispositionFilename,
          disableRange,
          disableStream
        }, rangeTransport);
      } else if (!data) {
        networkStream = createPDFNetworkStream({
          url,
          length,
          httpHeaders,
          withCredentials,
          rangeChunkSize,
          disableRange,
          disableStream
        });
      }
      resolve(networkStream);
    });
    return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
      if (task.destroyed) {
        throw new Error("Loading aborted");
      }
      const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
      const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory);
      task._transport = transport;
      messageHandler.send("Ready", null);
    });
  }).catch(task._capability.reject);
  return task;
}
async function _fetchDocument(worker, source) {
  if (worker.destroyed) {
    throw new Error("Worker was destroyed");
  }
  const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", source, source.data ? [source.data.buffer] : null);
  if (worker.destroyed) {
    throw new Error("Worker was destroyed");
  }
  return workerId;
}
function getUrlProp(val) {
  if (val instanceof URL) {
    return val.href;
  }
  try {
    return new URL(val, window.location).href;
  } catch (ex) {
    if (_is_node.isNodeJS && typeof val === "string") {
      return val;
    }
  }
  throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
}
function getDataProp(val) {
  if (_is_node.isNodeJS && typeof Buffer !== "undefined" && val instanceof Buffer) {
    return new Uint8Array(val);
  } else if (val instanceof Uint8Array && val.byteLength === val.buffer.byteLength) {
    return val;
  } else if (typeof val === "string") {
    return (0, _util.stringToBytes)(val);
  } else if (typeof val === "object" && !isNaN(val?.length) || (0, _util.isArrayBuffer)(val)) {
    return new Uint8Array(val);
  }
  throw new Error("Invalid PDF binary data: either TypedArray, " + "string, or array-like object is expected in the data property.");
}
class PDFDocumentLoadingTask {
  static #docId = 0;
  #onUnsupportedFeature = null;
  constructor() {
    this._capability = (0, _util.createPromiseCapability)();
    this._transport = null;
    this._worker = null;
    this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
    this.destroyed = false;
    this.onPassword = null;
    this.onProgress = null;
  }
  get onUnsupportedFeature() {
    return this.#onUnsupportedFeature;
  }
  set onUnsupportedFeature(callback) {
    (0, _display_utils.deprecated)("The PDFDocumentLoadingTask onUnsupportedFeature property will be removed in the future.");
    this.#onUnsupportedFeature = callback;
  }
  get promise() {
    return this._capability.promise;
  }
  async destroy() {
    this.destroyed = true;
    await this._transport?.destroy();
    this._transport = null;
    if (this._worker) {
      this._worker.destroy();
      this._worker = null;
    }
  }
}
exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
class PDFDataRangeTransport {
  constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
    this.length = length;
    this.initialData = initialData;
    this.progressiveDone = progressiveDone;
    this.contentDispositionFilename = contentDispositionFilename;
    this._rangeListeners = [];
    this._progressListeners = [];
    this._progressiveReadListeners = [];
    this._progressiveDoneListeners = [];
    this._readyCapability = (0, _util.createPromiseCapability)();
  }
  addRangeListener(listener) {
    this._rangeListeners.push(listener);
  }
  addProgressListener(listener) {
    this._progressListeners.push(listener);
  }
  addProgressiveReadListener(listener) {
    this._progressiveReadListeners.push(listener);
  }
  addProgressiveDoneListener(listener) {
    this._progressiveDoneListeners.push(listener);
  }
  onDataRange(begin, chunk) {
    for (const listener of this._rangeListeners) {
      listener(begin, chunk);
    }
  }
  onDataProgress(loaded, total) {
    this._readyCapability.promise.then(() => {
      for (const listener of this._progressListeners) {
        listener(loaded, total);
      }
    });
  }
  onDataProgressiveRead(chunk) {
    this._readyCapability.promise.then(() => {
      for (const listener of this._progressiveReadListeners) {
        listener(chunk);
      }
    });
  }
  onDataProgressiveDone() {
    this._readyCapability.promise.then(() => {
      for (const listener of this._progressiveDoneListeners) {
        listener();
      }
    });
  }
  transportReady() {
    this._readyCapability.resolve();
  }
  requestDataRange(begin, end) {
    (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
  }
  abort() {}
}
exports.PDFDataRangeTransport = PDFDataRangeTransport;
class PDFDocumentProxy {
  constructor(pdfInfo, transport) {
    this._pdfInfo = pdfInfo;
    this._transport = transport;
  }
  get annotationStorage() {
    return this._transport.annotationStorage;
  }
  get numPages() {
    return this._pdfInfo.numPages;
  }
  get fingerprints() {
    return this._pdfInfo.fingerprints;
  }
  get isPureXfa() {
    return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  }
  get allXfaHtml() {
    return this._transport._htmlForXfa;
  }
  getPage(pageNumber) {
    return this._transport.getPage(pageNumber);
  }
  getPageIndex(ref) {
    return this._transport.getPageIndex(ref);
  }
  getDestinations() {
    return this._transport.getDestinations();
  }
  getDestination(id) {
    return this._transport.getDestination(id);
  }
  getPageLabels() {
    return this._transport.getPageLabels();
  }
  getPageLayout() {
    return this._transport.getPageLayout();
  }
  getPageMode() {
    return this._transport.getPageMode();
  }
  getViewerPreferences() {
    return this._transport.getViewerPreferences();
  }
  getOpenAction() {
    return this._transport.getOpenAction();
  }
  getAttachments() {
    return this._transport.getAttachments();
  }
  getJavaScript() {
    return this._transport.getJavaScript();
  }
  getJSActions() {
    return this._transport.getDocJSActions();
  }
  getOutline() {
    return this._transport.getOutline();
  }
  getOptionalContentConfig() {
    return this._transport.getOptionalContentConfig();
  }
  getPermissions() {
    return this._transport.getPermissions();
  }
  getMetadata() {
    return this._transport.getMetadata();
  }
  getMarkInfo() {
    return this._transport.getMarkInfo();
  }
  getData() {
    return this._transport.getData();
  }
  saveDocument() {
    return this._transport.saveDocument();
  }
  getDownloadInfo() {
    return this._transport.downloadInfoCapability.promise;
  }
  cleanup(keepLoadedFonts = false) {
    return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
  }
  destroy() {
    return this.loadingTask.destroy();
  }
  get loadingParams() {
    return this._transport.loadingParams;
  }
  get loadingTask() {
    return this._transport.loadingTask;
  }
  getFieldObjects() {
    return this._transport.getFieldObjects();
  }
  hasJSActions() {
    return this._transport.hasJSActions();
  }
  getCalculationOrderIds() {
    return this._transport.getCalculationOrderIds();
  }
}
exports.PDFDocumentProxy = PDFDocumentProxy;
class PDFPageProxy {
  constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
    this._pageIndex = pageIndex;
    this._pageInfo = pageInfo;
    this._ownerDocument = ownerDocument;
    this._transport = transport;
    this._stats = pdfBug ? new _display_utils.StatTimer() : null;
    this._pdfBug = pdfBug;
    this.commonObjs = transport.commonObjs;
    this.objs = new PDFObjects();
    this._bitmaps = new Set();
    this.cleanupAfterRender = false;
    this.pendingCleanup = false;
    this._intentStates = new Map();
    this.destroyed = false;
  }
  get pageNumber() {
    return this._pageIndex + 1;
  }
  get rotate() {
    return this._pageInfo.rotate;
  }
  get ref() {
    return this._pageInfo.ref;
  }
  get userUnit() {
    return this._pageInfo.userUnit;
  }
  get view() {
    return this._pageInfo.view;
  }
  getViewport({
    scale,
    rotation = this.rotate,
    offsetX = 0,
    offsetY = 0,
    dontFlip = false
  } = {}) {
    return new _display_utils.PageViewport({
      viewBox: this.view,
      scale,
      rotation,
      offsetX,
      offsetY,
      dontFlip
    });
  }
  getAnnotations({
    intent = "display"
  } = {}) {
    const intentArgs = this._transport.getRenderingIntent(intent);
    return this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
  }
  getJSActions() {
    return this._transport.getPageJSActions(this._pageIndex);
  }
  get isPureXfa() {
    return (0, _util.shadow)(this, "isPureXfa", !!this._transport._htmlForXfa);
  }
  async getXfa() {
    return this._transport._htmlForXfa?.children[this._pageIndex] || null;
  }
  render({
    canvasContext,
    viewport,
    intent = "display",
    annotationMode = _util.AnnotationMode.ENABLE,
    transform = null,
    canvasFactory = null,
    background = null,
    optionalContentConfigPromise = null,
    annotationCanvasMap = null,
    pageColors = null,
    printAnnotationStorage = null
  }) {
    this._stats?.time("Overall");
    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage);
    this.pendingCleanup = false;
    if (!optionalContentConfigPromise) {
      optionalContentConfigPromise = this._transport.getOptionalContentConfig();
    }
    let intentState = this._intentStates.get(intentArgs.cacheKey);
    if (!intentState) {
      intentState = Object.create(null);
      this._intentStates.set(intentArgs.cacheKey, intentState);
    }
    if (intentState.streamReaderCancelTimeout) {
      clearTimeout(intentState.streamReaderCancelTimeout);
      intentState.streamReaderCancelTimeout = null;
    }
    const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
      ownerDocument: this._ownerDocument
    });
    const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
    if (!intentState.displayReadyCapability) {
      intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
      intentState.operatorList = {
        fnArray: [],
        argsArray: [],
        lastChunk: false,
        separateAnnots: null
      };
      this._stats?.time("Page Request");
      this._pumpOperatorList(intentArgs);
    }
    const complete = error => {
      intentState.renderTasks.delete(internalRenderTask);
      if (this.cleanupAfterRender || intentPrint) {
        this.pendingCleanup = true;
      }
      this._tryCleanup();
      if (error) {
        internalRenderTask.capability.reject(error);
        this._abortOperatorList({
          intentState,
          reason: error instanceof Error ? error : new Error(error)
        });
      } else {
        internalRenderTask.capability.resolve();
      }
      this._stats?.timeEnd("Rendering");
      this._stats?.timeEnd("Overall");
    };
    const internalRenderTask = new InternalRenderTask({
      callback: complete,
      params: {
        canvasContext,
        viewport,
        transform,
        background
      },
      objs: this.objs,
      commonObjs: this.commonObjs,
      annotationCanvasMap,
      operatorList: intentState.operatorList,
      pageIndex: this._pageIndex,
      canvasFactory: canvasFactoryInstance,
      useRequestAnimationFrame: !intentPrint,
      pdfBug: this._pdfBug,
      pageColors
    });
    (intentState.renderTasks ||= new Set()).add(internalRenderTask);
    const renderTask = internalRenderTask.task;
    Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
      if (this.pendingCleanup) {
        complete();
        return;
      }
      this._stats?.time("Rendering");
      internalRenderTask.initializeGraphics({
        transparency,
        optionalContentConfig
      });
      internalRenderTask.operatorListChanged();
    }).catch(complete);
    return renderTask;
  }
  getOperatorList({
    intent = "display",
    annotationMode = _util.AnnotationMode.ENABLE,
    printAnnotationStorage = null
  } = {}) {
    function operatorListChanged() {
      if (intentState.operatorList.lastChunk) {
        intentState.opListReadCapability.resolve(intentState.operatorList);
        intentState.renderTasks.delete(opListTask);
      }
    }
    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, true);
    let intentState = this._intentStates.get(intentArgs.cacheKey);
    if (!intentState) {
      intentState = Object.create(null);
      this._intentStates.set(intentArgs.cacheKey, intentState);
    }
    let opListTask;
    if (!intentState.opListReadCapability) {
      opListTask = Object.create(null);
      opListTask.operatorListChanged = operatorListChanged;
      intentState.opListReadCapability = (0, _util.createPromiseCapability)();
      (intentState.renderTasks ||= new Set()).add(opListTask);
      intentState.operatorList = {
        fnArray: [],
        argsArray: [],
        lastChunk: false,
        separateAnnots: null
      };
      this._stats?.time("Page Request");
      this._pumpOperatorList(intentArgs);
    }
    return intentState.opListReadCapability.promise;
  }
  streamTextContent({
    disableCombineTextItems = false,
    includeMarkedContent = false
  } = {}) {
    const TEXT_CONTENT_CHUNK_SIZE = 100;
    return this._transport.messageHandler.sendWithStream("GetTextContent", {
      pageIndex: this._pageIndex,
      combineTextItems: disableCombineTextItems !== true,
      includeMarkedContent: includeMarkedContent === true
    }, {
      highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
      size(textContent) {
        return textContent.items.length;
      }
    });
  }
  getTextContent(params = {}) {
    if (this._transport._htmlForXfa) {
      return this.getXfa().then(xfa => {
        return _xfa_text.XfaText.textContent(xfa);
      });
    }
    const readableStream = this.streamTextContent(params);
    return new Promise(function (resolve, reject) {
      function pump() {
        reader.read().then(function ({
          value,
          done
        }) {
          if (done) {
            resolve(textContent);
            return;
          }
          Object.assign(textContent.styles, value.styles);
          textContent.items.push(...value.items);
          pump();
        }, reject);
      }
      const reader = readableStream.getReader();
      const textContent = {
        items: [],
        styles: Object.create(null)
      };
      pump();
    });
  }
  getStructTree() {
    return this._transport.getStructTree(this._pageIndex);
  }
  _destroy() {
    this.destroyed = true;
    const waitOn = [];
    for (const intentState of this._intentStates.values()) {
      this._abortOperatorList({
        intentState,
        reason: new Error("Page was destroyed."),
        force: true
      });
      if (intentState.opListReadCapability) {
        continue;
      }
      for (const internalRenderTask of intentState.renderTasks) {
        waitOn.push(internalRenderTask.completed);
        internalRenderTask.cancel();
      }
    }
    this.objs.clear();
    for (const bitmap of this._bitmaps) {
      bitmap.close();
    }
    this._bitmaps.clear();
    this.pendingCleanup = false;
    return Promise.all(waitOn);
  }
  cleanup(resetStats = false) {
    this.pendingCleanup = true;
    return this._tryCleanup(resetStats);
  }
  _tryCleanup(resetStats = false) {
    if (!this.pendingCleanup) {
      return false;
    }
    for (const {
      renderTasks,
      operatorList
    } of this._intentStates.values()) {
      if (renderTasks.size > 0 || !operatorList.lastChunk) {
        return false;
      }
    }
    this._intentStates.clear();
    this.objs.clear();
    if (resetStats && this._stats) {
      this._stats = new _display_utils.StatTimer();
    }
    for (const bitmap of this._bitmaps) {
      bitmap.close();
    }
    this._bitmaps.clear();
    this.pendingCleanup = false;
    return true;
  }
  _startRenderPage(transparency, cacheKey) {
    const intentState = this._intentStates.get(cacheKey);
    if (!intentState) {
      return;
    }
    this._stats?.timeEnd("Page Request");
    intentState.displayReadyCapability?.resolve(transparency);
  }
  _renderPageChunk(operatorListChunk, intentState) {
    for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
      intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
      intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
    }
    intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
    intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots;
    for (const internalRenderTask of intentState.renderTasks) {
      internalRenderTask.operatorListChanged();
    }
    if (operatorListChunk.lastChunk) {
      this._tryCleanup();
    }
  }
  _pumpOperatorList({
    renderingIntent,
    cacheKey,
    annotationStorageMap
  }) {
    const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
      pageIndex: this._pageIndex,
      intent: renderingIntent,
      cacheKey,
      annotationStorage: annotationStorageMap
    });
    const reader = readableStream.getReader();
    const intentState = this._intentStates.get(cacheKey);
    intentState.streamReader = reader;
    const pump = () => {
      reader.read().then(({
        value,
        done
      }) => {
        if (done) {
          intentState.streamReader = null;
          return;
        }
        if (this._transport.destroyed) {
          return;
        }
        this._renderPageChunk(value, intentState);
        pump();
      }, reason => {
        intentState.streamReader = null;
        if (this._transport.destroyed) {
          return;
        }
        if (intentState.operatorList) {
          intentState.operatorList.lastChunk = true;
          for (const internalRenderTask of intentState.renderTasks) {
            internalRenderTask.operatorListChanged();
          }
          this._tryCleanup();
        }
        if (intentState.displayReadyCapability) {
          intentState.displayReadyCapability.reject(reason);
        } else if (intentState.opListReadCapability) {
          intentState.opListReadCapability.reject(reason);
        } else {
          throw reason;
        }
      });
    };
    pump();
  }
  _abortOperatorList({
    intentState,
    reason,
    force = false
  }) {
    if (!intentState.streamReader) {
      return;
    }
    if (intentState.streamReaderCancelTimeout) {
      clearTimeout(intentState.streamReaderCancelTimeout);
      intentState.streamReaderCancelTimeout = null;
    }
    if (!force) {
      if (intentState.renderTasks.size > 0) {
        return;
      }
      if (reason instanceof _display_utils.RenderingCancelledException) {
        let delay = RENDERING_CANCELLED_TIMEOUT;
        if (reason.extraDelay > 0 && reason.extraDelay < 1000) {
          delay += reason.extraDelay;
        }
        intentState.streamReaderCancelTimeout = setTimeout(() => {
          intentState.streamReaderCancelTimeout = null;
          this._abortOperatorList({
            intentState,
            reason,
            force: true
          });
        }, delay);
        return;
      }
    }
    intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
    intentState.streamReader = null;
    if (this._transport.destroyed) {
      return;
    }
    for (const [curCacheKey, curIntentState] of this._intentStates) {
      if (curIntentState === intentState) {
        this._intentStates.delete(curCacheKey);
        break;
      }
    }
    this.cleanup();
  }
  get stats() {
    return this._stats;
  }
}
exports.PDFPageProxy = PDFPageProxy;
class LoopbackPort {
  #listeners = [];
  #deferred = Promise.resolve();
  postMessage(obj, transfers) {
    const event = {
      data: structuredClone(obj, transfers)
    };
    this.#deferred.then(() => {
      for (const listener of this.#listeners) {
        listener.call(this, event);
      }
    });
  }
  addEventListener(name, listener) {
    this.#listeners.push(listener);
  }
  removeEventListener(name, listener) {
    const i = this.#listeners.indexOf(listener);
    this.#listeners.splice(i, 1);
  }
  terminate() {
    this.#listeners.length = 0;
  }
}
exports.LoopbackPort = LoopbackPort;
const PDFWorkerUtil = {
  isWorkerDisabled: false,
  fallbackWorkerSrc: null,
  fakeWorkerId: 0
};
exports.PDFWorkerUtil = PDFWorkerUtil;
{
  if (_is_node.isNodeJS && typeof require === "function") {
    PDFWorkerUtil.isWorkerDisabled = true;
    PDFWorkerUtil.fallbackWorkerSrc = "./pdf.worker.js";
  } else if (typeof document === "object") {
    const pdfjsFilePath = document?.currentScript?.src;
    if (pdfjsFilePath) {
      PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
    }
  }
  PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
    let base;
    try {
      base = new URL(baseUrl);
      if (!base.origin || base.origin === "null") {
        return false;
      }
    } catch (e) {
      return false;
    }
    const other = new URL(otherUrl, base);
    return base.origin === other.origin;
  };
  PDFWorkerUtil.createCDNWrapper = function (url) {
    const wrapper = `importScripts("${url}");`;
    return URL.createObjectURL(new Blob([wrapper]));
  };
}
class PDFWorker {
  static #workerPorts = new WeakMap();
  constructor({
    name = null,
    port = null,
    verbosity = (0, _util.getVerbosityLevel)()
  } = {}) {
    if (port && PDFWorker.#workerPorts.has(port)) {
      throw new Error("Cannot use more than one PDFWorker per port.");
    }
    this.name = name;
    this.destroyed = false;
    this.verbosity = verbosity;
    this._readyCapability = (0, _util.createPromiseCapability)();
    this._port = null;
    this._webWorker = null;
    this._messageHandler = null;
    if (port) {
      PDFWorker.#workerPorts.set(port, this);
      this._initializeFromPort(port);
      return;
    }
    this._initialize();
  }
  get promise() {
    return this._readyCapability.promise;
  }
  get port() {
    return this._port;
  }
  get messageHandler() {
    return this._messageHandler;
  }
  _initializeFromPort(port) {
    this._port = port;
    this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
    this._messageHandler.on("ready", function () {});
    this._readyCapability.resolve();
    this._messageHandler.send("configure", {
      verbosity: this.verbosity
    });
  }
  _initialize() {
    if (!PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
      let {
        workerSrc
      } = PDFWorker;
      try {
        if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
          workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
        }
        const worker = new Worker(workerSrc);
        const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
        const terminateEarly = () => {
          worker.removeEventListener("error", onWorkerError);
          messageHandler.destroy();
          worker.terminate();
          if (this.destroyed) {
            this._readyCapability.reject(new Error("Worker was destroyed"));
          } else {
            this._setupFakeWorker();
          }
        };
        const onWorkerError = () => {
          if (!this._webWorker) {
            terminateEarly();
          }
        };
        worker.addEventListener("error", onWorkerError);
        messageHandler.on("test", data => {
          worker.removeEventListener("error", onWorkerError);
          if (this.destroyed) {
            terminateEarly();
            return;
          }
          if (data) {
            this._messageHandler = messageHandler;
            this._port = worker;
            this._webWorker = worker;
            this._readyCapability.resolve();
            messageHandler.send("configure", {
              verbosity: this.verbosity
            });
          } else {
            this._setupFakeWorker();
            messageHandler.destroy();
            worker.terminate();
          }
        });
        messageHandler.on("ready", data => {
          worker.removeEventListener("error", onWorkerError);
          if (this.destroyed) {
            terminateEarly();
            return;
          }
          try {
            sendTest();
          } catch (e) {
            this._setupFakeWorker();
          }
        });
        const sendTest = () => {
          const testObj = new Uint8Array();
          messageHandler.send("test", testObj, [testObj.buffer]);
        };
        sendTest();
        return;
      } catch (e) {
        (0, _util.info)("The worker has been disabled.");
      }
    }
    this._setupFakeWorker();
  }
  _setupFakeWorker() {
    if (!PDFWorkerUtil.isWorkerDisabled) {
      (0, _util.warn)("Setting up fake worker.");
      PDFWorkerUtil.isWorkerDisabled = true;
    }
    PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
      if (this.destroyed) {
        this._readyCapability.reject(new Error("Worker was destroyed"));
        return;
      }
      const port = new LoopbackPort();
      this._port = port;
      const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
      const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
      WorkerMessageHandler.setup(workerHandler, port);
      const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
      this._messageHandler = messageHandler;
      this._readyCapability.resolve();
      messageHandler.send("configure", {
        verbosity: this.verbosity
      });
    }).catch(reason => {
      this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
    });
  }
  destroy() {
    this.destroyed = true;
    if (this._webWorker) {
      this._webWorker.terminate();
      this._webWorker = null;
    }
    PDFWorker.#workerPorts.delete(this._port);
    this._port = null;
    if (this._messageHandler) {
      this._messageHandler.destroy();
      this._messageHandler = null;
    }
  }
  static fromPort(params) {
    if (!params?.port) {
      throw new Error("PDFWorker.fromPort - invalid method signature.");
    }
    if (this.#workerPorts.has(params.port)) {
      return this.#workerPorts.get(params.port);
    }
    return new PDFWorker(params);
  }
  static get workerSrc() {
    if (_worker_options.GlobalWorkerOptions.workerSrc) {
      return _worker_options.GlobalWorkerOptions.workerSrc;
    }
    if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
      if (!_is_node.isNodeJS) {
        (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
      }
      return PDFWorkerUtil.fallbackWorkerSrc;
    }
    throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
  }
  static get _mainThreadWorkerMessageHandler() {
    try {
      return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
    } catch (ex) {
      return null;
    }
  }
  static get _setupFakeWorkerGlobal() {
    const loader = async () => {
      const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
      if (mainWorkerMessageHandler) {
        return mainWorkerMessageHandler;
      }
      if (_is_node.isNodeJS && typeof require === "function") {
        const worker = eval("require")(this.workerSrc);
        return worker.WorkerMessageHandler;
      }
      await (0, _display_utils.loadScript)(this.workerSrc);
      return window.pdfjsWorker.WorkerMessageHandler;
    };
    return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
  }
}
exports.PDFWorker = PDFWorker;
class WorkerTransport {
  #methodPromises = new Map();
  #pageCache = new Map();
  #pagePromises = new Map();
  constructor(messageHandler, loadingTask, networkStream, params, factory) {
    this.messageHandler = messageHandler;
    this.loadingTask = loadingTask;
    this.commonObjs = new PDFObjects();
    this.fontLoader = new _font_loader.FontLoader({
      onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
      ownerDocument: params.ownerDocument,
      styleElement: params.styleElement
    });
    this._params = params;
    this.cMapReaderFactory = factory?.cMapReaderFactory;
    this.standardFontDataFactory = factory?.standardFontDataFactory;
    this.destroyed = false;
    this.destroyCapability = null;
    this._passwordCapability = null;
    this._networkStream = networkStream;
    this._fullReader = null;
    this._lastProgress = null;
    this.downloadInfoCapability = (0, _util.createPromiseCapability)();
    this.setupMessageHandler();
  }
  #cacheSimpleMethod(name, data = null) {
    const cachedPromise = this.#methodPromises.get(name);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise(name, data);
    this.#methodPromises.set(name, promise);
    return promise;
  }
  get annotationStorage() {
    return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
  }
  getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, printAnnotationStorage = null, isOpList = false) {
    let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
    let annotationMap = null;
    switch (intent) {
      case "any":
        renderingIntent = _util.RenderingIntentFlag.ANY;
        break;
      case "display":
        break;
      case "print":
        renderingIntent = _util.RenderingIntentFlag.PRINT;
        break;
      default:
        (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
    }
    switch (annotationMode) {
      case _util.AnnotationMode.DISABLE:
        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
        break;
      case _util.AnnotationMode.ENABLE:
        break;
      case _util.AnnotationMode.ENABLE_FORMS:
        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
        break;
      case _util.AnnotationMode.ENABLE_STORAGE:
        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
        const annotationStorage = renderingIntent & _util.RenderingIntentFlag.PRINT && printAnnotationStorage instanceof _annotation_storage.PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage;
        annotationMap = annotationStorage.serializable;
        break;
      default:
        (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
    }
    if (isOpList) {
      renderingIntent += _util.RenderingIntentFlag.OPLIST;
    }
    return {
      renderingIntent,
      cacheKey: `${renderingIntent}_${_annotation_storage.AnnotationStorage.getHash(annotationMap)}`,
      annotationStorageMap: annotationMap
    };
  }
  destroy() {
    if (this.destroyCapability) {
      return this.destroyCapability.promise;
    }
    this.destroyed = true;
    this.destroyCapability = (0, _util.createPromiseCapability)();
    if (this._passwordCapability) {
      this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
    }
    const waitOn = [];
    for (const page of this.#pageCache.values()) {
      waitOn.push(page._destroy());
    }
    this.#pageCache.clear();
    this.#pagePromises.clear();
    if (this.hasOwnProperty("annotationStorage")) {
      this.annotationStorage.resetModified();
    }
    const terminated = this.messageHandler.sendWithPromise("Terminate", null);
    waitOn.push(terminated);
    Promise.all(waitOn).then(() => {
      this.commonObjs.clear();
      this.fontLoader.clear();
      this.#methodPromises.clear();
      if (this._networkStream) {
        this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
      }
      if (this.messageHandler) {
        this.messageHandler.destroy();
        this.messageHandler = null;
      }
      this.destroyCapability.resolve();
    }, this.destroyCapability.reject);
    return this.destroyCapability.promise;
  }
  setupMessageHandler() {
    const {
      messageHandler,
      loadingTask
    } = this;
    messageHandler.on("GetReader", (data, sink) => {
      (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
      this._fullReader = this._networkStream.getFullReader();
      this._fullReader.onProgress = evt => {
        this._lastProgress = {
          loaded: evt.loaded,
          total: evt.total
        };
      };
      sink.onPull = () => {
        this._fullReader.read().then(function ({
          value,
          done
        }) {
          if (done) {
            sink.close();
            return;
          }
          (0, _util.assert)(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer.");
          sink.enqueue(new Uint8Array(value), 1, [value]);
        }).catch(reason => {
          sink.error(reason);
        });
      };
      sink.onCancel = reason => {
        this._fullReader.cancel(reason);
        sink.ready.catch(readyReason => {
          if (this.destroyed) {
            return;
          }
          throw readyReason;
        });
      };
    });
    messageHandler.on("ReaderHeadersReady", data => {
      const headersCapability = (0, _util.createPromiseCapability)();
      const fullReader = this._fullReader;
      fullReader.headersReady.then(() => {
        if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
          if (this._lastProgress) {
            loadingTask.onProgress?.(this._lastProgress);
          }
          fullReader.onProgress = evt => {
            loadingTask.onProgress?.({
              loaded: evt.loaded,
              total: evt.total
            });
          };
        }
        headersCapability.resolve({
          isStreamingSupported: fullReader.isStreamingSupported,
          isRangeSupported: fullReader.isRangeSupported,
          contentLength: fullReader.contentLength
        });
      }, headersCapability.reject);
      return headersCapability.promise;
    });
    messageHandler.on("GetRangeReader", (data, sink) => {
      (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
      const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
      if (!rangeReader) {
        sink.close();
        return;
      }
      sink.onPull = () => {
        rangeReader.read().then(function ({
          value,
          done
        }) {
          if (done) {
            sink.close();
            return;
          }
          (0, _util.assert)(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer.");
          sink.enqueue(new Uint8Array(value), 1, [value]);
        }).catch(reason => {
          sink.error(reason);
        });
      };
      sink.onCancel = reason => {
        rangeReader.cancel(reason);
        sink.ready.catch(readyReason => {
          if (this.destroyed) {
            return;
          }
          throw readyReason;
        });
      };
    });
    messageHandler.on("GetDoc", ({
      pdfInfo
    }) => {
      this._numPages = pdfInfo.numPages;
      this._htmlForXfa = pdfInfo.htmlForXfa;
      delete pdfInfo.htmlForXfa;
      loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
    });
    messageHandler.on("DocException", function (ex) {
      let reason;
      switch (ex.name) {
        case "PasswordException":
          reason = new _util.PasswordException(ex.message, ex.code);
          break;
        case "InvalidPDFException":
          reason = new _util.InvalidPDFException(ex.message);
          break;
        case "MissingPDFException":
          reason = new _util.MissingPDFException(ex.message);
          break;
        case "UnexpectedResponseException":
          reason = new _util.UnexpectedResponseException(ex.message, ex.status);
          break;
        case "UnknownErrorException":
          reason = new _util.UnknownErrorException(ex.message, ex.details);
          break;
        default:
          (0, _util.unreachable)("DocException - expected a valid Error.");
      }
      loadingTask._capability.reject(reason);
    });
    messageHandler.on("PasswordRequest", exception => {
      this._passwordCapability = (0, _util.createPromiseCapability)();
      if (loadingTask.onPassword) {
        const updatePassword = password => {
          if (password instanceof Error) {
            this._passwordCapability.reject(password);
          } else {
            this._passwordCapability.resolve({
              password
            });
          }
        };
        try {
          loadingTask.onPassword(updatePassword, exception.code);
        } catch (ex) {
          this._passwordCapability.reject(ex);
        }
      } else {
        this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
      }
      return this._passwordCapability.promise;
    });
    messageHandler.on("DataLoaded", data => {
      loadingTask.onProgress?.({
        loaded: data.length,
        total: data.length
      });
      this.downloadInfoCapability.resolve(data);
    });
    messageHandler.on("StartRenderPage", data => {
      if (this.destroyed) {
        return;
      }
      const page = this.#pageCache.get(data.pageIndex);
      page._startRenderPage(data.transparency, data.cacheKey);
    });
    messageHandler.on("commonobj", ([id, type, exportedData]) => {
      if (this.destroyed) {
        return;
      }
      if (this.commonObjs.has(id)) {
        return;
      }
      switch (type) {
        case "Font":
          const params = this._params;
          if ("error" in exportedData) {
            const exportedError = exportedData.error;
            (0, _util.warn)(`Error during font loading: ${exportedError}`);
            this.commonObjs.resolve(id, exportedError);
            break;
          }
          let fontRegistry = null;
          if (params.pdfBug && globalThis.FontInspector?.enabled) {
            fontRegistry = {
              registerFont(font, url) {
                globalThis.FontInspector.fontAdded(font, url);
              }
            };
          }
          const font = new _font_loader.FontFaceObject(exportedData, {
            isEvalSupported: params.isEvalSupported,
            disableFontFace: params.disableFontFace,
            ignoreErrors: params.ignoreErrors,
            onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
            fontRegistry
          });
          this.fontLoader.bind(font).catch(reason => {
            return messageHandler.sendWithPromise("FontFallback", {
              id
            });
          }).finally(() => {
            if (!params.fontExtraProperties && font.data) {
              font.data = null;
            }
            this.commonObjs.resolve(id, font);
          });
          break;
        case "FontPath":
        case "Image":
          this.commonObjs.resolve(id, exportedData);
          break;
        default:
          throw new Error(`Got unknown common object type ${type}`);
      }
    });
    messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
      if (this.destroyed) {
        return;
      }
      const pageProxy = this.#pageCache.get(pageIndex);
      if (pageProxy.objs.has(id)) {
        return;
      }
      switch (type) {
        case "Image":
          pageProxy.objs.resolve(id, imageData);
          const MAX_IMAGE_SIZE_TO_STORE = 8000000;
          if (imageData) {
            let length;
            if (imageData.bitmap) {
              const {
                bitmap,
                width,
                height
              } = imageData;
              length = width * height * 4;
              pageProxy._bitmaps.add(bitmap);
            } else {
              length = imageData.data?.length || 0;
            }
            if (length > MAX_IMAGE_SIZE_TO_STORE) {
              pageProxy.cleanupAfterRender = true;
            }
          }
          break;
        case "Pattern":
          pageProxy.objs.resolve(id, imageData);
          break;
        default:
          throw new Error(`Got unknown object type ${type}`);
      }
    });
    messageHandler.on("DocProgress", data => {
      if (this.destroyed) {
        return;
      }
      loadingTask.onProgress?.({
        loaded: data.loaded,
        total: data.total
      });
    });
    messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
    messageHandler.on("FetchBuiltInCMap", data => {
      if (this.destroyed) {
        return Promise.reject(new Error("Worker was destroyed."));
      }
      if (!this.cMapReaderFactory) {
        return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
      }
      return this.cMapReaderFactory.fetch(data);
    });
    messageHandler.on("FetchStandardFontData", data => {
      if (this.destroyed) {
        return Promise.reject(new Error("Worker was destroyed."));
      }
      if (!this.standardFontDataFactory) {
        return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
      }
      return this.standardFontDataFactory.fetch(data);
    });
  }
  _onUnsupportedFeature({
    featureId
  }) {
    if (this.destroyed) {
      return;
    }
    this.loadingTask.onUnsupportedFeature?.(featureId);
  }
  getData() {
    return this.messageHandler.sendWithPromise("GetData", null);
  }
  saveDocument() {
    if (this.annotationStorage.size <= 0) {
      (0, _util.warn)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
    }
    return this.messageHandler.sendWithPromise("SaveDocument", {
      isPureXfa: !!this._htmlForXfa,
      numPages: this._numPages,
      annotationStorage: this.annotationStorage.serializable,
      filename: this._fullReader?.filename ?? null
    }).finally(() => {
      this.annotationStorage.resetModified();
    });
  }
  getPage(pageNumber) {
    if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
      return Promise.reject(new Error("Invalid page request."));
    }
    const pageIndex = pageNumber - 1,
      cachedPromise = this.#pagePromises.get(pageIndex);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise("GetPage", {
      pageIndex
    }).then(pageInfo => {
      if (this.destroyed) {
        throw new Error("Transport destroyed");
      }
      const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
      this.#pageCache.set(pageIndex, page);
      return page;
    });
    this.#pagePromises.set(pageIndex, promise);
    return promise;
  }
  getPageIndex(ref) {
    if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
      return Promise.reject(new Error("Invalid pageIndex request."));
    }
    return this.messageHandler.sendWithPromise("GetPageIndex", {
      num: ref.num,
      gen: ref.gen
    });
  }
  getAnnotations(pageIndex, intent) {
    return this.messageHandler.sendWithPromise("GetAnnotations", {
      pageIndex,
      intent
    });
  }
  getFieldObjects() {
    return this.#cacheSimpleMethod("GetFieldObjects");
  }
  hasJSActions() {
    return this.#cacheSimpleMethod("HasJSActions");
  }
  getCalculationOrderIds() {
    return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
  }
  getDestinations() {
    return this.messageHandler.sendWithPromise("GetDestinations", null);
  }
  getDestination(id) {
    if (typeof id !== "string") {
      return Promise.reject(new Error("Invalid destination request."));
    }
    return this.messageHandler.sendWithPromise("GetDestination", {
      id
    });
  }
  getPageLabels() {
    return this.messageHandler.sendWithPromise("GetPageLabels", null);
  }
  getPageLayout() {
    return this.messageHandler.sendWithPromise("GetPageLayout", null);
  }
  getPageMode() {
    return this.messageHandler.sendWithPromise("GetPageMode", null);
  }
  getViewerPreferences() {
    return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
  }
  getOpenAction() {
    return this.messageHandler.sendWithPromise("GetOpenAction", null);
  }
  getAttachments() {
    return this.messageHandler.sendWithPromise("GetAttachments", null);
  }
  getJavaScript() {
    return this.messageHandler.sendWithPromise("GetJavaScript", null);
  }
  getDocJSActions() {
    return this.messageHandler.sendWithPromise("GetDocJSActions", null);
  }
  getPageJSActions(pageIndex) {
    return this.messageHandler.sendWithPromise("GetPageJSActions", {
      pageIndex
    });
  }
  getStructTree(pageIndex) {
    return this.messageHandler.sendWithPromise("GetStructTree", {
      pageIndex
    });
  }
  getOutline() {
    return this.messageHandler.sendWithPromise("GetOutline", null);
  }
  getOptionalContentConfig() {
    return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
      return new _optional_content_config.OptionalContentConfig(results);
    });
  }
  getPermissions() {
    return this.messageHandler.sendWithPromise("GetPermissions", null);
  }
  getMetadata() {
    const name = "GetMetadata",
      cachedPromise = this.#methodPromises.get(name);
    if (cachedPromise) {
      return cachedPromise;
    }
    const promise = this.messageHandler.sendWithPromise(name, null).then(results => {
      return {
        info: results[0],
        metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
        contentDispositionFilename: this._fullReader?.filename ?? null,
        contentLength: this._fullReader?.contentLength ?? null
      };
    });
    this.#methodPromises.set(name, promise);
    return promise;
  }
  getMarkInfo() {
    return this.messageHandler.sendWithPromise("GetMarkInfo", null);
  }
  async startCleanup(keepLoadedFonts = false) {
    if (this.destroyed) {
      return;
    }
    await this.messageHandler.sendWithPromise("Cleanup", null);
    for (const page of this.#pageCache.values()) {
      const cleanupSuccessful = page.cleanup();
      if (!cleanupSuccessful) {
        throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
      }
    }
    this.commonObjs.clear();
    if (!keepLoadedFonts) {
      this.fontLoader.clear();
    }
    this.#methodPromises.clear();
  }
  get loadingParams() {
    const {
      disableAutoFetch,
      enableXfa
    } = this._params;
    return (0, _util.shadow)(this, "loadingParams", {
      disableAutoFetch,
      enableXfa
    });
  }
}
class PDFObjects {
  #objs = Object.create(null);
  #ensureObj(objId) {
    const obj = this.#objs[objId];
    if (obj) {
      return obj;
    }
    return this.#objs[objId] = {
      capability: (0, _util.createPromiseCapability)(),
      data: null
    };
  }
  get(objId, callback = null) {
    if (callback) {
      const obj = this.#ensureObj(objId);
      obj.capability.promise.then(() => callback(obj.data));
      return null;
    }
    const obj = this.#objs[objId];
    if (!obj?.capability.settled) {
      throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
    }
    return obj.data;
  }
  has(objId) {
    const obj = this.#objs[objId];
    return obj?.capability.settled || false;
  }
  resolve(objId, data = null) {
    const obj = this.#ensureObj(objId);
    obj.data = data;
    obj.capability.resolve();
  }
  clear() {
    this.#objs = Object.create(null);
  }
}
class RenderTask {
  #internalRenderTask = null;
  constructor(internalRenderTask) {
    this.#internalRenderTask = internalRenderTask;
    this.onContinue = null;
  }
  get promise() {
    return this.#internalRenderTask.capability.promise;
  }
  cancel(extraDelay = 0) {
    this.#internalRenderTask.cancel(null, extraDelay);
  }
  get separateAnnots() {
    const {
      separateAnnots
    } = this.#internalRenderTask.operatorList;
    if (!separateAnnots) {
      return false;
    }
    const {
      annotationCanvasMap
    } = this.#internalRenderTask;
    return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0;
  }
}
exports.RenderTask = RenderTask;
class InternalRenderTask {
  static #canvasInUse = new WeakSet();
  constructor({
    callback,
    params,
    objs,
    commonObjs,
    annotationCanvasMap,
    operatorList,
    pageIndex,
    canvasFactory,
    useRequestAnimationFrame = false,
    pdfBug = false,
    pageColors = null
  }) {
    this.callback = callback;
    this.params = params;
    this.objs = objs;
    this.commonObjs = commonObjs;
    this.annotationCanvasMap = annotationCanvasMap;
    this.operatorListIdx = null;
    this.operatorList = operatorList;
    this._pageIndex = pageIndex;
    this.canvasFactory = canvasFactory;
    this._pdfBug = pdfBug;
    this.pageColors = pageColors;
    this.running = false;
    this.graphicsReadyCallback = null;
    this.graphicsReady = false;
    this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
    this.cancelled = false;
    this.capability = (0, _util.createPromiseCapability)();
    this.task = new RenderTask(this);
    this._cancelBound = this.cancel.bind(this);
    this._continueBound = this._continue.bind(this);
    this._scheduleNextBound = this._scheduleNext.bind(this);
    this._nextBound = this._next.bind(this);
    this._canvas = params.canvasContext.canvas;
  }
  get completed() {
    return this.capability.promise.catch(function () {});
  }
  initializeGraphics({
    transparency = false,
    optionalContentConfig
  }) {
    if (this.cancelled) {
      return;
    }
    if (this._canvas) {
      if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
        throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
      }
      InternalRenderTask.#canvasInUse.add(this._canvas);
    }
    if (this._pdfBug && globalThis.StepperManager?.enabled) {
      this.stepper = globalThis.StepperManager.create(this._pageIndex);
      this.stepper.init(this.operatorList);
      this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
    }
    const {
      canvasContext,
      viewport,
      transform,
      background
    } = this.params;
    this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, {
      optionalContentConfig
    }, this.annotationCanvasMap, this.pageColors);
    this.gfx.beginDrawing({
      transform,
      viewport,
      transparency,
      background
    });
    this.operatorListIdx = 0;
    this.graphicsReady = true;
    this.graphicsReadyCallback?.();
  }
  cancel(error = null, extraDelay = 0) {
    this.running = false;
    this.cancelled = true;
    this.gfx?.endDrawing();
    if (this._canvas) {
      InternalRenderTask.#canvasInUse.delete(this._canvas);
    }
    this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas", extraDelay));
  }
  operatorListChanged() {
    if (!this.graphicsReady) {
      if (!this.graphicsReadyCallback) {
        this.graphicsReadyCallback = this._continueBound;
      }
      return;
    }
    this.stepper?.updateOperatorList(this.operatorList);
    if (this.running) {
      return;
    }
    this._continue();
  }
  _continue() {
    this.running = true;
    if (this.cancelled) {
      return;
    }
    if (this.task.onContinue) {
      this.task.onContinue(this._scheduleNextBound);
    } else {
      this._scheduleNext();
    }
  }
  _scheduleNext() {
    if (this._useRequestAnimationFrame) {
      window.requestAnimationFrame(() => {
        this._nextBound().catch(this._cancelBound);
      });
    } else {
      Promise.resolve().then(this._nextBound).catch(this._cancelBound);
    }
  }
  async _next() {
    if (this.cancelled) {
      return;
    }
    this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
    if (this.operatorListIdx === this.operatorList.argsArray.length) {
      this.running = false;
      if (this.operatorList.lastChunk) {
        this.gfx.endDrawing();
        if (this._canvas) {
          InternalRenderTask.#canvasInUse.delete(this._canvas);
        }
        this.callback();
      }
    }
  }
}
const version = '3.4.50';
exports.version = version;
const build = '00560ed83';
exports.build = build;

/***/ }),
/* 3 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PrintAnnotationStorage = exports.AnnotationStorage = void 0;
var _util = __w_pdfjs_require__(1);
var _editor = __w_pdfjs_require__(4);
var _murmurhash = __w_pdfjs_require__(8);
class AnnotationStorage {
  #modified = false;
  #storage = new Map();
  constructor() {
    this.onSetModified = null;
    this.onResetModified = null;
    this.onAnnotationEditor = null;
  }
  getValue(key, defaultValue) {
    const value = this.#storage.get(key);
    if (value === undefined) {
      return defaultValue;
    }
    return Object.assign(defaultValue, value);
  }
  getRawValue(key) {
    return this.#storage.get(key);
  }
  remove(key) {
    this.#storage.delete(key);
    if (this.#storage.size === 0) {
      this.resetModified();
    }
    if (typeof this.onAnnotationEditor === "function") {
      for (const value of this.#storage.values()) {
        if (value instanceof _editor.AnnotationEditor) {
          return;
        }
      }
      this.onAnnotationEditor(null);
    }
  }
  setValue(key, value) {
    const obj = this.#storage.get(key);
    let modified = false;
    if (obj !== undefined) {
      for (const [entry, val] of Object.entries(value)) {
        if (obj[entry] !== val) {
          modified = true;
          obj[entry] = val;
        }
      }
    } else {
      modified = true;
      this.#storage.set(key, value);
    }
    if (modified) {
      this.#setModified();
    }
    if (value instanceof _editor.AnnotationEditor && typeof this.onAnnotationEditor === "function") {
      this.onAnnotationEditor(value.constructor._type);
    }
  }
  has(key) {
    return this.#storage.has(key);
  }
  getAll() {
    return this.#storage.size > 0 ? (0, _util.objectFromMap)(this.#storage) : null;
  }
  get size() {
    return this.#storage.size;
  }
  #setModified() {
    if (!this.#modified) {
      this.#modified = true;
      if (typeof this.onSetModified === "function") {
        this.onSetModified();
      }
    }
  }
  resetModified() {
    if (this.#modified) {
      this.#modified = false;
      if (typeof this.onResetModified === "function") {
        this.onResetModified();
      }
    }
  }
  get print() {
    return new PrintAnnotationStorage(this);
  }
  get serializable() {
    if (this.#storage.size === 0) {
      return null;
    }
    const clone = new Map();
    for (const [key, val] of this.#storage) {
      const serialized = val instanceof _editor.AnnotationEditor ? val.serialize() : val;
      if (serialized) {
        clone.set(key, serialized);
      }
    }
    return clone;
  }
  static getHash(map) {
    if (!map) {
      return "";
    }
    const hash = new _murmurhash.MurmurHash3_64();
    for (const [key, val] of map) {
      hash.update(`${key}:${JSON.stringify(val)}`);
    }
    return hash.hexdigest();
  }
}
exports.AnnotationStorage = AnnotationStorage;
class PrintAnnotationStorage extends AnnotationStorage {
  #serializable = null;
  constructor(parent) {
    super();
    this.#serializable = structuredClone(parent.serializable);
  }
  get print() {
    (0, _util.unreachable)("Should not call PrintAnnotationStorage.print");
  }
  get serializable() {
    return this.#serializable;
  }
}
exports.PrintAnnotationStorage = PrintAnnotationStorage;

/***/ }),
/* 4 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.AnnotationEditor = void 0;
var _tools = __w_pdfjs_require__(5);
var _util = __w_pdfjs_require__(1);
class AnnotationEditor {
  #boundFocusin = this.focusin.bind(this);
  #boundFocusout = this.focusout.bind(this);
  #hasBeenSelected = false;
  #isEditing = false;
  #isInEditMode = false;
  _uiManager = null;
  #zIndex = AnnotationEditor._zIndex++;
  static _colorManager = new _tools.ColorManager();
  static _zIndex = 1;
  constructor(parameters) {
    if (this.constructor === AnnotationEditor) {
      (0, _util.unreachable)("Cannot initialize AnnotationEditor.");
    }
    this.parent = parameters.parent;
    this.id = parameters.id;
    this.width = this.height = null;
    this.pageIndex = parameters.parent.pageIndex;
    this.name = parameters.name;
    this.div = null;
    this._uiManager = parameters.uiManager;
    const {
      rotation,
      rawDims: {
        pageWidth,
        pageHeight,
        pageX,
        pageY
      }
    } = this.parent.viewport;
    this.rotation = rotation;
    this.pageDimensions = [pageWidth, pageHeight];
    this.pageTranslation = [pageX, pageY];
    const [width, height] = this.parentDimensions;
    this.x = parameters.x / width;
    this.y = parameters.y / height;
    this.isAttachedToDOM = false;
  }
  static get _defaultLineColor() {
    return (0, _util.shadow)(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText"));
  }
  addCommands(params) {
    this._uiManager.addCommands(params);
  }
  get currentLayer() {
    return this._uiManager.currentLayer;
  }
  setInBackground() {
    this.div.style.zIndex = 0;
  }
  setInForeground() {
    this.div.style.zIndex = this.#zIndex;
  }
  setParent(parent) {
    if (parent !== null) {
      this.pageIndex = parent.pageIndex;
      this.pageDimensions = parent.pageDimensions;
    }
    this.parent = parent;
  }
  focusin(event) {
    if (!this.#hasBeenSelected) {
      this.parent.setSelected(this);
    } else {
      this.#hasBeenSelected = false;
    }
  }
  focusout(event) {
    if (!this.isAttachedToDOM) {
      return;
    }
    const target = event.relatedTarget;
    if (target?.closest(`#${this.id}`)) {
      return;
    }
    event.preventDefault();
    if (!this.parent?.isMultipleSelection) {
      this.commitOrRemove();
    }
  }
  commitOrRemove() {
    if (this.isEmpty()) {
      this.remove();
    } else {
      this.commit();
    }
  }
  commit() {
    this.addToAnnotationStorage();
  }
  addToAnnotationStorage() {
    this._uiManager.addToAnnotationStorage(this);
  }
  dragstart(event) {
    const rect = this.parent.div.getBoundingClientRect();
    this.startX = event.clientX - rect.x;
    this.startY = event.clientY - rect.y;
    event.dataTransfer.setData("text/plain", this.id);
    event.dataTransfer.effectAllowed = "move";
  }
  setAt(x, y, tx, ty) {
    const [width, height] = this.parentDimensions;
    [tx, ty] = this.screenToPageTranslation(tx, ty);
    this.x = (x + tx) / width;
    this.y = (y + ty) / height;
    this.div.style.left = `${100 * this.x}%`;
    this.div.style.top = `${100 * this.y}%`;
  }
  translate(x, y) {
    const [width, height] = this.parentDimensions;
    [x, y] = this.screenToPageTranslation(x, y);
    this.x += x / width;
    this.y += y / height;
    this.div.style.left = `${100 * this.x}%`;
    this.div.style.top = `${100 * this.y}%`;
  }
  screenToPageTranslation(x, y) {
    switch (this.parentRotation) {
      case 90:
        return [y, -x];
      case 180:
        return [-x, -y];
      case 270:
        return [-y, x];
      default:
        return [x, y];
    }
  }
  get parentScale() {
    return this._uiManager.viewParameters.realScale;
  }
  get parentRotation() {
    return this._uiManager.viewParameters.rotation;
  }
  get parentDimensions() {
    const {
      realScale
    } = this._uiManager.viewParameters;
    const [pageWidth, pageHeight] = this.pageDimensions;
    return [pageWidth * realScale, pageHeight * realScale];
  }
  setDims(width, height) {
    const [parentWidth, parentHeight] = this.parentDimensions;
    this.div.style.width = `${100 * width / parentWidth}%`;
    this.div.style.height = `${100 * height / parentHeight}%`;
  }
  fixDims() {
    const {
      style
    } = this.div;
    const {
      height,
      width
    } = style;
    const widthPercent = width.endsWith("%");
    const heightPercent = height.endsWith("%");
    if (widthPercent && heightPercent) {
      return;
    }
    const [parentWidth, parentHeight] = this.parentDimensions;
    if (!widthPercent) {
      style.width = `${100 * parseFloat(width) / parentWidth}%`;
    }
    if (!heightPercent) {
      style.height = `${100 * parseFloat(height) / parentHeight}%`;
    }
  }
  getInitialTranslation() {
    return [0, 0];
  }
  render() {
    this.div = document.createElement("div");
    this.div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360);
    this.div.className = this.name;
    this.div.setAttribute("id", this.id);
    this.div.setAttribute("tabIndex", 0);
    this.setInForeground();
    this.div.addEventListener("focusin", this.#boundFocusin);
    this.div.addEventListener("focusout", this.#boundFocusout);
    const [tx, ty] = this.getInitialTranslation();
    this.translate(tx, ty);
    (0, _tools.bindEvents)(this, this.div, ["dragstart", "pointerdown"]);
    return this.div;
  }
  pointerdown(event) {
    const {
      isMac
    } = _util.FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      event.preventDefault();
      return;
    }
    if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) {
      this.parent.toggleSelected(this);
    } else {
      this.parent.setSelected(this);
    }
    this.#hasBeenSelected = true;
  }
  getRect(tx, ty) {
    const scale = this.parentScale;
    const [pageWidth, pageHeight] = this.pageDimensions;
    const [pageX, pageY] = this.pageTranslation;
    const shiftX = tx / scale;
    const shiftY = ty / scale;
    const x = this.x * pageWidth;
    const y = this.y * pageHeight;
    const width = this.width * pageWidth;
    const height = this.height * pageHeight;
    switch (this.rotation) {
      case 0:
        return [x + shiftX + pageX, pageHeight - y - shiftY - height + pageY, x + shiftX + width + pageX, pageHeight - y - shiftY + pageY];
      case 90:
        return [x + shiftY + pageX, pageHeight - y + shiftX + pageY, x + shiftY + height + pageX, pageHeight - y + shiftX + width + pageY];
      case 180:
        return [x - shiftX - width + pageX, pageHeight - y + shiftY + pageY, x - shiftX + pageX, pageHeight - y + shiftY + height + pageY];
      case 270:
        return [x - shiftY - height + pageX, pageHeight - y - shiftX - width + pageY, x - shiftY + pageX, pageHeight - y - shiftX + pageY];
      default:
        throw new Error("Invalid rotation");
    }
  }
  getRectInCurrentCoords(rect, pageHeight) {
    const [x1, y1, x2, y2] = rect;
    const width = x2 - x1;
    const height = y2 - y1;
    switch (this.rotation) {
      case 0:
        return [x1, pageHeight - y2, width, height];
      case 90:
        return [x1, pageHeight - y1, height, width];
      case 180:
        return [x2, pageHeight - y1, width, height];
      case 270:
        return [x2, pageHeight - y2, height, width];
      default:
        throw new Error("Invalid rotation");
    }
  }
  onceAdded() {}
  isEmpty() {
    return false;
  }
  enableEditMode() {
    this.#isInEditMode = true;
  }
  disableEditMode() {
    this.#isInEditMode = false;
  }
  isInEditMode() {
    return this.#isInEditMode;
  }
  shouldGetKeyboardEvents() {
    return false;
  }
  needsToBeRebuilt() {
    return this.div && !this.isAttachedToDOM;
  }
  rebuild() {
    this.div?.addEventListener("focusin", this.#boundFocusin);
  }
  serialize() {
    (0, _util.unreachable)("An editor must be serializable");
  }
  static deserialize(data, parent, uiManager) {
    const editor = new this.prototype.constructor({
      parent,
      id: parent.getNextId(),
      uiManager
    });
    editor.rotation = data.rotation;
    const [pageWidth, pageHeight] = editor.pageDimensions;
    const [x, y, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight);
    editor.x = x / pageWidth;
    editor.y = y / pageHeight;
    editor.width = width / pageWidth;
    editor.height = height / pageHeight;
    return editor;
  }
  remove() {
    this.div.removeEventListener("focusin", this.#boundFocusin);
    this.div.removeEventListener("focusout", this.#boundFocusout);
    if (!this.isEmpty()) {
      this.commit();
    }
    this.parent.remove(this);
  }
  select() {
    this.div?.classList.add("selectedEditor");
  }
  unselect() {
    this.div?.classList.remove("selectedEditor");
  }
  updateParams(type, value) {}
  disableEditing() {}
  enableEditing() {}
  get propertiesToUpdate() {
    return {};
  }
  get contentDiv() {
    return this.div;
  }
  get isEditing() {
    return this.#isEditing;
  }
  set isEditing(value) {
    this.#isEditing = value;
    if (value) {
      this.parent.setSelected(this);
      this.parent.setActiveEditor(this);
    } else {
      this.parent.setActiveEditor(null);
    }
  }
}
exports.AnnotationEditor = AnnotationEditor;

/***/ }),
/* 5 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
exports.bindEvents = bindEvents;
exports.opacityToHex = opacityToHex;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
function bindEvents(obj, element, names) {
  for (const name of names) {
    element.addEventListener(name, obj[name].bind(obj));
  }
}
function opacityToHex(opacity) {
  return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
}
class IdManager {
  #id = 0;
  getId() {
    return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  }
}
class CommandManager {
  #commands = [];
  #locked = false;
  #maxSize;
  #position = -1;
  constructor(maxSize = 128) {
    this.#maxSize = maxSize;
  }
  add({
    cmd,
    undo,
    mustExec,
    type = NaN,
    overwriteIfSameType = false,
    keepUndo = false
  }) {
    if (mustExec) {
      cmd();
    }
    if (this.#locked) {
      return;
    }
    const save = {
      cmd,
      undo,
      type
    };
    if (this.#position === -1) {
      if (this.#commands.length > 0) {
        this.#commands.length = 0;
      }
      this.#position = 0;
      this.#commands.push(save);
      return;
    }
    if (overwriteIfSameType && this.#commands[this.#position].type === type) {
      if (keepUndo) {
        save.undo = this.#commands[this.#position].undo;
      }
      this.#commands[this.#position] = save;
      return;
    }
    const next = this.#position + 1;
    if (next === this.#maxSize) {
      this.#commands.splice(0, 1);
    } else {
      this.#position = next;
      if (next < this.#commands.length) {
        this.#commands.splice(next);
      }
    }
    this.#commands.push(save);
  }
  undo() {
    if (this.#position === -1) {
      return;
    }
    this.#locked = true;
    this.#commands[this.#position].undo();
    this.#locked = false;
    this.#position -= 1;
  }
  redo() {
    if (this.#position < this.#commands.length - 1) {
      this.#position += 1;
      this.#locked = true;
      this.#commands[this.#position].cmd();
      this.#locked = false;
    }
  }
  hasSomethingToUndo() {
    return this.#position !== -1;
  }
  hasSomethingToRedo() {
    return this.#position < this.#commands.length - 1;
  }
  destroy() {
    this.#commands = null;
  }
}
exports.CommandManager = CommandManager;
class KeyboardManager {
  constructor(callbacks) {
    this.buffer = [];
    this.callbacks = new Map();
    this.allKeys = new Set();
    const {
      isMac
    } = _util.FeatureTest.platform;
    for (const [keys, callback] of callbacks) {
      for (const key of keys) {
        const isMacKey = key.startsWith("mac+");
        if (isMac && isMacKey) {
          this.callbacks.set(key.slice(4), callback);
          this.allKeys.add(key.split("+").at(-1));
        } else if (!isMac && !isMacKey) {
          this.callbacks.set(key, callback);
          this.allKeys.add(key.split("+").at(-1));
        }
      }
    }
  }
  #serialize(event) {
    if (event.altKey) {
      this.buffer.push("alt");
    }
    if (event.ctrlKey) {
      this.buffer.push("ctrl");
    }
    if (event.metaKey) {
      this.buffer.push("meta");
    }
    if (event.shiftKey) {
      this.buffer.push("shift");
    }
    this.buffer.push(event.key);
    const str = this.buffer.join("+");
    this.buffer.length = 0;
    return str;
  }
  exec(self, event) {
    if (!this.allKeys.has(event.key)) {
      return;
    }
    const callback = this.callbacks.get(this.#serialize(event));
    if (!callback) {
      return;
    }
    callback.bind(self)();
    event.stopPropagation();
    event.preventDefault();
  }
}
exports.KeyboardManager = KeyboardManager;
class ColorManager {
  static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  get _colors() {
    const colors = new Map([["CanvasText", null], ["Canvas", null]]);
    (0, _display_utils.getColorValues)(colors);
    return (0, _util.shadow)(this, "_colors", colors);
  }
  convert(color) {
    const rgb = (0, _display_utils.getRGB)(color);
    if (!window.matchMedia("(forced-colors: active)").matches) {
      return rgb;
    }
    for (const [name, RGB] of this._colors) {
      if (RGB.every((x, i) => x === rgb[i])) {
        return ColorManager._colorsMapping.get(name);
      }
    }
    return rgb;
  }
  getHexCode(name) {
    const rgb = this._colors.get(name);
    if (!rgb) {
      return name;
    }
    return _util.Util.makeHexColor(...rgb);
  }
}
exports.ColorManager = ColorManager;
class AnnotationEditorUIManager {
  #activeEditor = null;
  #allEditors = new Map();
  #allLayers = new Map();
  #annotationStorage = null;
  #commandManager = new CommandManager();
  #currentPageIndex = 0;
  #editorTypes = null;
  #editorsToRescale = new Set();
  #eventBus = null;
  #idManager = new IdManager();
  #isEnabled = false;
  #mode = _util.AnnotationEditorType.NONE;
  #selectedEditors = new Set();
  #boundCopy = this.copy.bind(this);
  #boundCut = this.cut.bind(this);
  #boundPaste = this.paste.bind(this);
  #boundKeydown = this.keydown.bind(this);
  #boundOnEditingAction = this.onEditingAction.bind(this);
  #boundOnPageChanging = this.onPageChanging.bind(this);
  #boundOnScaleChanging = this.onScaleChanging.bind(this);
  #boundOnRotationChanging = this.onRotationChanging.bind(this);
  #previousStates = {
    isEditing: false,
    isEmpty: true,
    hasSomethingToUndo: false,
    hasSomethingToRedo: false,
    hasSelectedEditor: false
  };
  #container = null;
  static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
  constructor(container, eventBus, annotationStorage) {
    this.#container = container;
    this.#eventBus = eventBus;
    this.#eventBus._on("editingaction", this.#boundOnEditingAction);
    this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
    this.#eventBus._on("scalechanging", this.#boundOnScaleChanging);
    this.#eventBus._on("rotationchanging", this.#boundOnRotationChanging);
    this.#annotationStorage = annotationStorage;
    this.viewParameters = {
      realScale: _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS,
      rotation: 0
    };
  }
  destroy() {
    this.#removeKeyboardManager();
    this.#eventBus._off("editingaction", this.#boundOnEditingAction);
    this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
    this.#eventBus._off("scalechanging", this.#boundOnScaleChanging);
    this.#eventBus._off("rotationchanging", this.#boundOnRotationChanging);
    for (const layer of this.#allLayers.values()) {
      layer.destroy();
    }
    this.#allLayers.clear();
    this.#allEditors.clear();
    this.#editorsToRescale.clear();
    this.#activeEditor = null;
    this.#selectedEditors.clear();
    this.#commandManager.destroy();
  }
  onPageChanging({
    pageNumber
  }) {
    this.#currentPageIndex = pageNumber - 1;
  }
  focusMainContainer() {
    this.#container.focus();
  }
  addShouldRescale(editor) {
    this.#editorsToRescale.add(editor);
  }
  removeShouldRescale(editor) {
    this.#editorsToRescale.delete(editor);
  }
  onScaleChanging({
    scale
  }) {
    this.commitOrRemove();
    this.viewParameters.realScale = scale * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS;
    for (const editor of this.#editorsToRescale) {
      editor.onScaleChanging();
    }
  }
  onRotationChanging({
    pagesRotation
  }) {
    this.commitOrRemove();
    this.viewParameters.rotation = pagesRotation;
  }
  addToAnnotationStorage(editor) {
    if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) {
      this.#annotationStorage.setValue(editor.id, editor);
    }
  }
  #addKeyboardManager() {
    this.#container.addEventListener("keydown", this.#boundKeydown);
  }
  #removeKeyboardManager() {
    this.#container.removeEventListener("keydown", this.#boundKeydown);
  }
  #addCopyPasteListeners() {
    document.addEventListener("copy", this.#boundCopy);
    document.addEventListener("cut", this.#boundCut);
    document.addEventListener("paste", this.#boundPaste);
  }
  #removeCopyPasteListeners() {
    document.removeEventListener("copy", this.#boundCopy);
    document.removeEventListener("cut", this.#boundCut);
    document.removeEventListener("paste", this.#boundPaste);
  }
  copy(event) {
    event.preventDefault();
    if (this.#activeEditor) {
      this.#activeEditor.commitOrRemove();
    }
    if (!this.hasSelection) {
      return;
    }
    const editors = [];
    for (const editor of this.#selectedEditors) {
      if (!editor.isEmpty()) {
        editors.push(editor.serialize());
      }
    }
    if (editors.length === 0) {
      return;
    }
    event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  }
  cut(event) {
    this.copy(event);
    this.delete();
  }
  paste(event) {
    event.preventDefault();
    let data = event.clipboardData.getData("application/pdfjs");
    if (!data) {
      return;
    }
    try {
      data = JSON.parse(data);
    } catch (ex) {
      (0, _util.warn)(`paste: "${ex.message}".`);
      return;
    }
    if (!Array.isArray(data)) {
      return;
    }
    this.unselectAll();
    const layer = this.#allLayers.get(this.#currentPageIndex);
    try {
      const newEditors = [];
      for (const editor of data) {
        const deserializedEditor = layer.deserialize(editor);
        if (!deserializedEditor) {
          return;
        }
        newEditors.push(deserializedEditor);
      }
      const cmd = () => {
        for (const editor of newEditors) {
          this.#addEditorToLayer(editor);
        }
        this.#selectEditors(newEditors);
      };
      const undo = () => {
        for (const editor of newEditors) {
          editor.remove();
        }
      };
      this.addCommands({
        cmd,
        undo,
        mustExec: true
      });
    } catch (ex) {
      (0, _util.warn)(`paste: "${ex.message}".`);
    }
  }
  keydown(event) {
    if (!this.getActive()?.shouldGetKeyboardEvents()) {
      AnnotationEditorUIManager._keyboardManager.exec(this, event);
    }
  }
  onEditingAction(details) {
    if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
      this[details.name]();
    }
  }
  #dispatchUpdateStates(details) {
    const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
    if (hasChanged) {
      this.#eventBus.dispatch("annotationeditorstateschanged", {
        source: this,
        details: Object.assign(this.#previousStates, details)
      });
    }
  }
  #dispatchUpdateUI(details) {
    this.#eventBus.dispatch("annotationeditorparamschanged", {
      source: this,
      details
    });
  }
  setEditingState(isEditing) {
    if (isEditing) {
      this.#addKeyboardManager();
      this.#addCopyPasteListeners();
      this.#dispatchUpdateStates({
        isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
        isEmpty: this.#isEmpty(),
        hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
        hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
        hasSelectedEditor: false
      });
    } else {
      this.#removeKeyboardManager();
      this.#removeCopyPasteListeners();
      this.#dispatchUpdateStates({
        isEditing: false
      });
    }
  }
  registerEditorTypes(types) {
    if (this.#editorTypes) {
      return;
    }
    this.#editorTypes = types;
    for (const editorType of this.#editorTypes) {
      this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
    }
  }
  getId() {
    return this.#idManager.getId();
  }
  get currentLayer() {
    return this.#allLayers.get(this.#currentPageIndex);
  }
  get currentPageIndex() {
    return this.#currentPageIndex;
  }
  addLayer(layer) {
    this.#allLayers.set(layer.pageIndex, layer);
    if (this.#isEnabled) {
      layer.enable();
    } else {
      layer.disable();
    }
  }
  removeLayer(layer) {
    this.#allLayers.delete(layer.pageIndex);
  }
  updateMode(mode) {
    this.#mode = mode;
    if (mode === _util.AnnotationEditorType.NONE) {
      this.setEditingState(false);
      this.#disableAll();
    } else {
      this.setEditingState(true);
      this.#enableAll();
      for (const layer of this.#allLayers.values()) {
        layer.updateMode(mode);
      }
    }
  }
  updateToolbar(mode) {
    if (mode === this.#mode) {
      return;
    }
    this.#eventBus.dispatch("switchannotationeditormode", {
      source: this,
      mode
    });
  }
  updateParams(type, value) {
    if (!this.#editorTypes) {
      return;
    }
    for (const editor of this.#selectedEditors) {
      editor.updateParams(type, value);
    }
    for (const editorType of this.#editorTypes) {
      editorType.updateDefaultParams(type, value);
    }
  }
  #enableAll() {
    if (!this.#isEnabled) {
      this.#isEnabled = true;
      for (const layer of this.#allLayers.values()) {
        layer.enable();
      }
    }
  }
  #disableAll() {
    this.unselectAll();
    if (this.#isEnabled) {
      this.#isEnabled = false;
      for (const layer of this.#allLayers.values()) {
        layer.disable();
      }
    }
  }
  getEditors(pageIndex) {
    const editors = [];
    for (const editor of this.#allEditors.values()) {
      if (editor.pageIndex === pageIndex) {
        editors.push(editor);
      }
    }
    return editors;
  }
  getEditor(id) {
    return this.#allEditors.get(id);
  }
  addEditor(editor) {
    this.#allEditors.set(editor.id, editor);
  }
  removeEditor(editor) {
    this.#allEditors.delete(editor.id);
    this.unselect(editor);
    this.#annotationStorage?.remove(editor.id);
  }
  #addEditorToLayer(editor) {
    const layer = this.#allLayers.get(editor.pageIndex);
    if (layer) {
      layer.addOrRebuild(editor);
    } else {
      this.addEditor(editor);
    }
  }
  setActiveEditor(editor) {
    if (this.#activeEditor === editor) {
      return;
    }
    this.#activeEditor = editor;
    if (editor) {
      this.#dispatchUpdateUI(editor.propertiesToUpdate);
    }
  }
  toggleSelected(editor) {
    if (this.#selectedEditors.has(editor)) {
      this.#selectedEditors.delete(editor);
      editor.unselect();
      this.#dispatchUpdateStates({
        hasSelectedEditor: this.hasSelection
      });
      return;
    }
    this.#selectedEditors.add(editor);
    editor.select();
    this.#dispatchUpdateUI(editor.propertiesToUpdate);
    this.#dispatchUpdateStates({
      hasSelectedEditor: true
    });
  }
  setSelected(editor) {
    for (const ed of this.#selectedEditors) {
      if (ed !== editor) {
        ed.unselect();
      }
    }
    this.#selectedEditors.clear();
    this.#selectedEditors.add(editor);
    editor.select();
    this.#dispatchUpdateUI(editor.propertiesToUpdate);
    this.#dispatchUpdateStates({
      hasSelectedEditor: true
    });
  }
  isSelected(editor) {
    return this.#selectedEditors.has(editor);
  }
  unselect(editor) {
    editor.unselect();
    this.#selectedEditors.delete(editor);
    this.#dispatchUpdateStates({
      hasSelectedEditor: this.hasSelection
    });
  }
  get hasSelection() {
    return this.#selectedEditors.size !== 0;
  }
  undo() {
    this.#commandManager.undo();
    this.#dispatchUpdateStates({
      hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
      hasSomethingToRedo: true,
      isEmpty: this.#isEmpty()
    });
  }
  redo() {
    this.#commandManager.redo();
    this.#dispatchUpdateStates({
      hasSomethingToUndo: true,
      hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
      isEmpty: this.#isEmpty()
    });
  }
  addCommands(params) {
    this.#commandManager.add(params);
    this.#dispatchUpdateStates({
      hasSomethingToUndo: true,
      hasSomethingToRedo: false,
      isEmpty: this.#isEmpty()
    });
  }
  #isEmpty() {
    if (this.#allEditors.size === 0) {
      return true;
    }
    if (this.#allEditors.size === 1) {
      for (const editor of this.#allEditors.values()) {
        return editor.isEmpty();
      }
    }
    return false;
  }
  delete() {
    this.commitOrRemove();
    if (!this.hasSelection) {
      return;
    }
    const editors = [...this.#selectedEditors];
    const cmd = () => {
      for (const editor of editors) {
        editor.remove();
      }
    };
    const undo = () => {
      for (const editor of editors) {
        this.#addEditorToLayer(editor);
      }
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: true
    });
  }
  commitOrRemove() {
    this.#activeEditor?.commitOrRemove();
  }
  #selectEditors(editors) {
    this.#selectedEditors.clear();
    for (const editor of editors) {
      if (editor.isEmpty()) {
        continue;
      }
      this.#selectedEditors.add(editor);
      editor.select();
    }
    this.#dispatchUpdateStates({
      hasSelectedEditor: true
    });
  }
  selectAll() {
    for (const editor of this.#selectedEditors) {
      editor.commit();
    }
    this.#selectEditors(this.#allEditors.values());
  }
  unselectAll() {
    if (this.#activeEditor) {
      this.#activeEditor.commitOrRemove();
      return;
    }
    if (this.#selectedEditors.size === 0) {
      return;
    }
    for (const editor of this.#selectedEditors) {
      editor.unselect();
    }
    this.#selectedEditors.clear();
    this.#dispatchUpdateStates({
      hasSelectedEditor: false
    });
  }
  isActive(editor) {
    return this.#activeEditor === editor;
  }
  getActive() {
    return this.#activeEditor;
  }
  getMode() {
    return this.#mode;
  }
}
exports.AnnotationEditorUIManager = AnnotationEditorUIManager;

/***/ }),
/* 6 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = exports.AnnotationPrefix = void 0;
exports.deprecated = deprecated;
exports.getColorValues = getColorValues;
exports.getCurrentTransform = getCurrentTransform;
exports.getCurrentTransformInverse = getCurrentTransformInverse;
exports.getFilenameFromUrl = getFilenameFromUrl;
exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
exports.getRGB = getRGB;
exports.getXfaPageViewport = getXfaPageViewport;
exports.isDataScheme = isDataScheme;
exports.isPdfFile = isPdfFile;
exports.isValidFetchUrl = isValidFetchUrl;
exports.loadScript = loadScript;
exports.setLayerDimensions = setLayerDimensions;
var _base_factory = __w_pdfjs_require__(7);
var _util = __w_pdfjs_require__(1);
const SVG_NS = "http://www.w3.org/2000/svg";
const AnnotationPrefix = "pdfjs_internal_id_";
exports.AnnotationPrefix = AnnotationPrefix;
class PixelsPerInch {
  static CSS = 96.0;
  static PDF = 72.0;
  static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
}
exports.PixelsPerInch = PixelsPerInch;
class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
  constructor({
    ownerDocument = globalThis.document
  } = {}) {
    super();
    this._document = ownerDocument;
  }
  _createCanvas(width, height) {
    const canvas = this._document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
}
exports.DOMCanvasFactory = DOMCanvasFactory;
async function fetchData(url, asTypedArray = false) {
  if (isValidFetchUrl(url, document.baseURI)) {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
  }
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    if (asTypedArray) {
      request.responseType = "arraybuffer";
    }
    request.onreadystatechange = () => {
      if (request.readyState !== XMLHttpRequest.DONE) {
        return;
      }
      if (request.status === 200 || request.status === 0) {
        let data;
        if (asTypedArray && request.response) {
          data = new Uint8Array(request.response);
        } else if (!asTypedArray && request.responseText) {
          data = (0, _util.stringToBytes)(request.responseText);
        }
        if (data) {
          resolve(data);
          return;
        }
      }
      reject(new Error(request.statusText));
    };
    request.send(null);
  });
}
class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  _fetchData(url, compressionType) {
    return fetchData(url, this.isCompressed).then(data => {
      return {
        cMapData: data,
        compressionType
      };
    });
  }
}
exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  _fetchData(url) {
    return fetchData(url, true);
  }
}
exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
class DOMSVGFactory extends _base_factory.BaseSVGFactory {
  _createSVG(type) {
    return document.createElementNS(SVG_NS, type);
  }
}
exports.DOMSVGFactory = DOMSVGFactory;
class PageViewport {
  constructor({
    viewBox,
    scale,
    rotation,
    offsetX = 0,
    offsetY = 0,
    dontFlip = false
  }) {
    this.viewBox = viewBox;
    this.scale = scale;
    this.rotation = rotation;
    this.offsetX = offsetX;
    this.offsetY = offsetY;
    const centerX = (viewBox[2] + viewBox[0]) / 2;
    const centerY = (viewBox[3] + viewBox[1]) / 2;
    let rotateA, rotateB, rotateC, rotateD;
    rotation %= 360;
    if (rotation < 0) {
      rotation += 360;
    }
    switch (rotation) {
      case 180:
        rotateA = -1;
        rotateB = 0;
        rotateC = 0;
        rotateD = 1;
        break;
      case 90:
        rotateA = 0;
        rotateB = 1;
        rotateC = 1;
        rotateD = 0;
        break;
      case 270:
        rotateA = 0;
        rotateB = -1;
        rotateC = -1;
        rotateD = 0;
        break;
      case 0:
        rotateA = 1;
        rotateB = 0;
        rotateC = 0;
        rotateD = -1;
        break;
      default:
        throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
    }
    if (dontFlip) {
      rotateC = -rotateC;
      rotateD = -rotateD;
    }
    let offsetCanvasX, offsetCanvasY;
    let width, height;
    if (rotateA === 0) {
      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
      width = (viewBox[3] - viewBox[1]) * scale;
      height = (viewBox[2] - viewBox[0]) * scale;
    } else {
      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
      width = (viewBox[2] - viewBox[0]) * scale;
      height = (viewBox[3] - viewBox[1]) * scale;
    }
    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
    this.width = width;
    this.height = height;
  }
  get rawDims() {
    const {
      viewBox
    } = this;
    return (0, _util.shadow)(this, "rawDims", {
      pageWidth: viewBox[2] - viewBox[0],
      pageHeight: viewBox[3] - viewBox[1],
      pageX: viewBox[0],
      pageY: viewBox[1]
    });
  }
  clone({
    scale = this.scale,
    rotation = this.rotation,
    offsetX = this.offsetX,
    offsetY = this.offsetY,
    dontFlip = false
  } = {}) {
    return new PageViewport({
      viewBox: this.viewBox.slice(),
      scale,
      rotation,
      offsetX,
      offsetY,
      dontFlip
    });
  }
  convertToViewportPoint(x, y) {
    return _util.Util.applyTransform([x, y], this.transform);
  }
  convertToViewportRectangle(rect) {
    const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
    const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
  }
  convertToPdfPoint(x, y) {
    return _util.Util.applyInverseTransform([x, y], this.transform);
  }
}
exports.PageViewport = PageViewport;
class RenderingCancelledException extends _util.BaseException {
  constructor(msg, type, extraDelay = 0) {
    super(msg, "RenderingCancelledException");
    this.type = type;
    this.extraDelay = extraDelay;
  }
}
exports.RenderingCancelledException = RenderingCancelledException;
function isDataScheme(url) {
  const ii = url.length;
  let i = 0;
  while (i < ii && url[i].trim() === "") {
    i++;
  }
  return url.substring(i, i + 5).toLowerCase() === "data:";
}
function isPdfFile(filename) {
  return typeof filename === "string" && /\.pdf$/i.test(filename);
}
function getFilenameFromUrl(url, onlyStripPath = false) {
  if (!onlyStripPath) {
    [url] = url.split(/[#?]/, 1);
  }
  return url.substring(url.lastIndexOf("/") + 1);
}
function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
  if (typeof url !== "string") {
    return defaultFilename;
  }
  if (isDataScheme(url)) {
    (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
    return defaultFilename;
  }
  const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  const splitURI = reURI.exec(url);
  let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  if (suggestedFilename) {
    suggestedFilename = suggestedFilename[0];
    if (suggestedFilename.includes("%")) {
      try {
        suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
      } catch (ex) {}
    }
  }
  return suggestedFilename || defaultFilename;
}
class StatTimer {
  started = Object.create(null);
  times = [];
  time(name) {
    if (name in this.started) {
      (0, _util.warn)(`Timer is already running for ${name}`);
    }
    this.started[name] = Date.now();
  }
  timeEnd(name) {
    if (!(name in this.started)) {
      (0, _util.warn)(`Timer has not been started for ${name}`);
    }
    this.times.push({
      name,
      start: this.started[name],
      end: Date.now()
    });
    delete this.started[name];
  }
  toString() {
    const outBuf = [];
    let longest = 0;
    for (const {
      name
    } of this.times) {
      longest = Math.max(name.length, longest);
    }
    for (const {
      name,
      start,
      end
    } of this.times) {
      outBuf.push(`${name.padEnd(longest)} ${end - start}ms\n`);
    }
    return outBuf.join("");
  }
}
exports.StatTimer = StatTimer;
function isValidFetchUrl(url, baseUrl) {
  try {
    const {
      protocol
    } = baseUrl ? new URL(url, baseUrl) : new URL(url);
    return protocol === "http:" || protocol === "https:";
  } catch (ex) {
    return false;
  }
}
function loadScript(src, removeScriptElement = false) {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = src;
    script.onload = function (evt) {
      if (removeScriptElement) {
        script.remove();
      }
      resolve(evt);
    };
    script.onerror = function () {
      reject(new Error(`Cannot load script at: ${script.src}`));
    };
    (document.head || document.documentElement).append(script);
  });
}
function deprecated(details) {
  console.log("Deprecated API usage: " + details);
}
let pdfDateStringRegex;
class PDFDateString {
  static toDateObject(input) {
    if (!input || typeof input !== "string") {
      return null;
    }
    if (!pdfDateStringRegex) {
      pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
    }
    const matches = pdfDateStringRegex.exec(input);
    if (!matches) {
      return null;
    }
    const year = parseInt(matches[1], 10);
    let month = parseInt(matches[2], 10);
    month = month >= 1 && month <= 12 ? month - 1 : 0;
    let day = parseInt(matches[3], 10);
    day = day >= 1 && day <= 31 ? day : 1;
    let hour = parseInt(matches[4], 10);
    hour = hour >= 0 && hour <= 23 ? hour : 0;
    let minute = parseInt(matches[5], 10);
    minute = minute >= 0 && minute <= 59 ? minute : 0;
    let second = parseInt(matches[6], 10);
    second = second >= 0 && second <= 59 ? second : 0;
    const universalTimeRelation = matches[7] || "Z";
    let offsetHour = parseInt(matches[8], 10);
    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
    let offsetMinute = parseInt(matches[9], 10) || 0;
    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
    if (universalTimeRelation === "-") {
      hour += offsetHour;
      minute += offsetMinute;
    } else if (universalTimeRelation === "+") {
      hour -= offsetHour;
      minute -= offsetMinute;
    }
    return new Date(Date.UTC(year, month, day, hour, minute, second));
  }
}
exports.PDFDateString = PDFDateString;
function getXfaPageViewport(xfaPage, {
  scale = 1,
  rotation = 0
}) {
  const {
    width,
    height
  } = xfaPage.attributes.style;
  const viewBox = [0, 0, parseInt(width), parseInt(height)];
  return new PageViewport({
    viewBox,
    scale,
    rotation
  });
}
function getRGB(color) {
  if (color.startsWith("#")) {
    const colorRGB = parseInt(color.slice(1), 16);
    return [(colorRGB & 0xff0000) >> 16, (colorRGB & 0x00ff00) >> 8, colorRGB & 0x0000ff];
  }
  if (color.startsWith("rgb(")) {
    return color.slice(4, -1).split(",").map(x => parseInt(x));
  }
  if (color.startsWith("rgba(")) {
    return color.slice(5, -1).split(",").map(x => parseInt(x)).slice(0, 3);
  }
  (0, _util.warn)(`Not a valid color format: "${color}"`);
  return [0, 0, 0];
}
function getColorValues(colors) {
  const span = document.createElement("span");
  span.style.visibility = "hidden";
  document.body.append(span);
  for (const name of colors.keys()) {
    span.style.color = name;
    const computedColor = window.getComputedStyle(span).color;
    colors.set(name, getRGB(computedColor));
  }
  span.remove();
}
function getCurrentTransform(ctx) {
  const {
    a,
    b,
    c,
    d,
    e,
    f
  } = ctx.getTransform();
  return [a, b, c, d, e, f];
}
function getCurrentTransformInverse(ctx) {
  const {
    a,
    b,
    c,
    d,
    e,
    f
  } = ctx.getTransform().invertSelf();
  return [a, b, c, d, e, f];
}
function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) {
  if (viewport instanceof PageViewport) {
    const {
      pageWidth,
      pageHeight
    } = viewport.rawDims;
    const {
      style
    } = div;
    const widthStr = `calc(var(--scale-factor) * ${pageWidth}px)`;
    const heightStr = `calc(var(--scale-factor) * ${pageHeight}px)`;
    if (!mustFlip || viewport.rotation % 180 === 0) {
      style.width = widthStr;
      style.height = heightStr;
    } else {
      style.width = heightStr;
      style.height = widthStr;
    }
  }
  if (mustRotate) {
    div.setAttribute("data-main-rotation", viewport.rotation);
  }
}

/***/ }),
/* 7 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
var _util = __w_pdfjs_require__(1);
class BaseCanvasFactory {
  constructor() {
    if (this.constructor === BaseCanvasFactory) {
      (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
    }
  }
  create(width, height) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    const canvas = this._createCanvas(width, height);
    return {
      canvas,
      context: canvas.getContext("2d")
    };
  }
  reset(canvasAndContext, width, height) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    canvasAndContext.canvas.width = width;
    canvasAndContext.canvas.height = height;
  }
  destroy(canvasAndContext) {
    if (!canvasAndContext.canvas) {
      throw new Error("Canvas is not specified");
    }
    canvasAndContext.canvas.width = 0;
    canvasAndContext.canvas.height = 0;
    canvasAndContext.canvas = null;
    canvasAndContext.context = null;
  }
  _createCanvas(width, height) {
    (0, _util.unreachable)("Abstract method `_createCanvas` called.");
  }
}
exports.BaseCanvasFactory = BaseCanvasFactory;
class BaseCMapReaderFactory {
  constructor({
    baseUrl = null,
    isCompressed = true
  }) {
    if (this.constructor === BaseCMapReaderFactory) {
      (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
    }
    this.baseUrl = baseUrl;
    this.isCompressed = isCompressed;
  }
  async fetch({
    name
  }) {
    if (!this.baseUrl) {
      throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
    }
    if (!name) {
      throw new Error("CMap name must be specified.");
    }
    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
    const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
    return this._fetchData(url, compressionType).catch(reason => {
      throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
    });
  }
  _fetchData(url, compressionType) {
    (0, _util.unreachable)("Abstract method `_fetchData` called.");
  }
}
exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
class BaseStandardFontDataFactory {
  constructor({
    baseUrl = null
  }) {
    if (this.constructor === BaseStandardFontDataFactory) {
      (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
    }
    this.baseUrl = baseUrl;
  }
  async fetch({
    filename
  }) {
    if (!this.baseUrl) {
      throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
    }
    if (!filename) {
      throw new Error("Font filename must be specified.");
    }
    const url = `${this.baseUrl}${filename}`;
    return this._fetchData(url).catch(reason => {
      throw new Error(`Unable to load font data at: ${url}`);
    });
  }
  _fetchData(url) {
    (0, _util.unreachable)("Abstract method `_fetchData` called.");
  }
}
exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
class BaseSVGFactory {
  constructor() {
    if (this.constructor === BaseSVGFactory) {
      (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
    }
  }
  create(width, height, skipDimensions = false) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid SVG dimensions");
    }
    const svg = this._createSVG("svg:svg");
    svg.setAttribute("version", "1.1");
    if (!skipDimensions) {
      svg.setAttribute("width", `${width}px`);
      svg.setAttribute("height", `${height}px`);
    }
    svg.setAttribute("preserveAspectRatio", "none");
    svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
    return svg;
  }
  createElement(type) {
    if (typeof type !== "string") {
      throw new Error("Invalid SVG element type");
    }
    return this._createSVG(type);
  }
  _createSVG(type) {
    (0, _util.unreachable)("Abstract method `_createSVG` called.");
  }
}
exports.BaseSVGFactory = BaseSVGFactory;

/***/ }),
/* 8 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MurmurHash3_64 = void 0;
var _util = __w_pdfjs_require__(1);
const SEED = 0xc3d2e1f0;
const MASK_HIGH = 0xffff0000;
const MASK_LOW = 0xffff;
class MurmurHash3_64 {
  constructor(seed) {
    this.h1 = seed ? seed & 0xffffffff : SEED;
    this.h2 = seed ? seed & 0xffffffff : SEED;
  }
  update(input) {
    let data, length;
    if (typeof input === "string") {
      data = new Uint8Array(input.length * 2);
      length = 0;
      for (let i = 0, ii = input.length; i < ii; i++) {
        const code = input.charCodeAt(i);
        if (code <= 0xff) {
          data[length++] = code;
        } else {
          data[length++] = code >>> 8;
          data[length++] = code & 0xff;
        }
      }
    } else if ((0, _util.isArrayBuffer)(input)) {
      data = input.slice();
      length = data.byteLength;
    } else {
      throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
    }
    const blockCounts = length >> 2;
    const tailLength = length - blockCounts * 4;
    const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
    let k1 = 0,
      k2 = 0;
    let h1 = this.h1,
      h2 = this.h2;
    const C1 = 0xcc9e2d51,
      C2 = 0x1b873593;
    const C1_LOW = C1 & MASK_LOW,
      C2_LOW = C2 & MASK_LOW;
    for (let i = 0; i < blockCounts; i++) {
      if (i & 1) {
        k1 = dataUint32[i];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        h1 ^= k1;
        h1 = h1 << 13 | h1 >>> 19;
        h1 = h1 * 5 + 0xe6546b64;
      } else {
        k2 = dataUint32[i];
        k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
        k2 = k2 << 15 | k2 >>> 17;
        k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
        h2 ^= k2;
        h2 = h2 << 13 | h2 >>> 19;
        h2 = h2 * 5 + 0xe6546b64;
      }
    }
    k1 = 0;
    switch (tailLength) {
      case 3:
        k1 ^= data[blockCounts * 4 + 2] << 16;
      case 2:
        k1 ^= data[blockCounts * 4 + 1] << 8;
      case 1:
        k1 ^= data[blockCounts * 4];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        if (blockCounts & 1) {
          h1 ^= k1;
        } else {
          h2 ^= k1;
        }
    }
    this.h1 = h1;
    this.h2 = h2;
  }
  hexdigest() {
    let h1 = this.h1,
      h2 = this.h2;
    h1 ^= h2 >>> 1;
    h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
    h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
    h1 ^= h2 >>> 1;
    h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
    h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
    h1 ^= h2 >>> 1;
    return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  }
}
exports.MurmurHash3_64 = MurmurHash3_64;

/***/ }),
/* 9 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FontLoader = exports.FontFaceObject = void 0;
var _util = __w_pdfjs_require__(1);
var _is_node = __w_pdfjs_require__(10);
class FontLoader {
  constructor({
    onUnsupportedFeature,
    ownerDocument = globalThis.document,
    styleElement = null
  }) {
    this._onUnsupportedFeature = onUnsupportedFeature;
    this._document = ownerDocument;
    this.nativeFontFaces = [];
    this.styleElement = null;
    this.loadingRequests = [];
    this.loadTestFontId = 0;
  }
  addNativeFontFace(nativeFontFace) {
    this.nativeFontFaces.push(nativeFontFace);
    this._document.fonts.add(nativeFontFace);
  }
  insertRule(rule) {
    if (!this.styleElement) {
      this.styleElement = this._document.createElement("style");
      this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);
    }
    const styleSheet = this.styleElement.sheet;
    styleSheet.insertRule(rule, styleSheet.cssRules.length);
  }
  clear() {
    for (const nativeFontFace of this.nativeFontFaces) {
      this._document.fonts.delete(nativeFontFace);
    }
    this.nativeFontFaces.length = 0;
    if (this.styleElement) {
      this.styleElement.remove();
      this.styleElement = null;
    }
  }
  async bind(font) {
    if (font.attached || font.missingFile) {
      return;
    }
    font.attached = true;
    if (this.isFontLoadingAPISupported) {
      const nativeFontFace = font.createNativeFontFace();
      if (nativeFontFace) {
        this.addNativeFontFace(nativeFontFace);
        try {
          await nativeFontFace.loaded;
        } catch (ex) {
          this._onUnsupportedFeature({
            featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
          });
          (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
          font.disableFontFace = true;
          throw ex;
        }
      }
      return;
    }
    const rule = font.createFontFaceRule();
    if (rule) {
      this.insertRule(rule);
      if (this.isSyncFontLoadingSupported) {
        return;
      }
      await new Promise(resolve => {
        const request = this._queueLoadingCallback(resolve);
        this._prepareFontLoadEvent(font, request);
      });
    }
  }
  get isFontLoadingAPISupported() {
    const hasFonts = !!this._document?.fonts;
    return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
  }
  get isSyncFontLoadingSupported() {
    let supported = false;
    if (_is_node.isNodeJS) {
      supported = true;
    } else if (typeof navigator !== "undefined" && /Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)) {
      supported = true;
    }
    return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
  }
  _queueLoadingCallback(callback) {
    function completeRequest() {
      (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
      request.done = true;
      while (loadingRequests.length > 0 && loadingRequests[0].done) {
        const otherRequest = loadingRequests.shift();
        setTimeout(otherRequest.callback, 0);
      }
    }
    const {
      loadingRequests
    } = this;
    const request = {
      done: false,
      complete: completeRequest,
      callback
    };
    loadingRequests.push(request);
    return request;
  }
  get _loadTestFont() {
    const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
    return (0, _util.shadow)(this, "_loadTestFont", testFont);
  }
  _prepareFontLoadEvent(font, request) {
    function int32(data, offset) {
      return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
    }
    function spliceString(s, offset, remove, insert) {
      const chunk1 = s.substring(0, offset);
      const chunk2 = s.substring(offset + remove);
      return chunk1 + insert + chunk2;
    }
    let i, ii;
    const canvas = this._document.createElement("canvas");
    canvas.width = 1;
    canvas.height = 1;
    const ctx = canvas.getContext("2d");
    let called = 0;
    function isFontReady(name, callback) {
      if (++called > 30) {
        (0, _util.warn)("Load test font never loaded.");
        callback();
        return;
      }
      ctx.font = "30px " + name;
      ctx.fillText(".", 0, 20);
      const imageData = ctx.getImageData(0, 0, 1, 1);
      if (imageData.data[3] > 0) {
        callback();
        return;
      }
      setTimeout(isFontReady.bind(null, name, callback));
    }
    const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
    let data = this._loadTestFont;
    const COMMENT_OFFSET = 976;
    data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
    const CFF_CHECKSUM_OFFSET = 16;
    const XXXX_VALUE = 0x58585858;
    let checksum = int32(data, CFF_CHECKSUM_OFFSET);
    for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
      checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
    }
    if (i < loadTestFontId.length) {
      checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
    }
    data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
    const url = `url(data:font/opentype;base64,${btoa(data)});`;
    const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
    this.insertRule(rule);
    const div = this._document.createElement("div");
    div.style.visibility = "hidden";
    div.style.width = div.style.height = "10px";
    div.style.position = "absolute";
    div.style.top = div.style.left = "0px";
    for (const name of [font.loadedName, loadTestFontId]) {
      const span = this._document.createElement("span");
      span.textContent = "Hi";
      span.style.fontFamily = name;
      div.append(span);
    }
    this._document.body.append(div);
    isFontReady(loadTestFontId, () => {
      div.remove();
      request.complete();
    });
  }
}
exports.FontLoader = FontLoader;
class FontFaceObject {
  constructor(translatedData, {
    isEvalSupported = true,
    disableFontFace = false,
    ignoreErrors = false,
    onUnsupportedFeature,
    fontRegistry = null
  }) {
    this.compiledGlyphs = Object.create(null);
    for (const i in translatedData) {
      this[i] = translatedData[i];
    }
    this.isEvalSupported = isEvalSupported !== false;
    this.disableFontFace = disableFontFace === true;
    this.ignoreErrors = ignoreErrors === true;
    this._onUnsupportedFeature = onUnsupportedFeature;
    this.fontRegistry = fontRegistry;
  }
  createNativeFontFace() {
    if (!this.data || this.disableFontFace) {
      return null;
    }
    let nativeFontFace;
    if (!this.cssFontInfo) {
      nativeFontFace = new FontFace(this.loadedName, this.data, {});
    } else {
      const css = {
        weight: this.cssFontInfo.fontWeight
      };
      if (this.cssFontInfo.italicAngle) {
        css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
      }
      nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
    }
    this.fontRegistry?.registerFont(this);
    return nativeFontFace;
  }
  createFontFaceRule() {
    if (!this.data || this.disableFontFace) {
      return null;
    }
    const data = (0, _util.bytesToString)(this.data);
    const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
    let rule;
    if (!this.cssFontInfo) {
      rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
    } else {
      let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
      if (this.cssFontInfo.italicAngle) {
        css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
      }
      rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
    }
    this.fontRegistry?.registerFont(this, url);
    return rule;
  }
  getPathGenerator(objs, character) {
    if (this.compiledGlyphs[character] !== undefined) {
      return this.compiledGlyphs[character];
    }
    let cmds;
    try {
      cmds = objs.get(this.loadedName + "_path_" + character);
    } catch (ex) {
      if (!this.ignoreErrors) {
        throw ex;
      }
      this._onUnsupportedFeature({
        featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
      });
      (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
      return this.compiledGlyphs[character] = function (c, size) {};
    }
    if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
      const jsBuf = [];
      for (const current of cmds) {
        const args = current.args !== undefined ? current.args.join(",") : "";
        jsBuf.push("c.", current.cmd, "(", args, ");\n");
      }
      return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
    }
    return this.compiledGlyphs[character] = function (c, size) {
      for (const current of cmds) {
        if (current.cmd === "scale") {
          current.args = [size, -size];
        }
        c[current.cmd].apply(c, current.args);
      }
    };
  }
}
exports.FontFaceObject = FontFaceObject;

/***/ }),
/* 10 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.isNodeJS = void 0;
const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
exports.isNodeJS = isNodeJS;

/***/ }),
/* 11 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CanvasGraphics = void 0;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
var _pattern_helper = __w_pdfjs_require__(12);
var _image_utils = __w_pdfjs_require__(13);
const MIN_FONT_SIZE = 16;
const MAX_FONT_SIZE = 100;
const MAX_GROUP_SIZE = 4096;
const EXECUTION_TIME = 15;
const EXECUTION_STEPS = 10;
const MAX_SIZE_TO_COMPILE = 1000;
const FULL_CHUNK_HEIGHT = 16;
function mirrorContextOperations(ctx, destCtx) {
  if (ctx._removeMirroring) {
    throw new Error("Context is already forwarding operations.");
  }
  ctx.__originalSave = ctx.save;
  ctx.__originalRestore = ctx.restore;
  ctx.__originalRotate = ctx.rotate;
  ctx.__originalScale = ctx.scale;
  ctx.__originalTranslate = ctx.translate;
  ctx.__originalTransform = ctx.transform;
  ctx.__originalSetTransform = ctx.setTransform;
  ctx.__originalResetTransform = ctx.resetTransform;
  ctx.__originalClip = ctx.clip;
  ctx.__originalMoveTo = ctx.moveTo;
  ctx.__originalLineTo = ctx.lineTo;
  ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
  ctx.__originalRect = ctx.rect;
  ctx.__originalClosePath = ctx.closePath;
  ctx.__originalBeginPath = ctx.beginPath;
  ctx._removeMirroring = () => {
    ctx.save = ctx.__originalSave;
    ctx.restore = ctx.__originalRestore;
    ctx.rotate = ctx.__originalRotate;
    ctx.scale = ctx.__originalScale;
    ctx.translate = ctx.__originalTranslate;
    ctx.transform = ctx.__originalTransform;
    ctx.setTransform = ctx.__originalSetTransform;
    ctx.resetTransform = ctx.__originalResetTransform;
    ctx.clip = ctx.__originalClip;
    ctx.moveTo = ctx.__originalMoveTo;
    ctx.lineTo = ctx.__originalLineTo;
    ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
    ctx.rect = ctx.__originalRect;
    ctx.closePath = ctx.__originalClosePath;
    ctx.beginPath = ctx.__originalBeginPath;
    delete ctx._removeMirroring;
  };
  ctx.save = function ctxSave() {
    destCtx.save();
    this.__originalSave();
  };
  ctx.restore = function ctxRestore() {
    destCtx.restore();
    this.__originalRestore();
  };
  ctx.translate = function ctxTranslate(x, y) {
    destCtx.translate(x, y);
    this.__originalTranslate(x, y);
  };
  ctx.scale = function ctxScale(x, y) {
    destCtx.scale(x, y);
    this.__originalScale(x, y);
  };
  ctx.transform = function ctxTransform(a, b, c, d, e, f) {
    destCtx.transform(a, b, c, d, e, f);
    this.__originalTransform(a, b, c, d, e, f);
  };
  ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
    destCtx.setTransform(a, b, c, d, e, f);
    this.__originalSetTransform(a, b, c, d, e, f);
  };
  ctx.resetTransform = function ctxResetTransform() {
    destCtx.resetTransform();
    this.__originalResetTransform();
  };
  ctx.rotate = function ctxRotate(angle) {
    destCtx.rotate(angle);
    this.__originalRotate(angle);
  };
  ctx.clip = function ctxRotate(rule) {
    destCtx.clip(rule);
    this.__originalClip(rule);
  };
  ctx.moveTo = function (x, y) {
    destCtx.moveTo(x, y);
    this.__originalMoveTo(x, y);
  };
  ctx.lineTo = function (x, y) {
    destCtx.lineTo(x, y);
    this.__originalLineTo(x, y);
  };
  ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
    destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
    this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
  };
  ctx.rect = function (x, y, width, height) {
    destCtx.rect(x, y, width, height);
    this.__originalRect(x, y, width, height);
  };
  ctx.closePath = function () {
    destCtx.closePath();
    this.__originalClosePath();
  };
  ctx.beginPath = function () {
    destCtx.beginPath();
    this.__originalBeginPath();
  };
}
class CachedCanvases {
  constructor(canvasFactory) {
    this.canvasFactory = canvasFactory;
    this.cache = Object.create(null);
  }
  getCanvas(id, width, height) {
    let canvasEntry;
    if (this.cache[id] !== undefined) {
      canvasEntry = this.cache[id];
      this.canvasFactory.reset(canvasEntry, width, height);
    } else {
      canvasEntry = this.canvasFactory.create(width, height);
      this.cache[id] = canvasEntry;
    }
    return canvasEntry;
  }
  delete(id) {
    delete this.cache[id];
  }
  clear() {
    for (const id in this.cache) {
      const canvasEntry = this.cache[id];
      this.canvasFactory.destroy(canvasEntry);
      delete this.cache[id];
    }
  }
}
function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
  const [a, b, c, d, tx, ty] = (0, _display_utils.getCurrentTransform)(ctx);
  if (b === 0 && c === 0) {
    const tlX = destX * a + tx;
    const rTlX = Math.round(tlX);
    const tlY = destY * d + ty;
    const rTlY = Math.round(tlY);
    const brX = (destX + destW) * a + tx;
    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
    const brY = (destY + destH) * d + ty;
    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
    ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
    ctx.setTransform(a, b, c, d, tx, ty);
    return [rWidth, rHeight];
  }
  if (a === 0 && d === 0) {
    const tlX = destY * c + tx;
    const rTlX = Math.round(tlX);
    const tlY = destX * b + ty;
    const rTlY = Math.round(tlY);
    const brX = (destY + destH) * c + tx;
    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
    const brY = (destX + destW) * b + ty;
    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
    ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
    ctx.setTransform(a, b, c, d, tx, ty);
    return [rHeight, rWidth];
  }
  ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
  const scaleX = Math.hypot(a, b);
  const scaleY = Math.hypot(c, d);
  return [scaleX * destW, scaleY * destH];
}
function compileType3Glyph(imgData) {
  const {
    width,
    height
  } = imgData;
  if (width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
    return null;
  }
  const POINT_TO_PROCESS_LIMIT = 1000;
  const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  const width1 = width + 1;
  let points = new Uint8Array(width1 * (height + 1));
  let i, j, j0;
  const lineSize = width + 7 & ~7;
  let data = new Uint8Array(lineSize * height),
    pos = 0;
  for (const elem of imgData.data) {
    let mask = 128;
    while (mask > 0) {
      data[pos++] = elem & mask ? 0 : 255;
      mask >>= 1;
    }
  }
  let count = 0;
  pos = 0;
  if (data[pos] !== 0) {
    points[0] = 1;
    ++count;
  }
  for (j = 1; j < width; j++) {
    if (data[pos] !== data[pos + 1]) {
      points[j] = data[pos] ? 2 : 1;
      ++count;
    }
    pos++;
  }
  if (data[pos] !== 0) {
    points[j] = 2;
    ++count;
  }
  for (i = 1; i < height; i++) {
    pos = i * lineSize;
    j0 = i * width1;
    if (data[pos - lineSize] !== data[pos]) {
      points[j0] = data[pos] ? 1 : 8;
      ++count;
    }
    let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
    for (j = 1; j < width; j++) {
      sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
      if (POINT_TYPES[sum]) {
        points[j0 + j] = POINT_TYPES[sum];
        ++count;
      }
      pos++;
    }
    if (data[pos - lineSize] !== data[pos]) {
      points[j0 + j] = data[pos] ? 2 : 4;
      ++count;
    }
    if (count > POINT_TO_PROCESS_LIMIT) {
      return null;
    }
  }
  pos = lineSize * (height - 1);
  j0 = i * width1;
  if (data[pos] !== 0) {
    points[j0] = 8;
    ++count;
  }
  for (j = 1; j < width; j++) {
    if (data[pos] !== data[pos + 1]) {
      points[j0 + j] = data[pos] ? 4 : 8;
      ++count;
    }
    pos++;
  }
  if (data[pos] !== 0) {
    points[j0 + j] = 4;
    ++count;
  }
  if (count > POINT_TO_PROCESS_LIMIT) {
    return null;
  }
  const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  const path = new Path2D();
  for (i = 0; count && i <= height; i++) {
    let p = i * width1;
    const end = p + width;
    while (p < end && !points[p]) {
      p++;
    }
    if (p === end) {
      continue;
    }
    path.moveTo(p % width1, i);
    const p0 = p;
    let type = points[p];
    do {
      const step = steps[type];
      do {
        p += step;
      } while (!points[p]);
      const pp = points[p];
      if (pp !== 5 && pp !== 10) {
        type = pp;
        points[p] = 0;
      } else {
        type = pp & 0x33 * type >> 4;
        points[p] &= type >> 2 | type << 2;
      }
      path.lineTo(p % width1, p / width1 | 0);
      if (!points[p]) {
        --count;
      }
    } while (p0 !== p);
    --i;
  }
  data = null;
  points = null;
  const drawOutline = function (c) {
    c.save();
    c.scale(1 / width, -1 / height);
    c.translate(0, -height);
    c.fill(path);
    c.beginPath();
    c.restore();
  };
  return drawOutline;
}
class CanvasExtraState {
  constructor(width, height) {
    this.alphaIsShape = false;
    this.fontSize = 0;
    this.fontSizeScale = 1;
    this.textMatrix = _util.IDENTITY_MATRIX;
    this.textMatrixScale = 1;
    this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
    this.leading = 0;
    this.x = 0;
    this.y = 0;
    this.lineX = 0;
    this.lineY = 0;
    this.charSpacing = 0;
    this.wordSpacing = 0;
    this.textHScale = 1;
    this.textRenderingMode = _util.TextRenderingMode.FILL;
    this.textRise = 0;
    this.fillColor = "#000000";
    this.strokeColor = "#000000";
    this.patternFill = false;
    this.fillAlpha = 1;
    this.strokeAlpha = 1;
    this.lineWidth = 1;
    this.activeSMask = null;
    this.transferMaps = null;
    this.startNewPathAndClipBox([0, 0, width, height]);
  }
  clone() {
    const clone = Object.create(this);
    clone.clipBox = this.clipBox.slice();
    return clone;
  }
  setCurrentPoint(x, y) {
    this.x = x;
    this.y = y;
  }
  updatePathMinMax(transform, x, y) {
    [x, y] = _util.Util.applyTransform([x, y], transform);
    this.minX = Math.min(this.minX, x);
    this.minY = Math.min(this.minY, y);
    this.maxX = Math.max(this.maxX, x);
    this.maxY = Math.max(this.maxY, y);
  }
  updateRectMinMax(transform, rect) {
    const p1 = _util.Util.applyTransform(rect, transform);
    const p2 = _util.Util.applyTransform(rect.slice(2), transform);
    this.minX = Math.min(this.minX, p1[0], p2[0]);
    this.minY = Math.min(this.minY, p1[1], p2[1]);
    this.maxX = Math.max(this.maxX, p1[0], p2[0]);
    this.maxY = Math.max(this.maxY, p1[1], p2[1]);
  }
  updateScalingPathMinMax(transform, minMax) {
    _util.Util.scaleMinMax(transform, minMax);
    this.minX = Math.min(this.minX, minMax[0]);
    this.maxX = Math.max(this.maxX, minMax[1]);
    this.minY = Math.min(this.minY, minMax[2]);
    this.maxY = Math.max(this.maxY, minMax[3]);
  }
  updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
    const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
    if (minMax) {
      minMax[0] = Math.min(minMax[0], box[0], box[2]);
      minMax[1] = Math.max(minMax[1], box[0], box[2]);
      minMax[2] = Math.min(minMax[2], box[1], box[3]);
      minMax[3] = Math.max(minMax[3], box[1], box[3]);
      return;
    }
    this.updateRectMinMax(transform, box);
  }
  getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
    const box = [this.minX, this.minY, this.maxX, this.maxY];
    if (pathType === _pattern_helper.PathType.STROKE) {
      if (!transform) {
        (0, _util.unreachable)("Stroke bounding box must include transform.");
      }
      const scale = _util.Util.singularValueDecompose2dScale(transform);
      const xStrokePad = scale[0] * this.lineWidth / 2;
      const yStrokePad = scale[1] * this.lineWidth / 2;
      box[0] -= xStrokePad;
      box[1] -= yStrokePad;
      box[2] += xStrokePad;
      box[3] += yStrokePad;
    }
    return box;
  }
  updateClipFromPath() {
    const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
    this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
  }
  isEmptyClip() {
    return this.minX === Infinity;
  }
  startNewPathAndClipBox(box) {
    this.clipBox = box;
    this.minX = Infinity;
    this.minY = Infinity;
    this.maxX = 0;
    this.maxY = 0;
  }
  getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
    return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
  }
}
function putBinaryImageData(ctx, imgData, transferMaps = null) {
  if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
    ctx.putImageData(imgData, 0, 0);
    return;
  }
  const height = imgData.height,
    width = imgData.width;
  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  let srcPos = 0,
    destPos;
  const src = imgData.data;
  const dest = chunkImgData.data;
  let i, j, thisChunkHeight, elemsInThisChunk;
  let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
  if (transferMaps) {
    switch (transferMaps.length) {
      case 1:
        transferMapRed = transferMaps[0];
        transferMapGreen = transferMaps[0];
        transferMapBlue = transferMaps[0];
        transferMapGray = transferMaps[0];
        break;
      case 4:
        transferMapRed = transferMaps[0];
        transferMapGreen = transferMaps[1];
        transferMapBlue = transferMaps[2];
        transferMapGray = transferMaps[3];
        break;
    }
  }
  if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
    const srcLength = src.byteLength;
    const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
    const dest32DataLength = dest32.length;
    const fullSrcDiff = width + 7 >> 3;
    let white = 0xffffffff;
    let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
    if (transferMapGray) {
      if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
        [white, black] = [black, white];
      }
    }
    for (i = 0; i < totalChunks; i++) {
      thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
      destPos = 0;
      for (j = 0; j < thisChunkHeight; j++) {
        const srcDiff = srcLength - srcPos;
        let k = 0;
        const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
        const kEndUnrolled = kEnd & ~7;
        let mask = 0;
        let srcByte = 0;
        for (; k < kEndUnrolled; k += 8) {
          srcByte = src[srcPos++];
          dest32[destPos++] = srcByte & 128 ? white : black;
          dest32[destPos++] = srcByte & 64 ? white : black;
          dest32[destPos++] = srcByte & 32 ? white : black;
          dest32[destPos++] = srcByte & 16 ? white : black;
          dest32[destPos++] = srcByte & 8 ? white : black;
          dest32[destPos++] = srcByte & 4 ? white : black;
          dest32[destPos++] = srcByte & 2 ? white : black;
          dest32[destPos++] = srcByte & 1 ? white : black;
        }
        for (; k < kEnd; k++) {
          if (mask === 0) {
            srcByte = src[srcPos++];
            mask = 128;
          }
          dest32[destPos++] = srcByte & mask ? white : black;
          mask >>= 1;
        }
      }
      while (destPos < dest32DataLength) {
        dest32[destPos++] = 0;
      }
      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
    }
  } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
    j = 0;
    elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
    for (i = 0; i < fullChunks; i++) {
      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
      srcPos += elemsInThisChunk;
      if (hasTransferMaps) {
        for (let k = 0; k < elemsInThisChunk; k += 4) {
          if (transferMapRed) {
            dest[k + 0] = transferMapRed[dest[k + 0]];
          }
          if (transferMapGreen) {
            dest[k + 1] = transferMapGreen[dest[k + 1]];
          }
          if (transferMapBlue) {
            dest[k + 2] = transferMapBlue[dest[k + 2]];
          }
        }
      }
      ctx.putImageData(chunkImgData, 0, j);
      j += FULL_CHUNK_HEIGHT;
    }
    if (i < totalChunks) {
      elemsInThisChunk = width * partialChunkHeight * 4;
      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
      if (hasTransferMaps) {
        for (let k = 0; k < elemsInThisChunk; k += 4) {
          if (transferMapRed) {
            dest[k + 0] = transferMapRed[dest[k + 0]];
          }
          if (transferMapGreen) {
            dest[k + 1] = transferMapGreen[dest[k + 1]];
          }
          if (transferMapBlue) {
            dest[k + 2] = transferMapBlue[dest[k + 2]];
          }
        }
      }
      ctx.putImageData(chunkImgData, 0, j);
    }
  } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
    thisChunkHeight = FULL_CHUNK_HEIGHT;
    elemsInThisChunk = width * thisChunkHeight;
    for (i = 0; i < totalChunks; i++) {
      if (i >= fullChunks) {
        thisChunkHeight = partialChunkHeight;
        elemsInThisChunk = width * thisChunkHeight;
      }
      destPos = 0;
      for (j = elemsInThisChunk; j--;) {
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = src[srcPos++];
        dest[destPos++] = 255;
      }
      if (hasTransferMaps) {
        for (let k = 0; k < destPos; k += 4) {
          if (transferMapRed) {
            dest[k + 0] = transferMapRed[dest[k + 0]];
          }
          if (transferMapGreen) {
            dest[k + 1] = transferMapGreen[dest[k + 1]];
          }
          if (transferMapBlue) {
            dest[k + 2] = transferMapBlue[dest[k + 2]];
          }
        }
      }
      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
    }
  } else {
    throw new Error(`bad image kind: ${imgData.kind}`);
  }
}
function putBinaryImageMask(ctx, imgData) {
  if (imgData.bitmap) {
    ctx.drawImage(imgData.bitmap, 0, 0);
    return;
  }
  const height = imgData.height,
    width = imgData.width;
  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  let srcPos = 0;
  const src = imgData.data;
  const dest = chunkImgData.data;
  for (let i = 0; i < totalChunks; i++) {
    const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
    ({
      srcPos
    } = (0, _image_utils.applyMaskImageData)({
      src,
      srcPos,
      dest,
      width,
      height: thisChunkHeight
    }));
    ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  }
}
function copyCtxState(sourceCtx, destCtx) {
  const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
  for (const property of properties) {
    if (sourceCtx[property] !== undefined) {
      destCtx[property] = sourceCtx[property];
    }
  }
  if (sourceCtx.setLineDash !== undefined) {
    destCtx.setLineDash(sourceCtx.getLineDash());
    destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  }
}
function resetCtxToDefault(ctx, foregroundColor) {
  ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
  ctx.fillRule = "nonzero";
  ctx.globalAlpha = 1;
  ctx.lineWidth = 1;
  ctx.lineCap = "butt";
  ctx.lineJoin = "miter";
  ctx.miterLimit = 10;
  ctx.globalCompositeOperation = "source-over";
  ctx.font = "10px sans-serif";
  if (ctx.setLineDash !== undefined) {
    ctx.setLineDash([]);
    ctx.lineDashOffset = 0;
  }
}
function composeSMaskBackdrop(bytes, r0, g0, b0) {
  const length = bytes.length;
  for (let i = 3; i < length; i += 4) {
    const alpha = bytes[i];
    if (alpha === 0) {
      bytes[i - 3] = r0;
      bytes[i - 2] = g0;
      bytes[i - 1] = b0;
    } else if (alpha < 255) {
      const alpha_ = 255 - alpha;
      bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
      bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
      bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
    }
  }
}
function composeSMaskAlpha(maskData, layerData, transferMap) {
  const length = maskData.length;
  const scale = 1 / 255;
  for (let i = 3; i < length; i += 4) {
    const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
    layerData[i] = layerData[i] * alpha * scale | 0;
  }
}
function composeSMaskLuminosity(maskData, layerData, transferMap) {
  const length = maskData.length;
  for (let i = 3; i < length; i += 4) {
    const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
    layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  }
}
function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
  const hasBackdrop = !!backdrop;
  const r0 = hasBackdrop ? backdrop[0] : 0;
  const g0 = hasBackdrop ? backdrop[1] : 0;
  const b0 = hasBackdrop ? backdrop[2] : 0;
  let composeFn;
  if (subtype === "Luminosity") {
    composeFn = composeSMaskLuminosity;
  } else {
    composeFn = composeSMaskAlpha;
  }
  const PIXELS_TO_PROCESS = 1048576;
  const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  for (let row = 0; row < height; row += chunkSize) {
    const chunkHeight = Math.min(chunkSize, height - row);
    const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
    const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
    if (hasBackdrop) {
      composeSMaskBackdrop(maskData.data, r0, g0, b0);
    }
    composeFn(maskData.data, layerData.data, transferMap);
    layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
  }
}
function composeSMask(ctx, smask, layerCtx, layerBox) {
  const layerOffsetX = layerBox[0];
  const layerOffsetY = layerBox[1];
  const layerWidth = layerBox[2] - layerOffsetX;
  const layerHeight = layerBox[3] - layerOffsetY;
  if (layerWidth === 0 || layerHeight === 0) {
    return;
  }
  genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
  ctx.save();
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = "source-over";
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.drawImage(layerCtx.canvas, 0, 0);
  ctx.restore();
}
function getImageSmoothingEnabled(transform, interpolate) {
  const scale = _util.Util.singularValueDecompose2dScale(transform);
  scale[0] = Math.fround(scale[0]);
  scale[1] = Math.fround(scale[1]);
  const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
  if (interpolate !== undefined) {
    return interpolate;
  } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
    return true;
  }
  return false;
}
const LINE_CAP_STYLES = ["butt", "round", "square"];
const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
const NORMAL_CLIP = {};
const EO_CLIP = {};
class CanvasGraphics {
  constructor(canvasCtx, commonObjs, objs, canvasFactory, {
    optionalContentConfig,
    markedContentStack = null
  }, annotationCanvasMap, pageColors) {
    this.ctx = canvasCtx;
    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
    this.stateStack = [];
    this.pendingClip = null;
    this.pendingEOFill = false;
    this.res = null;
    this.xobjs = null;
    this.commonObjs = commonObjs;
    this.objs = objs;
    this.canvasFactory = canvasFactory;
    this.groupStack = [];
    this.processingType3 = null;
    this.baseTransform = null;
    this.baseTransformStack = [];
    this.groupLevel = 0;
    this.smaskStack = [];
    this.smaskCounter = 0;
    this.tempSMask = null;
    this.suspendedCtx = null;
    this.contentVisible = true;
    this.markedContentStack = markedContentStack || [];
    this.optionalContentConfig = optionalContentConfig;
    this.cachedCanvases = new CachedCanvases(this.canvasFactory);
    this.cachedPatterns = new Map();
    this.annotationCanvasMap = annotationCanvasMap;
    this.viewportScale = 1;
    this.outputScaleX = 1;
    this.outputScaleY = 1;
    this.backgroundColor = pageColors?.background || null;
    this.foregroundColor = pageColors?.foreground || null;
    this._cachedScaleForStroking = null;
    this._cachedGetSinglePixelWidth = null;
    this._cachedBitmapsMap = new Map();
  }
  getObject(data, fallback = null) {
    if (typeof data === "string") {
      return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
    }
    return fallback;
  }
  beginDrawing({
    transform,
    viewport,
    transparency = false,
    background = null
  }) {
    const width = this.ctx.canvas.width;
    const height = this.ctx.canvas.height;
    const defaultBackgroundColor = background || "#ffffff";
    this.ctx.save();
    if (this.foregroundColor && this.backgroundColor) {
      this.ctx.fillStyle = this.foregroundColor;
      const fg = this.foregroundColor = this.ctx.fillStyle;
      this.ctx.fillStyle = this.backgroundColor;
      const bg = this.backgroundColor = this.ctx.fillStyle;
      let isValidDefaultBg = true;
      let defaultBg = defaultBackgroundColor;
      this.ctx.fillStyle = defaultBackgroundColor;
      defaultBg = this.ctx.fillStyle;
      isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
      if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
        this.foregroundColor = this.backgroundColor = null;
      } else {
        const [rB, gB, bB] = (0, _display_utils.getRGB)(defaultBg);
        const newComp = x => {
          x /= 255;
          return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
        };
        const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
        this.selectColor = (r, g, b) => {
          const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
          return Math.round(lumC) === lumB ? bg : fg;
        };
      }
    }
    this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
    this.ctx.fillRect(0, 0, width, height);
    this.ctx.restore();
    if (transparency) {
      const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height);
      this.compositeCtx = this.ctx;
      this.transparentCanvas = transparentCanvas.canvas;
      this.ctx = transparentCanvas.context;
      this.ctx.save();
      this.ctx.transform(...(0, _display_utils.getCurrentTransform)(this.compositeCtx));
    }
    this.ctx.save();
    resetCtxToDefault(this.ctx, this.foregroundColor);
    if (transform) {
      this.ctx.transform(...transform);
      this.outputScaleX = transform[0];
      this.outputScaleY = transform[0];
    }
    this.ctx.transform(...viewport.transform);
    this.viewportScale = viewport.scale;
    this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
  }
  executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
    const argsArray = operatorList.argsArray;
    const fnArray = operatorList.fnArray;
    let i = executionStartIdx || 0;
    const argsArrayLen = argsArray.length;
    if (argsArrayLen === i) {
      return i;
    }
    const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
    const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
    let steps = 0;
    const commonObjs = this.commonObjs;
    const objs = this.objs;
    let fnId;
    while (true) {
      if (stepper !== undefined && i === stepper.nextBreakPoint) {
        stepper.breakIt(i, continueCallback);
        return i;
      }
      fnId = fnArray[i];
      if (fnId !== _util.OPS.dependency) {
        this[fnId].apply(this, argsArray[i]);
      } else {
        for (const depObjId of argsArray[i]) {
          const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
          if (!objsPool.has(depObjId)) {
            objsPool.get(depObjId, continueCallback);
            return i;
          }
        }
      }
      i++;
      if (i === argsArrayLen) {
        return i;
      }
      if (chunkOperations && ++steps > EXECUTION_STEPS) {
        if (Date.now() > endTime) {
          continueCallback();
          return i;
        }
        steps = 0;
      }
    }
  }
  #restoreInitialState() {
    while (this.stateStack.length || this.inSMaskMode) {
      this.restore();
    }
    this.ctx.restore();
    if (this.transparentCanvas) {
      this.ctx = this.compositeCtx;
      this.ctx.save();
      this.ctx.setTransform(1, 0, 0, 1, 0, 0);
      this.ctx.drawImage(this.transparentCanvas, 0, 0);
      this.ctx.restore();
      this.transparentCanvas = null;
    }
  }
  endDrawing() {
    this.#restoreInitialState();
    this.cachedCanvases.clear();
    this.cachedPatterns.clear();
    for (const cache of this._cachedBitmapsMap.values()) {
      for (const canvas of cache.values()) {
        if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
          canvas.width = canvas.height = 0;
        }
      }
      cache.clear();
    }
    this._cachedBitmapsMap.clear();
  }
  _scaleImage(img, inverseTransform) {
    const width = img.width;
    const height = img.height;
    let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
    let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
    let paintWidth = width,
      paintHeight = height;
    let tmpCanvasId = "prescale1";
    let tmpCanvas, tmpCtx;
    while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
      let newWidth = paintWidth,
        newHeight = paintHeight;
      if (widthScale > 2 && paintWidth > 1) {
        newWidth = Math.ceil(paintWidth / 2);
        widthScale /= paintWidth / newWidth;
      }
      if (heightScale > 2 && paintHeight > 1) {
        newHeight = Math.ceil(paintHeight / 2);
        heightScale /= paintHeight / newHeight;
      }
      tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
      tmpCtx = tmpCanvas.context;
      tmpCtx.clearRect(0, 0, newWidth, newHeight);
      tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
      img = tmpCanvas.canvas;
      paintWidth = newWidth;
      paintHeight = newHeight;
      tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
    }
    return {
      img,
      paintWidth,
      paintHeight
    };
  }
  _createMaskCanvas(img) {
    const ctx = this.ctx;
    const {
      width,
      height
    } = img;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
    let cache, cacheKey, scaled, maskCanvas;
    if ((img.bitmap || img.data) && img.count > 1) {
      const mainKey = img.bitmap || img.data.buffer;
      cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]);
      cache = this._cachedBitmapsMap.get(mainKey);
      if (!cache) {
        cache = new Map();
        this._cachedBitmapsMap.set(mainKey, cache);
      }
      const cachedImage = cache.get(cacheKey);
      if (cachedImage && !isPatternFill) {
        const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
        const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
        return {
          canvas: cachedImage,
          offsetX,
          offsetY
        };
      }
      scaled = cachedImage;
    }
    if (!scaled) {
      maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
      putBinaryImageMask(maskCanvas.context, img);
    }
    let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
    maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
    const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
    const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
    const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
    const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
    const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
    const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight);
    const fillCtx = fillCanvas.context;
    const offsetX = Math.min(cord1[0], cord2[0]);
    const offsetY = Math.min(cord1[1], cord2[1]);
    fillCtx.translate(-offsetX, -offsetY);
    fillCtx.transform(...maskToCanvas);
    if (!scaled) {
      scaled = this._scaleImage(maskCanvas.canvas, (0, _display_utils.getCurrentTransformInverse)(fillCtx));
      scaled = scaled.img;
      if (cache && isPatternFill) {
        cache.set(cacheKey, scaled);
      }
    }
    fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(fillCtx), img.interpolate);
    drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
    fillCtx.globalCompositeOperation = "source-in";
    const inverse = _util.Util.transform((0, _display_utils.getCurrentTransformInverse)(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]);
    fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
    fillCtx.fillRect(0, 0, width, height);
    if (cache && !isPatternFill) {
      this.cachedCanvases.delete("fillCanvas");
      cache.set(cacheKey, fillCanvas.canvas);
    }
    return {
      canvas: fillCanvas.canvas,
      offsetX: Math.round(offsetX),
      offsetY: Math.round(offsetY)
    };
  }
  setLineWidth(width) {
    if (width !== this.current.lineWidth) {
      this._cachedScaleForStroking = null;
    }
    this.current.lineWidth = width;
    this.ctx.lineWidth = width;
  }
  setLineCap(style) {
    this.ctx.lineCap = LINE_CAP_STYLES[style];
  }
  setLineJoin(style) {
    this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  }
  setMiterLimit(limit) {
    this.ctx.miterLimit = limit;
  }
  setDash(dashArray, dashPhase) {
    const ctx = this.ctx;
    if (ctx.setLineDash !== undefined) {
      ctx.setLineDash(dashArray);
      ctx.lineDashOffset = dashPhase;
    }
  }
  setRenderingIntent(intent) {}
  setFlatness(flatness) {}
  setGState(states) {
    for (const [key, value] of states) {
      switch (key) {
        case "LW":
          this.setLineWidth(value);
          break;
        case "LC":
          this.setLineCap(value);
          break;
        case "LJ":
          this.setLineJoin(value);
          break;
        case "ML":
          this.setMiterLimit(value);
          break;
        case "D":
          this.setDash(value[0], value[1]);
          break;
        case "RI":
          this.setRenderingIntent(value);
          break;
        case "FL":
          this.setFlatness(value);
          break;
        case "Font":
          this.setFont(value[0], value[1]);
          break;
        case "CA":
          this.current.strokeAlpha = value;
          break;
        case "ca":
          this.current.fillAlpha = value;
          this.ctx.globalAlpha = value;
          break;
        case "BM":
          this.ctx.globalCompositeOperation = value;
          break;
        case "SMask":
          this.current.activeSMask = value ? this.tempSMask : null;
          this.tempSMask = null;
          this.checkSMaskState();
          break;
        case "TR":
          this.current.transferMaps = value;
      }
    }
  }
  get inSMaskMode() {
    return !!this.suspendedCtx;
  }
  checkSMaskState() {
    const inSMaskMode = this.inSMaskMode;
    if (this.current.activeSMask && !inSMaskMode) {
      this.beginSMaskMode();
    } else if (!this.current.activeSMask && inSMaskMode) {
      this.endSMaskMode();
    }
  }
  beginSMaskMode() {
    if (this.inSMaskMode) {
      throw new Error("beginSMaskMode called while already in smask mode");
    }
    const drawnWidth = this.ctx.canvas.width;
    const drawnHeight = this.ctx.canvas.height;
    const cacheId = "smaskGroupAt" + this.groupLevel;
    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
    this.suspendedCtx = this.ctx;
    this.ctx = scratchCanvas.context;
    const ctx = this.ctx;
    ctx.setTransform(...(0, _display_utils.getCurrentTransform)(this.suspendedCtx));
    copyCtxState(this.suspendedCtx, ctx);
    mirrorContextOperations(ctx, this.suspendedCtx);
    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
  }
  endSMaskMode() {
    if (!this.inSMaskMode) {
      throw new Error("endSMaskMode called while not in smask mode");
    }
    this.ctx._removeMirroring();
    copyCtxState(this.ctx, this.suspendedCtx);
    this.ctx = this.suspendedCtx;
    this.suspendedCtx = null;
  }
  compose(dirtyBox) {
    if (!this.current.activeSMask) {
      return;
    }
    if (!dirtyBox) {
      dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
    } else {
      dirtyBox[0] = Math.floor(dirtyBox[0]);
      dirtyBox[1] = Math.floor(dirtyBox[1]);
      dirtyBox[2] = Math.ceil(dirtyBox[2]);
      dirtyBox[3] = Math.ceil(dirtyBox[3]);
    }
    const smask = this.current.activeSMask;
    const suspendedCtx = this.suspendedCtx;
    composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
    this.ctx.save();
    this.ctx.setTransform(1, 0, 0, 1, 0, 0);
    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
    this.ctx.restore();
  }
  save() {
    if (this.inSMaskMode) {
      copyCtxState(this.ctx, this.suspendedCtx);
      this.suspendedCtx.save();
    } else {
      this.ctx.save();
    }
    const old = this.current;
    this.stateStack.push(old);
    this.current = old.clone();
  }
  restore() {
    if (this.stateStack.length === 0 && this.inSMaskMode) {
      this.endSMaskMode();
    }
    if (this.stateStack.length !== 0) {
      this.current = this.stateStack.pop();
      if (this.inSMaskMode) {
        this.suspendedCtx.restore();
        copyCtxState(this.suspendedCtx, this.ctx);
      } else {
        this.ctx.restore();
      }
      this.checkSMaskState();
      this.pendingClip = null;
      this._cachedScaleForStroking = null;
      this._cachedGetSinglePixelWidth = null;
    }
  }
  transform(a, b, c, d, e, f) {
    this.ctx.transform(a, b, c, d, e, f);
    this._cachedScaleForStroking = null;
    this._cachedGetSinglePixelWidth = null;
  }
  constructPath(ops, args, minMax) {
    const ctx = this.ctx;
    const current = this.current;
    let x = current.x,
      y = current.y;
    let startX, startY;
    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
    const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
    const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
    for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
      switch (ops[i] | 0) {
        case _util.OPS.rectangle:
          x = args[j++];
          y = args[j++];
          const width = args[j++];
          const height = args[j++];
          const xw = x + width;
          const yh = y + height;
          ctx.moveTo(x, y);
          if (width === 0 || height === 0) {
            ctx.lineTo(xw, yh);
          } else {
            ctx.lineTo(xw, y);
            ctx.lineTo(xw, yh);
            ctx.lineTo(x, yh);
          }
          if (!isScalingMatrix) {
            current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
          }
          ctx.closePath();
          break;
        case _util.OPS.moveTo:
          x = args[j++];
          y = args[j++];
          ctx.moveTo(x, y);
          if (!isScalingMatrix) {
            current.updatePathMinMax(currentTransform, x, y);
          }
          break;
        case _util.OPS.lineTo:
          x = args[j++];
          y = args[j++];
          ctx.lineTo(x, y);
          if (!isScalingMatrix) {
            current.updatePathMinMax(currentTransform, x, y);
          }
          break;
        case _util.OPS.curveTo:
          startX = x;
          startY = y;
          x = args[j + 4];
          y = args[j + 5];
          ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
          j += 6;
          break;
        case _util.OPS.curveTo2:
          startX = x;
          startY = y;
          ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
          current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
          x = args[j + 2];
          y = args[j + 3];
          j += 4;
          break;
        case _util.OPS.curveTo3:
          startX = x;
          startY = y;
          x = args[j + 2];
          y = args[j + 3];
          ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
          j += 4;
          break;
        case _util.OPS.closePath:
          ctx.closePath();
          break;
      }
    }
    if (isScalingMatrix) {
      current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
    }
    current.setCurrentPoint(x, y);
  }
  closePath() {
    this.ctx.closePath();
  }
  stroke(consumePath = true) {
    const ctx = this.ctx;
    const strokeColor = this.current.strokeColor;
    ctx.globalAlpha = this.current.strokeAlpha;
    if (this.contentVisible) {
      if (typeof strokeColor === "object" && strokeColor?.getPattern) {
        ctx.save();
        ctx.strokeStyle = strokeColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.STROKE);
        this.rescaleAndStroke(false);
        ctx.restore();
      } else {
        this.rescaleAndStroke(true);
      }
    }
    if (consumePath) {
      this.consumePath(this.current.getClippedPathBoundingBox());
    }
    ctx.globalAlpha = this.current.fillAlpha;
  }
  closeStroke() {
    this.closePath();
    this.stroke();
  }
  fill(consumePath = true) {
    const ctx = this.ctx;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    let needRestore = false;
    if (isPatternFill) {
      ctx.save();
      ctx.fillStyle = fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
      needRestore = true;
    }
    const intersect = this.current.getClippedPathBoundingBox();
    if (this.contentVisible && intersect !== null) {
      if (this.pendingEOFill) {
        ctx.fill("evenodd");
        this.pendingEOFill = false;
      } else {
        ctx.fill();
      }
    }
    if (needRestore) {
      ctx.restore();
    }
    if (consumePath) {
      this.consumePath(intersect);
    }
  }
  eoFill() {
    this.pendingEOFill = true;
    this.fill();
  }
  fillStroke() {
    this.fill(false);
    this.stroke(false);
    this.consumePath();
  }
  eoFillStroke() {
    this.pendingEOFill = true;
    this.fillStroke();
  }
  closeFillStroke() {
    this.closePath();
    this.fillStroke();
  }
  closeEOFillStroke() {
    this.pendingEOFill = true;
    this.closePath();
    this.fillStroke();
  }
  endPath() {
    this.consumePath();
  }
  clip() {
    this.pendingClip = NORMAL_CLIP;
  }
  eoClip() {
    this.pendingClip = EO_CLIP;
  }
  beginText() {
    this.current.textMatrix = _util.IDENTITY_MATRIX;
    this.current.textMatrixScale = 1;
    this.current.x = this.current.lineX = 0;
    this.current.y = this.current.lineY = 0;
  }
  endText() {
    const paths = this.pendingTextPaths;
    const ctx = this.ctx;
    if (paths === undefined) {
      ctx.beginPath();
      return;
    }
    ctx.save();
    ctx.beginPath();
    for (const path of paths) {
      ctx.setTransform(...path.transform);
      ctx.translate(path.x, path.y);
      path.addToPath(ctx, path.fontSize);
    }
    ctx.restore();
    ctx.clip();
    ctx.beginPath();
    delete this.pendingTextPaths;
  }
  setCharSpacing(spacing) {
    this.current.charSpacing = spacing;
  }
  setWordSpacing(spacing) {
    this.current.wordSpacing = spacing;
  }
  setHScale(scale) {
    this.current.textHScale = scale / 100;
  }
  setLeading(leading) {
    this.current.leading = -leading;
  }
  setFont(fontRefName, size) {
    const fontObj = this.commonObjs.get(fontRefName);
    const current = this.current;
    if (!fontObj) {
      throw new Error(`Can't find font for ${fontRefName}`);
    }
    current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
    if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
      (0, _util.warn)("Invalid font matrix for font " + fontRefName);
    }
    if (size < 0) {
      size = -size;
      current.fontDirection = -1;
    } else {
      current.fontDirection = 1;
    }
    this.current.font = fontObj;
    this.current.fontSize = size;
    if (fontObj.isType3Font) {
      return;
    }
    const name = fontObj.loadedName || "sans-serif";
    let bold = "normal";
    if (fontObj.black) {
      bold = "900";
    } else if (fontObj.bold) {
      bold = "bold";
    }
    const italic = fontObj.italic ? "italic" : "normal";
    const typeface = `"${name}", ${fontObj.fallbackName}`;
    let browserFontSize = size;
    if (size < MIN_FONT_SIZE) {
      browserFontSize = MIN_FONT_SIZE;
    } else if (size > MAX_FONT_SIZE) {
      browserFontSize = MAX_FONT_SIZE;
    }
    this.current.fontSizeScale = size / browserFontSize;
    this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
  }
  setTextRenderingMode(mode) {
    this.current.textRenderingMode = mode;
  }
  setTextRise(rise) {
    this.current.textRise = rise;
  }
  moveText(x, y) {
    this.current.x = this.current.lineX += x;
    this.current.y = this.current.lineY += y;
  }
  setLeadingMoveText(x, y) {
    this.setLeading(-y);
    this.moveText(x, y);
  }
  setTextMatrix(a, b, c, d, e, f) {
    this.current.textMatrix = [a, b, c, d, e, f];
    this.current.textMatrixScale = Math.hypot(a, b);
    this.current.x = this.current.lineX = 0;
    this.current.y = this.current.lineY = 0;
  }
  nextLine() {
    this.moveText(0, this.current.leading);
  }
  paintChar(character, x, y, patternTransform) {
    const ctx = this.ctx;
    const current = this.current;
    const font = current.font;
    const textRenderingMode = current.textRenderingMode;
    const fontSize = current.fontSize / current.fontSizeScale;
    const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
    const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
    const patternFill = current.patternFill && !font.missingFile;
    let addToPath;
    if (font.disableFontFace || isAddToPathSet || patternFill) {
      addToPath = font.getPathGenerator(this.commonObjs, character);
    }
    if (font.disableFontFace || patternFill) {
      ctx.save();
      ctx.translate(x, y);
      ctx.beginPath();
      addToPath(ctx, fontSize);
      if (patternTransform) {
        ctx.setTransform(...patternTransform);
      }
      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        ctx.fill();
      }
      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        ctx.stroke();
      }
      ctx.restore();
    } else {
      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        ctx.fillText(character, x, y);
      }
      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        ctx.strokeText(character, x, y);
      }
    }
    if (isAddToPathSet) {
      const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
      paths.push({
        transform: (0, _display_utils.getCurrentTransform)(ctx),
        x,
        y,
        fontSize,
        addToPath
      });
    }
  }
  get isFontSubpixelAAEnabled() {
    const {
      context: ctx
    } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
    ctx.scale(1.5, 1);
    ctx.fillText("I", 0, 10);
    const data = ctx.getImageData(0, 0, 10, 10).data;
    let enabled = false;
    for (let i = 3; i < data.length; i += 4) {
      if (data[i] > 0 && data[i] < 255) {
        enabled = true;
        break;
      }
    }
    return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
  }
  showText(glyphs) {
    const current = this.current;
    const font = current.font;
    if (font.isType3Font) {
      return this.showType3Text(glyphs);
    }
    const fontSize = current.fontSize;
    if (fontSize === 0) {
      return undefined;
    }
    const ctx = this.ctx;
    const fontSizeScale = current.fontSizeScale;
    const charSpacing = current.charSpacing;
    const wordSpacing = current.wordSpacing;
    const fontDirection = current.fontDirection;
    const textHScale = current.textHScale * fontDirection;
    const glyphsLength = glyphs.length;
    const vertical = font.vertical;
    const spacingDir = vertical ? 1 : -1;
    const defaultVMetrics = font.defaultVMetrics;
    const widthAdvanceScale = fontSize * current.fontMatrix[0];
    const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
    ctx.save();
    ctx.transform(...current.textMatrix);
    ctx.translate(current.x, current.y + current.textRise);
    if (fontDirection > 0) {
      ctx.scale(textHScale, -1);
    } else {
      ctx.scale(textHScale, 1);
    }
    let patternTransform;
    if (current.patternFill) {
      ctx.save();
      const pattern = current.fillColor.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL);
      patternTransform = (0, _display_utils.getCurrentTransform)(ctx);
      ctx.restore();
      ctx.fillStyle = pattern;
    }
    let lineWidth = current.lineWidth;
    const scale = current.textMatrixScale;
    if (scale === 0 || lineWidth === 0) {
      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        lineWidth = this.getSinglePixelWidth();
      }
    } else {
      lineWidth /= scale;
    }
    if (fontSizeScale !== 1.0) {
      ctx.scale(fontSizeScale, fontSizeScale);
      lineWidth /= fontSizeScale;
    }
    ctx.lineWidth = lineWidth;
    if (font.isInvalidPDFjsFont) {
      const chars = [];
      let width = 0;
      for (const glyph of glyphs) {
        chars.push(glyph.unicode);
        width += glyph.width;
      }
      ctx.fillText(chars.join(""), 0, 0);
      current.x += width * widthAdvanceScale * textHScale;
      ctx.restore();
      this.compose();
      return undefined;
    }
    let x = 0,
      i;
    for (i = 0; i < glyphsLength; ++i) {
      const glyph = glyphs[i];
      if (typeof glyph === "number") {
        x += spacingDir * glyph * fontSize / 1000;
        continue;
      }
      let restoreNeeded = false;
      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
      const character = glyph.fontChar;
      const accent = glyph.accent;
      let scaledX, scaledY;
      let width = glyph.width;
      if (vertical) {
        const vmetric = glyph.vmetric || defaultVMetrics;
        const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
        const vy = vmetric[2] * widthAdvanceScale;
        width = vmetric ? -vmetric[0] : width;
        scaledX = vx / fontSizeScale;
        scaledY = (x + vy) / fontSizeScale;
      } else {
        scaledX = x / fontSizeScale;
        scaledY = 0;
      }
      if (font.remeasure && width > 0) {
        const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
        if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
          const characterScaleX = width / measuredWidth;
          restoreNeeded = true;
          ctx.save();
          ctx.scale(characterScaleX, 1);
          scaledX /= characterScaleX;
        } else if (width !== measuredWidth) {
          scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
        }
      }
      if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
        if (simpleFillText && !accent) {
          ctx.fillText(character, scaledX, scaledY);
        } else {
          this.paintChar(character, scaledX, scaledY, patternTransform);
          if (accent) {
            const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
            const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
            this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
          }
        }
      }
      let charWidth;
      if (vertical) {
        charWidth = width * widthAdvanceScale - spacing * fontDirection;
      } else {
        charWidth = width * widthAdvanceScale + spacing * fontDirection;
      }
      x += charWidth;
      if (restoreNeeded) {
        ctx.restore();
      }
    }
    if (vertical) {
      current.y -= x;
    } else {
      current.x += x * textHScale;
    }
    ctx.restore();
    this.compose();
    return undefined;
  }
  showType3Text(glyphs) {
    const ctx = this.ctx;
    const current = this.current;
    const font = current.font;
    const fontSize = current.fontSize;
    const fontDirection = current.fontDirection;
    const spacingDir = font.vertical ? 1 : -1;
    const charSpacing = current.charSpacing;
    const wordSpacing = current.wordSpacing;
    const textHScale = current.textHScale * fontDirection;
    const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
    const glyphsLength = glyphs.length;
    const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
    let i, glyph, width, spacingLength;
    if (isTextInvisible || fontSize === 0) {
      return;
    }
    this._cachedScaleForStroking = null;
    this._cachedGetSinglePixelWidth = null;
    ctx.save();
    ctx.transform(...current.textMatrix);
    ctx.translate(current.x, current.y);
    ctx.scale(textHScale, fontDirection);
    for (i = 0; i < glyphsLength; ++i) {
      glyph = glyphs[i];
      if (typeof glyph === "number") {
        spacingLength = spacingDir * glyph * fontSize / 1000;
        this.ctx.translate(spacingLength, 0);
        current.x += spacingLength * textHScale;
        continue;
      }
      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
      const operatorList = font.charProcOperatorList[glyph.operatorListId];
      if (!operatorList) {
        (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
        continue;
      }
      if (this.contentVisible) {
        this.processingType3 = glyph;
        this.save();
        ctx.scale(fontSize, fontSize);
        ctx.transform(...fontMatrix);
        this.executeOperatorList(operatorList);
        this.restore();
      }
      const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
      width = transformed[0] * fontSize + spacing;
      ctx.translate(width, 0);
      current.x += width * textHScale;
    }
    ctx.restore();
    this.processingType3 = null;
  }
  setCharWidth(xWidth, yWidth) {}
  setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
    this.ctx.rect(llx, lly, urx - llx, ury - lly);
    this.ctx.clip();
    this.endPath();
  }
  getColorN_Pattern(IR) {
    let pattern;
    if (IR[0] === "TilingPattern") {
      const color = IR[1];
      const baseTransform = this.baseTransform || (0, _display_utils.getCurrentTransform)(this.ctx);
      const canvasGraphicsFactory = {
        createCanvasGraphics: ctx => {
          return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, {
            optionalContentConfig: this.optionalContentConfig,
            markedContentStack: this.markedContentStack
          });
        }
      };
      pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
    } else {
      pattern = this._getPattern(IR[1], IR[2]);
    }
    return pattern;
  }
  setStrokeColorN() {
    this.current.strokeColor = this.getColorN_Pattern(arguments);
  }
  setFillColorN() {
    this.current.fillColor = this.getColorN_Pattern(arguments);
    this.current.patternFill = true;
  }
  setStrokeRGBColor(r, g, b) {
    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
    this.ctx.strokeStyle = color;
    this.current.strokeColor = color;
  }
  setFillRGBColor(r, g, b) {
    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
    this.ctx.fillStyle = color;
    this.current.fillColor = color;
    this.current.patternFill = false;
  }
  _getPattern(objId, matrix = null) {
    let pattern;
    if (this.cachedPatterns.has(objId)) {
      pattern = this.cachedPatterns.get(objId);
    } else {
      pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
      this.cachedPatterns.set(objId, pattern);
    }
    if (matrix) {
      pattern.matrix = matrix;
    }
    return pattern;
  }
  shadingFill(objId) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    this.save();
    const pattern = this._getPattern(objId);
    ctx.fillStyle = pattern.getPattern(ctx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.SHADING);
    const inv = (0, _display_utils.getCurrentTransformInverse)(ctx);
    if (inv) {
      const canvas = ctx.canvas;
      const width = canvas.width;
      const height = canvas.height;
      const bl = _util.Util.applyTransform([0, 0], inv);
      const br = _util.Util.applyTransform([0, height], inv);
      const ul = _util.Util.applyTransform([width, 0], inv);
      const ur = _util.Util.applyTransform([width, height], inv);
      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
      this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
    } else {
      this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
    }
    this.compose(this.current.getClippedPathBoundingBox());
    this.restore();
  }
  beginInlineImage() {
    (0, _util.unreachable)("Should not call beginInlineImage");
  }
  beginImageData() {
    (0, _util.unreachable)("Should not call beginImageData");
  }
  paintFormXObjectBegin(matrix, bbox) {
    if (!this.contentVisible) {
      return;
    }
    this.save();
    this.baseTransformStack.push(this.baseTransform);
    if (Array.isArray(matrix) && matrix.length === 6) {
      this.transform(...matrix);
    }
    this.baseTransform = (0, _display_utils.getCurrentTransform)(this.ctx);
    if (bbox) {
      const width = bbox[2] - bbox[0];
      const height = bbox[3] - bbox[1];
      this.ctx.rect(bbox[0], bbox[1], width, height);
      this.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(this.ctx), bbox);
      this.clip();
      this.endPath();
    }
  }
  paintFormXObjectEnd() {
    if (!this.contentVisible) {
      return;
    }
    this.restore();
    this.baseTransform = this.baseTransformStack.pop();
  }
  beginGroup(group) {
    if (!this.contentVisible) {
      return;
    }
    this.save();
    if (this.inSMaskMode) {
      this.endSMaskMode();
      this.current.activeSMask = null;
    }
    const currentCtx = this.ctx;
    if (!group.isolated) {
      (0, _util.info)("TODO: Support non-isolated groups.");
    }
    if (group.knockout) {
      (0, _util.warn)("Knockout groups not supported.");
    }
    const currentTransform = (0, _display_utils.getCurrentTransform)(currentCtx);
    if (group.matrix) {
      currentCtx.transform(...group.matrix);
    }
    if (!group.bbox) {
      throw new Error("Bounding box is required.");
    }
    let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, (0, _display_utils.getCurrentTransform)(currentCtx));
    const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
    bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
    const offsetX = Math.floor(bounds[0]);
    const offsetY = Math.floor(bounds[1]);
    let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
    let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
    let scaleX = 1,
      scaleY = 1;
    if (drawnWidth > MAX_GROUP_SIZE) {
      scaleX = drawnWidth / MAX_GROUP_SIZE;
      drawnWidth = MAX_GROUP_SIZE;
    }
    if (drawnHeight > MAX_GROUP_SIZE) {
      scaleY = drawnHeight / MAX_GROUP_SIZE;
      drawnHeight = MAX_GROUP_SIZE;
    }
    this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
    let cacheId = "groupAt" + this.groupLevel;
    if (group.smask) {
      cacheId += "_smask_" + this.smaskCounter++ % 2;
    }
    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight);
    const groupCtx = scratchCanvas.context;
    groupCtx.scale(1 / scaleX, 1 / scaleY);
    groupCtx.translate(-offsetX, -offsetY);
    groupCtx.transform(...currentTransform);
    if (group.smask) {
      this.smaskStack.push({
        canvas: scratchCanvas.canvas,
        context: groupCtx,
        offsetX,
        offsetY,
        scaleX,
        scaleY,
        subtype: group.smask.subtype,
        backdrop: group.smask.backdrop,
        transferMap: group.smask.transferMap || null,
        startTransformInverse: null
      });
    } else {
      currentCtx.setTransform(1, 0, 0, 1, 0, 0);
      currentCtx.translate(offsetX, offsetY);
      currentCtx.scale(scaleX, scaleY);
      currentCtx.save();
    }
    copyCtxState(currentCtx, groupCtx);
    this.ctx = groupCtx;
    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
    this.groupStack.push(currentCtx);
    this.groupLevel++;
  }
  endGroup(group) {
    if (!this.contentVisible) {
      return;
    }
    this.groupLevel--;
    const groupCtx = this.ctx;
    const ctx = this.groupStack.pop();
    this.ctx = ctx;
    this.ctx.imageSmoothingEnabled = false;
    if (group.smask) {
      this.tempSMask = this.smaskStack.pop();
      this.restore();
    } else {
      this.ctx.restore();
      const currentMtx = (0, _display_utils.getCurrentTransform)(this.ctx);
      this.restore();
      this.ctx.save();
      this.ctx.setTransform(...currentMtx);
      const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
      this.ctx.drawImage(groupCtx.canvas, 0, 0);
      this.ctx.restore();
      this.compose(dirtyBox);
    }
  }
  beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
    this.#restoreInitialState();
    resetCtxToDefault(this.ctx, this.foregroundColor);
    this.ctx.save();
    this.save();
    if (this.baseTransform) {
      this.ctx.setTransform(...this.baseTransform);
    }
    if (Array.isArray(rect) && rect.length === 4) {
      const width = rect[2] - rect[0];
      const height = rect[3] - rect[1];
      if (hasOwnCanvas && this.annotationCanvasMap) {
        transform = transform.slice();
        transform[4] -= rect[0];
        transform[5] -= rect[1];
        rect = rect.slice();
        rect[0] = rect[1] = 0;
        rect[2] = width;
        rect[3] = height;
        const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(this.ctx));
        const {
          viewportScale
        } = this;
        const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
        const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
        this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
        const {
          canvas,
          context
        } = this.annotationCanvas;
        this.annotationCanvasMap.set(id, canvas);
        this.annotationCanvas.savedCtx = this.ctx;
        this.ctx = context;
        this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
        resetCtxToDefault(this.ctx, this.foregroundColor);
      } else {
        resetCtxToDefault(this.ctx, this.foregroundColor);
        this.ctx.rect(rect[0], rect[1], width, height);
        this.ctx.clip();
        this.endPath();
      }
    }
    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
    this.transform(...transform);
    this.transform(...matrix);
  }
  endAnnotation() {
    if (this.annotationCanvas) {
      this.ctx = this.annotationCanvas.savedCtx;
      delete this.annotationCanvas.savedCtx;
      delete this.annotationCanvas;
    }
  }
  paintImageMaskXObject(img) {
    if (!this.contentVisible) {
      return;
    }
    const count = img.count;
    img = this.getObject(img.data, img);
    img.count = count;
    const ctx = this.ctx;
    const glyph = this.processingType3;
    if (glyph) {
      if (glyph.compiled === undefined) {
        glyph.compiled = compileType3Glyph(img);
      }
      if (glyph.compiled) {
        glyph.compiled(ctx);
        return;
      }
    }
    const mask = this._createMaskCanvas(img);
    const maskCanvas = mask.canvas;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
    ctx.restore();
    this.compose();
  }
  paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
    if (!this.contentVisible) {
      return;
    }
    img = this.getObject(img.data, img);
    const ctx = this.ctx;
    ctx.save();
    const currentTransform = (0, _display_utils.getCurrentTransform)(ctx);
    ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
    const mask = this._createMaskCanvas(img);
    ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]);
    for (let i = 0, ii = positions.length; i < ii; i += 2) {
      const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
      const [x, y] = _util.Util.applyTransform([0, 0], trans);
      ctx.drawImage(mask.canvas, x, y);
    }
    ctx.restore();
    this.compose();
  }
  paintImageMaskXObjectGroup(images) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    const fillColor = this.current.fillColor;
    const isPatternFill = this.current.patternFill;
    for (const image of images) {
      const {
        data,
        width,
        height,
        transform
      } = image;
      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
      const maskCtx = maskCanvas.context;
      maskCtx.save();
      const img = this.getObject(data, image);
      putBinaryImageMask(maskCtx, img);
      maskCtx.globalCompositeOperation = "source-in";
      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, (0, _display_utils.getCurrentTransformInverse)(ctx), _pattern_helper.PathType.FILL) : fillColor;
      maskCtx.fillRect(0, 0, width, height);
      maskCtx.restore();
      ctx.save();
      ctx.transform(...transform);
      ctx.scale(1, -1);
      drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
      ctx.restore();
    }
    this.compose();
  }
  paintImageXObject(objId) {
    if (!this.contentVisible) {
      return;
    }
    const imgData = this.getObject(objId);
    if (!imgData) {
      (0, _util.warn)("Dependent image isn't ready yet");
      return;
    }
    this.paintInlineImageXObject(imgData);
  }
  paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
    if (!this.contentVisible) {
      return;
    }
    const imgData = this.getObject(objId);
    if (!imgData) {
      (0, _util.warn)("Dependent image isn't ready yet");
      return;
    }
    const width = imgData.width;
    const height = imgData.height;
    const map = [];
    for (let i = 0, ii = positions.length; i < ii; i += 2) {
      map.push({
        transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
        x: 0,
        y: 0,
        w: width,
        h: height
      });
    }
    this.paintInlineImageXObjectGroup(imgData, map);
  }
  paintInlineImageXObject(imgData) {
    if (!this.contentVisible) {
      return;
    }
    const width = imgData.width;
    const height = imgData.height;
    const ctx = this.ctx;
    this.save();
    ctx.scale(1 / width, -1 / height);
    let imgToPaint;
    if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
      imgToPaint = imgData;
    } else {
      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
      const tmpCtx = tmpCanvas.context;
      putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
      imgToPaint = tmpCanvas.canvas;
    }
    const scaled = this._scaleImage(imgToPaint, (0, _display_utils.getCurrentTransformInverse)(ctx));
    ctx.imageSmoothingEnabled = getImageSmoothingEnabled((0, _display_utils.getCurrentTransform)(ctx), imgData.interpolate);
    drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
    this.compose();
    this.restore();
  }
  paintInlineImageXObjectGroup(imgData, map) {
    if (!this.contentVisible) {
      return;
    }
    const ctx = this.ctx;
    const w = imgData.width;
    const h = imgData.height;
    const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
    const tmpCtx = tmpCanvas.context;
    putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
    for (const entry of map) {
      ctx.save();
      ctx.transform(...entry.transform);
      ctx.scale(1, -1);
      drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
      ctx.restore();
    }
    this.compose();
  }
  paintSolidColorImageMask() {
    if (!this.contentVisible) {
      return;
    }
    this.ctx.fillRect(0, 0, 1, 1);
    this.compose();
  }
  markPoint(tag) {}
  markPointProps(tag, properties) {}
  beginMarkedContent(tag) {
    this.markedContentStack.push({
      visible: true
    });
  }
  beginMarkedContentProps(tag, properties) {
    if (tag === "OC") {
      this.markedContentStack.push({
        visible: this.optionalContentConfig.isVisible(properties)
      });
    } else {
      this.markedContentStack.push({
        visible: true
      });
    }
    this.contentVisible = this.isContentVisible();
  }
  endMarkedContent() {
    this.markedContentStack.pop();
    this.contentVisible = this.isContentVisible();
  }
  beginCompat() {}
  endCompat() {}
  consumePath(clipBox) {
    const isEmpty = this.current.isEmptyClip();
    if (this.pendingClip) {
      this.current.updateClipFromPath();
    }
    if (!this.pendingClip) {
      this.compose(clipBox);
    }
    const ctx = this.ctx;
    if (this.pendingClip) {
      if (!isEmpty) {
        if (this.pendingClip === EO_CLIP) {
          ctx.clip("evenodd");
        } else {
          ctx.clip();
        }
      }
      this.pendingClip = null;
    }
    this.current.startNewPathAndClipBox(this.current.clipBox);
    ctx.beginPath();
  }
  getSinglePixelWidth() {
    if (!this._cachedGetSinglePixelWidth) {
      const m = (0, _display_utils.getCurrentTransform)(this.ctx);
      if (m[1] === 0 && m[2] === 0) {
        this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
      } else {
        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
        const normX = Math.hypot(m[0], m[2]);
        const normY = Math.hypot(m[1], m[3]);
        this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
      }
    }
    return this._cachedGetSinglePixelWidth;
  }
  getScaleForStroking() {
    if (!this._cachedScaleForStroking) {
      const {
        lineWidth
      } = this.current;
      const m = (0, _display_utils.getCurrentTransform)(this.ctx);
      let scaleX, scaleY;
      if (m[1] === 0 && m[2] === 0) {
        const normX = Math.abs(m[0]);
        const normY = Math.abs(m[3]);
        if (lineWidth === 0) {
          scaleX = 1 / normX;
          scaleY = 1 / normY;
        } else {
          const scaledXLineWidth = normX * lineWidth;
          const scaledYLineWidth = normY * lineWidth;
          scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
          scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
        }
      } else {
        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
        const normX = Math.hypot(m[0], m[1]);
        const normY = Math.hypot(m[2], m[3]);
        if (lineWidth === 0) {
          scaleX = normY / absDet;
          scaleY = normX / absDet;
        } else {
          const baseArea = lineWidth * absDet;
          scaleX = normY > baseArea ? normY / baseArea : 1;
          scaleY = normX > baseArea ? normX / baseArea : 1;
        }
      }
      this._cachedScaleForStroking = [scaleX, scaleY];
    }
    return this._cachedScaleForStroking;
  }
  rescaleAndStroke(saveRestore) {
    const {
      ctx
    } = this;
    const {
      lineWidth
    } = this.current;
    const [scaleX, scaleY] = this.getScaleForStroking();
    ctx.lineWidth = lineWidth || 1;
    if (scaleX === 1 && scaleY === 1) {
      ctx.stroke();
      return;
    }
    let savedMatrix, savedDashes, savedDashOffset;
    if (saveRestore) {
      savedMatrix = (0, _display_utils.getCurrentTransform)(ctx);
      savedDashes = ctx.getLineDash().slice();
      savedDashOffset = ctx.lineDashOffset;
    }
    ctx.scale(scaleX, scaleY);
    const scale = Math.max(scaleX, scaleY);
    ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
    ctx.lineDashOffset /= scale;
    ctx.stroke();
    if (saveRestore) {
      ctx.setTransform(...savedMatrix);
      ctx.setLineDash(savedDashes);
      ctx.lineDashOffset = savedDashOffset;
    }
  }
  isContentVisible() {
    for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
      if (!this.markedContentStack[i].visible) {
        return false;
      }
    }
    return true;
  }
}
exports.CanvasGraphics = CanvasGraphics;
for (const op in _util.OPS) {
  if (CanvasGraphics.prototype[op] !== undefined) {
    CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
  }
}

/***/ }),
/* 12 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.TilingPattern = exports.PathType = void 0;
exports.getShadingPattern = getShadingPattern;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
const PathType = {
  FILL: "Fill",
  STROKE: "Stroke",
  SHADING: "Shading"
};
exports.PathType = PathType;
function applyBoundingBox(ctx, bbox) {
  if (!bbox) {
    return;
  }
  const width = bbox[2] - bbox[0];
  const height = bbox[3] - bbox[1];
  const region = new Path2D();
  region.rect(bbox[0], bbox[1], width, height);
  ctx.clip(region);
}
class BaseShadingPattern {
  constructor() {
    if (this.constructor === BaseShadingPattern) {
      (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
    }
  }
  getPattern() {
    (0, _util.unreachable)("Abstract method `getPattern` called.");
  }
}
class RadialAxialShadingPattern extends BaseShadingPattern {
  constructor(IR) {
    super();
    this._type = IR[1];
    this._bbox = IR[2];
    this._colorStops = IR[3];
    this._p0 = IR[4];
    this._p1 = IR[5];
    this._r0 = IR[6];
    this._r1 = IR[7];
    this.matrix = null;
  }
  _createGradient(ctx) {
    let grad;
    if (this._type === "axial") {
      grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
    } else if (this._type === "radial") {
      grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
    }
    for (const colorStop of this._colorStops) {
      grad.addColorStop(colorStop[0], colorStop[1]);
    }
    return grad;
  }
  getPattern(ctx, owner, inverse, pathType) {
    let pattern;
    if (pathType === PathType.STROKE || pathType === PathType.FILL) {
      const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
      const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
      const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
      const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
      const tmpCtx = tmpCanvas.context;
      tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
      tmpCtx.beginPath();
      tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
      tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
      inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
      tmpCtx.transform(...owner.baseTransform);
      if (this.matrix) {
        tmpCtx.transform(...this.matrix);
      }
      applyBoundingBox(tmpCtx, this._bbox);
      tmpCtx.fillStyle = this._createGradient(tmpCtx);
      tmpCtx.fill();
      pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
      const domMatrix = new DOMMatrix(inverse);
      pattern.setTransform(domMatrix);
    } else {
      applyBoundingBox(ctx, this._bbox);
      pattern = this._createGradient(ctx);
    }
    return pattern;
  }
}
function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  const coords = context.coords,
    colors = context.colors;
  const bytes = data.data,
    rowSize = data.width * 4;
  let tmp;
  if (coords[p1 + 1] > coords[p2 + 1]) {
    tmp = p1;
    p1 = p2;
    p2 = tmp;
    tmp = c1;
    c1 = c2;
    c2 = tmp;
  }
  if (coords[p2 + 1] > coords[p3 + 1]) {
    tmp = p2;
    p2 = p3;
    p3 = tmp;
    tmp = c2;
    c2 = c3;
    c3 = tmp;
  }
  if (coords[p1 + 1] > coords[p2 + 1]) {
    tmp = p1;
    p1 = p2;
    p2 = tmp;
    tmp = c1;
    c1 = c2;
    c2 = tmp;
  }
  const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  if (y1 >= y3) {
    return;
  }
  const c1r = colors[c1],
    c1g = colors[c1 + 1],
    c1b = colors[c1 + 2];
  const c2r = colors[c2],
    c2g = colors[c2 + 1],
    c2b = colors[c2 + 2];
  const c3r = colors[c3],
    c3g = colors[c3 + 1],
    c3b = colors[c3 + 2];
  const minY = Math.round(y1),
    maxY = Math.round(y3);
  let xa, car, cag, cab;
  let xb, cbr, cbg, cbb;
  for (let y = minY; y <= maxY; y++) {
    if (y < y2) {
      let k;
      if (y < y1) {
        k = 0;
      } else {
        k = (y1 - y) / (y1 - y2);
      }
      xa = x1 - (x1 - x2) * k;
      car = c1r - (c1r - c2r) * k;
      cag = c1g - (c1g - c2g) * k;
      cab = c1b - (c1b - c2b) * k;
    } else {
      let k;
      if (y > y3) {
        k = 1;
      } else if (y2 === y3) {
        k = 0;
      } else {
        k = (y2 - y) / (y2 - y3);
      }
      xa = x2 - (x2 - x3) * k;
      car = c2r - (c2r - c3r) * k;
      cag = c2g - (c2g - c3g) * k;
      cab = c2b - (c2b - c3b) * k;
    }
    let k;
    if (y < y1) {
      k = 0;
    } else if (y > y3) {
      k = 1;
    } else {
      k = (y1 - y) / (y1 - y3);
    }
    xb = x1 - (x1 - x3) * k;
    cbr = c1r - (c1r - c3r) * k;
    cbg = c1g - (c1g - c3g) * k;
    cbb = c1b - (c1b - c3b) * k;
    const x1_ = Math.round(Math.min(xa, xb));
    const x2_ = Math.round(Math.max(xa, xb));
    let j = rowSize * y + x1_ * 4;
    for (let x = x1_; x <= x2_; x++) {
      k = (xa - x) / (xa - xb);
      if (k < 0) {
        k = 0;
      } else if (k > 1) {
        k = 1;
      }
      bytes[j++] = car - (car - cbr) * k | 0;
      bytes[j++] = cag - (cag - cbg) * k | 0;
      bytes[j++] = cab - (cab - cbb) * k | 0;
      bytes[j++] = 255;
    }
  }
}
function drawFigure(data, figure, context) {
  const ps = figure.coords;
  const cs = figure.colors;
  let i, ii;
  switch (figure.type) {
    case "lattice":
      const verticesPerRow = figure.verticesPerRow;
      const rows = Math.floor(ps.length / verticesPerRow) - 1;
      const cols = verticesPerRow - 1;
      for (i = 0; i < rows; i++) {
        let q = i * verticesPerRow;
        for (let j = 0; j < cols; j++, q++) {
          drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
          drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
        }
      }
      break;
    case "triangles":
      for (i = 0, ii = ps.length; i < ii; i += 3) {
        drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
      }
      break;
    default:
      throw new Error("illegal figure");
  }
}
class MeshShadingPattern extends BaseShadingPattern {
  constructor(IR) {
    super();
    this._coords = IR[2];
    this._colors = IR[3];
    this._figures = IR[4];
    this._bounds = IR[5];
    this._bbox = IR[7];
    this._background = IR[8];
    this.matrix = null;
  }
  _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
    const EXPECTED_SCALE = 1.1;
    const MAX_PATTERN_SIZE = 3000;
    const BORDER_SIZE = 2;
    const offsetX = Math.floor(this._bounds[0]);
    const offsetY = Math.floor(this._bounds[1]);
    const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
    const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
    const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
    const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
    const scaleX = boundsWidth / width;
    const scaleY = boundsHeight / height;
    const context = {
      coords: this._coords,
      colors: this._colors,
      offsetX: -offsetX,
      offsetY: -offsetY,
      scaleX: 1 / scaleX,
      scaleY: 1 / scaleY
    };
    const paddedWidth = width + BORDER_SIZE * 2;
    const paddedHeight = height + BORDER_SIZE * 2;
    const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
    const tmpCtx = tmpCanvas.context;
    const data = tmpCtx.createImageData(width, height);
    if (backgroundColor) {
      const bytes = data.data;
      for (let i = 0, ii = bytes.length; i < ii; i += 4) {
        bytes[i] = backgroundColor[0];
        bytes[i + 1] = backgroundColor[1];
        bytes[i + 2] = backgroundColor[2];
        bytes[i + 3] = 255;
      }
    }
    for (const figure of this._figures) {
      drawFigure(data, figure, context);
    }
    tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
    const canvas = tmpCanvas.canvas;
    return {
      canvas,
      offsetX: offsetX - BORDER_SIZE * scaleX,
      offsetY: offsetY - BORDER_SIZE * scaleY,
      scaleX,
      scaleY
    };
  }
  getPattern(ctx, owner, inverse, pathType) {
    applyBoundingBox(ctx, this._bbox);
    let scale;
    if (pathType === PathType.SHADING) {
      scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
    } else {
      scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
      if (this.matrix) {
        const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
        scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
      }
    }
    const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
    if (pathType !== PathType.SHADING) {
      ctx.setTransform(...owner.baseTransform);
      if (this.matrix) {
        ctx.transform(...this.matrix);
      }
    }
    ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
    ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
    return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  }
}
class DummyShadingPattern extends BaseShadingPattern {
  getPattern() {
    return "hotpink";
  }
}
function getShadingPattern(IR) {
  switch (IR[0]) {
    case "RadialAxial":
      return new RadialAxialShadingPattern(IR);
    case "Mesh":
      return new MeshShadingPattern(IR);
    case "Dummy":
      return new DummyShadingPattern();
  }
  throw new Error(`Unknown IR type: ${IR[0]}`);
}
const PaintType = {
  COLORED: 1,
  UNCOLORED: 2
};
class TilingPattern {
  static get MAX_PATTERN_SIZE() {
    return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  }
  constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
    this.operatorList = IR[2];
    this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
    this.bbox = IR[4];
    this.xstep = IR[5];
    this.ystep = IR[6];
    this.paintType = IR[7];
    this.tilingType = IR[8];
    this.color = color;
    this.ctx = ctx;
    this.canvasGraphicsFactory = canvasGraphicsFactory;
    this.baseTransform = baseTransform;
  }
  createPatternCanvas(owner) {
    const operatorList = this.operatorList;
    const bbox = this.bbox;
    const xstep = this.xstep;
    const ystep = this.ystep;
    const paintType = this.paintType;
    const tilingType = this.tilingType;
    const color = this.color;
    const canvasGraphicsFactory = this.canvasGraphicsFactory;
    (0, _util.info)("TilingType: " + tilingType);
    const x0 = bbox[0],
      y0 = bbox[1],
      x1 = bbox[2],
      y1 = bbox[3];
    const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
    const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
    const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
    const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
    const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
    const tmpCtx = tmpCanvas.context;
    const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
    graphics.groupLevel = owner.groupLevel;
    this.setFillAndStrokeStyleToContext(graphics, paintType, color);
    let adjustedX0 = x0;
    let adjustedY0 = y0;
    let adjustedX1 = x1;
    let adjustedY1 = y1;
    if (x0 < 0) {
      adjustedX0 = 0;
      adjustedX1 += Math.abs(x0);
    }
    if (y0 < 0) {
      adjustedY0 = 0;
      adjustedY1 += Math.abs(y0);
    }
    tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
    graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
    tmpCtx.save();
    this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
    graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
    graphics.executeOperatorList(operatorList);
    graphics.endDrawing();
    return {
      canvas: tmpCanvas.canvas,
      scaleX: dimx.scale,
      scaleY: dimy.scale,
      offsetX: adjustedX0,
      offsetY: adjustedY0
    };
  }
  getSizeAndScale(step, realOutputSize, scale) {
    step = Math.abs(step);
    const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
    let size = Math.ceil(step * scale);
    if (size >= maxSize) {
      size = maxSize;
    } else {
      scale = size / step;
    }
    return {
      scale,
      size
    };
  }
  clipBbox(graphics, x0, y0, x1, y1) {
    const bboxWidth = x1 - x0;
    const bboxHeight = y1 - y0;
    graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
    graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
    graphics.clip();
    graphics.endPath();
  }
  setFillAndStrokeStyleToContext(graphics, paintType, color) {
    const context = graphics.ctx,
      current = graphics.current;
    switch (paintType) {
      case PaintType.COLORED:
        const ctx = this.ctx;
        context.fillStyle = ctx.fillStyle;
        context.strokeStyle = ctx.strokeStyle;
        current.fillColor = ctx.fillStyle;
        current.strokeColor = ctx.strokeStyle;
        break;
      case PaintType.UNCOLORED:
        const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
        context.fillStyle = cssColor;
        context.strokeStyle = cssColor;
        current.fillColor = cssColor;
        current.strokeColor = cssColor;
        break;
      default:
        throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
    }
  }
  getPattern(ctx, owner, inverse, pathType) {
    let matrix = inverse;
    if (pathType !== PathType.SHADING) {
      matrix = _util.Util.transform(matrix, owner.baseTransform);
      if (this.matrix) {
        matrix = _util.Util.transform(matrix, this.matrix);
      }
    }
    const temporaryPatternCanvas = this.createPatternCanvas(owner);
    let domMatrix = new DOMMatrix(matrix);
    domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
    domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
    const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
    pattern.setTransform(domMatrix);
    return pattern;
  }
}
exports.TilingPattern = TilingPattern;

/***/ }),
/* 13 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.applyMaskImageData = applyMaskImageData;
var _util = __w_pdfjs_require__(1);
function applyMaskImageData({
  src,
  srcPos = 0,
  dest,
  destPos = 0,
  width,
  height,
  inverseDecode = false
}) {
  const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  const widthInSource = width >> 3;
  const widthRemainder = width & 7;
  const srcLength = src.length;
  dest = new Uint32Array(dest.buffer);
  for (let i = 0; i < height; i++) {
    for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
      const elem = srcPos < srcLength ? src[srcPos] : 255;
      dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
    }
    if (widthRemainder === 0) {
      continue;
    }
    const elem = srcPos < srcLength ? src[srcPos++] : 255;
    for (let j = 0; j < widthRemainder; j++) {
      dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
    }
  }
  return {
    srcPos,
    destPos
  };
}

/***/ }),
/* 14 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.GlobalWorkerOptions = void 0;
const GlobalWorkerOptions = Object.create(null);
exports.GlobalWorkerOptions = GlobalWorkerOptions;
GlobalWorkerOptions.workerPort = null;
GlobalWorkerOptions.workerSrc = "";

/***/ }),
/* 15 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MessageHandler = void 0;
var _util = __w_pdfjs_require__(1);
const CallbackKind = {
  UNKNOWN: 0,
  DATA: 1,
  ERROR: 2
};
const StreamKind = {
  UNKNOWN: 0,
  CANCEL: 1,
  CANCEL_COMPLETE: 2,
  CLOSE: 3,
  ENQUEUE: 4,
  ERROR: 5,
  PULL: 6,
  PULL_COMPLETE: 7,
  START_COMPLETE: 8
};
function wrapReason(reason) {
  if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
    (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  }
  switch (reason.name) {
    case "AbortException":
      return new _util.AbortException(reason.message);
    case "MissingPDFException":
      return new _util.MissingPDFException(reason.message);
    case "PasswordException":
      return new _util.PasswordException(reason.message, reason.code);
    case "UnexpectedResponseException":
      return new _util.UnexpectedResponseException(reason.message, reason.status);
    case "UnknownErrorException":
      return new _util.UnknownErrorException(reason.message, reason.details);
    default:
      return new _util.UnknownErrorException(reason.message, reason.toString());
  }
}
class MessageHandler {
  constructor(sourceName, targetName, comObj) {
    this.sourceName = sourceName;
    this.targetName = targetName;
    this.comObj = comObj;
    this.callbackId = 1;
    this.streamId = 1;
    this.streamSinks = Object.create(null);
    this.streamControllers = Object.create(null);
    this.callbackCapabilities = Object.create(null);
    this.actionHandler = Object.create(null);
    this._onComObjOnMessage = event => {
      const data = event.data;
      if (data.targetName !== this.sourceName) {
        return;
      }
      if (data.stream) {
        this._processStreamMessage(data);
        return;
      }
      if (data.callback) {
        const callbackId = data.callbackId;
        const capability = this.callbackCapabilities[callbackId];
        if (!capability) {
          throw new Error(`Cannot resolve callback ${callbackId}`);
        }
        delete this.callbackCapabilities[callbackId];
        if (data.callback === CallbackKind.DATA) {
          capability.resolve(data.data);
        } else if (data.callback === CallbackKind.ERROR) {
          capability.reject(wrapReason(data.reason));
        } else {
          throw new Error("Unexpected callback case");
        }
        return;
      }
      const action = this.actionHandler[data.action];
      if (!action) {
        throw new Error(`Unknown action from worker: ${data.action}`);
      }
      if (data.callbackId) {
        const cbSourceName = this.sourceName;
        const cbTargetName = data.sourceName;
        new Promise(function (resolve) {
          resolve(action(data.data));
        }).then(function (result) {
          comObj.postMessage({
            sourceName: cbSourceName,
            targetName: cbTargetName,
            callback: CallbackKind.DATA,
            callbackId: data.callbackId,
            data: result
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName: cbSourceName,
            targetName: cbTargetName,
            callback: CallbackKind.ERROR,
            callbackId: data.callbackId,
            reason: wrapReason(reason)
          });
        });
        return;
      }
      if (data.streamId) {
        this._createStreamSink(data);
        return;
      }
      action(data.data);
    };
    comObj.addEventListener("message", this._onComObjOnMessage);
  }
  on(actionName, handler) {
    const ah = this.actionHandler;
    if (ah[actionName]) {
      throw new Error(`There is already an actionName called "${actionName}"`);
    }
    ah[actionName] = handler;
  }
  send(actionName, data, transfers) {
    this.comObj.postMessage({
      sourceName: this.sourceName,
      targetName: this.targetName,
      action: actionName,
      data
    }, transfers);
  }
  sendWithPromise(actionName, data, transfers) {
    const callbackId = this.callbackId++;
    const capability = (0, _util.createPromiseCapability)();
    this.callbackCapabilities[callbackId] = capability;
    try {
      this.comObj.postMessage({
        sourceName: this.sourceName,
        targetName: this.targetName,
        action: actionName,
        callbackId,
        data
      }, transfers);
    } catch (ex) {
      capability.reject(ex);
    }
    return capability.promise;
  }
  sendWithStream(actionName, data, queueingStrategy, transfers) {
    const streamId = this.streamId++,
      sourceName = this.sourceName,
      targetName = this.targetName,
      comObj = this.comObj;
    return new ReadableStream({
      start: controller => {
        const startCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId] = {
          controller,
          startCall: startCapability,
          pullCall: null,
          cancelCall: null,
          isClosed: false
        };
        comObj.postMessage({
          sourceName,
          targetName,
          action: actionName,
          streamId,
          data,
          desiredSize: controller.desiredSize
        }, transfers);
        return startCapability.promise;
      },
      pull: controller => {
        const pullCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId].pullCall = pullCapability;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.PULL,
          streamId,
          desiredSize: controller.desiredSize
        });
        return pullCapability.promise;
      },
      cancel: reason => {
        (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
        const cancelCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId].cancelCall = cancelCapability;
        this.streamControllers[streamId].isClosed = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CANCEL,
          streamId,
          reason: wrapReason(reason)
        });
        return cancelCapability.promise;
      }
    }, queueingStrategy);
  }
  _createStreamSink(data) {
    const streamId = data.streamId,
      sourceName = this.sourceName,
      targetName = data.sourceName,
      comObj = this.comObj;
    const self = this,
      action = this.actionHandler[data.action];
    const streamSink = {
      enqueue(chunk, size = 1, transfers) {
        if (this.isCancelled) {
          return;
        }
        const lastDesiredSize = this.desiredSize;
        this.desiredSize -= size;
        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
          this.sinkCapability = (0, _util.createPromiseCapability)();
          this.ready = this.sinkCapability.promise;
        }
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ENQUEUE,
          streamId,
          chunk
        }, transfers);
      },
      close() {
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CLOSE,
          streamId
        });
        delete self.streamSinks[streamId];
      },
      error(reason) {
        (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ERROR,
          streamId,
          reason: wrapReason(reason)
        });
      },
      sinkCapability: (0, _util.createPromiseCapability)(),
      onPull: null,
      onCancel: null,
      isCancelled: false,
      desiredSize: data.desiredSize,
      ready: null
    };
    streamSink.sinkCapability.resolve();
    streamSink.ready = streamSink.sinkCapability.promise;
    this.streamSinks[streamId] = streamSink;
    new Promise(function (resolve) {
      resolve(action(data.data, streamSink));
    }).then(function () {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        success: true
      });
    }, function (reason) {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        reason: wrapReason(reason)
      });
    });
  }
  _processStreamMessage(data) {
    const streamId = data.streamId,
      sourceName = this.sourceName,
      targetName = data.sourceName,
      comObj = this.comObj;
    const streamController = this.streamControllers[streamId],
      streamSink = this.streamSinks[streamId];
    switch (data.stream) {
      case StreamKind.START_COMPLETE:
        if (data.success) {
          streamController.startCall.resolve();
        } else {
          streamController.startCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL_COMPLETE:
        if (data.success) {
          streamController.pullCall.resolve();
        } else {
          streamController.pullCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL:
        if (!streamSink) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
          break;
        }
        if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
          streamSink.sinkCapability.resolve();
        }
        streamSink.desiredSize = data.desiredSize;
        new Promise(function (resolve) {
          resolve(streamSink.onPull && streamSink.onPull());
        }).then(function () {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        break;
      case StreamKind.ENQUEUE:
        (0, _util.assert)(streamController, "enqueue should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.controller.enqueue(data.chunk);
        break;
      case StreamKind.CLOSE:
        (0, _util.assert)(streamController, "close should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.isClosed = true;
        streamController.controller.close();
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.ERROR:
        (0, _util.assert)(streamController, "error should have stream controller");
        streamController.controller.error(wrapReason(data.reason));
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL_COMPLETE:
        if (data.success) {
          streamController.cancelCall.resolve();
        } else {
          streamController.cancelCall.reject(wrapReason(data.reason));
        }
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL:
        if (!streamSink) {
          break;
        }
        new Promise(function (resolve) {
          resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
        }).then(function () {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            success: true
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        streamSink.sinkCapability.reject(wrapReason(data.reason));
        streamSink.isCancelled = true;
        delete this.streamSinks[streamId];
        break;
      default:
        throw new Error("Unexpected stream case");
    }
  }
  async _deleteStreamController(streamController, streamId) {
    await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
    delete this.streamControllers[streamId];
  }
  destroy() {
    this.comObj.removeEventListener("message", this._onComObjOnMessage);
  }
}
exports.MessageHandler = MessageHandler;

/***/ }),
/* 16 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Metadata = void 0;
var _util = __w_pdfjs_require__(1);
class Metadata {
  #metadataMap;
  #data;
  constructor({
    parsedData,
    rawData
  }) {
    this.#metadataMap = parsedData;
    this.#data = rawData;
  }
  getRaw() {
    return this.#data;
  }
  get(name) {
    return this.#metadataMap.get(name) ?? null;
  }
  getAll() {
    return (0, _util.objectFromMap)(this.#metadataMap);
  }
  has(name) {
    return this.#metadataMap.has(name);
  }
}
exports.Metadata = Metadata;

/***/ }),
/* 17 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.OptionalContentConfig = void 0;
var _util = __w_pdfjs_require__(1);
var _murmurhash = __w_pdfjs_require__(8);
const INTERNAL = Symbol("INTERNAL");
class OptionalContentGroup {
  #visible = true;
  constructor(name, intent) {
    this.name = name;
    this.intent = intent;
  }
  get visible() {
    return this.#visible;
  }
  _setVisible(internal, visible) {
    if (internal !== INTERNAL) {
      (0, _util.unreachable)("Internal method `_setVisible` called.");
    }
    this.#visible = visible;
  }
}
class OptionalContentConfig {
  #cachedGetHash = null;
  #groups = new Map();
  #initialHash = null;
  #order = null;
  constructor(data) {
    this.name = null;
    this.creator = null;
    if (data === null) {
      return;
    }
    this.name = data.name;
    this.creator = data.creator;
    this.#order = data.order;
    for (const group of data.groups) {
      this.#groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
    }
    if (data.baseState === "OFF") {
      for (const group of this.#groups.values()) {
        group._setVisible(INTERNAL, false);
      }
    }
    for (const on of data.on) {
      this.#groups.get(on)._setVisible(INTERNAL, true);
    }
    for (const off of data.off) {
      this.#groups.get(off)._setVisible(INTERNAL, false);
    }
    this.#initialHash = this.getHash();
  }
  #evaluateVisibilityExpression(array) {
    const length = array.length;
    if (length < 2) {
      return true;
    }
    const operator = array[0];
    for (let i = 1; i < length; i++) {
      const element = array[i];
      let state;
      if (Array.isArray(element)) {
        state = this.#evaluateVisibilityExpression(element);
      } else if (this.#groups.has(element)) {
        state = this.#groups.get(element).visible;
      } else {
        (0, _util.warn)(`Optional content group not found: ${element}`);
        return true;
      }
      switch (operator) {
        case "And":
          if (!state) {
            return false;
          }
          break;
        case "Or":
          if (state) {
            return true;
          }
          break;
        case "Not":
          return !state;
        default:
          return true;
      }
    }
    return operator === "And";
  }
  isVisible(group) {
    if (this.#groups.size === 0) {
      return true;
    }
    if (!group) {
      (0, _util.warn)("Optional content group not defined.");
      return true;
    }
    if (group.type === "OCG") {
      if (!this.#groups.has(group.id)) {
        (0, _util.warn)(`Optional content group not found: ${group.id}`);
        return true;
      }
      return this.#groups.get(group.id).visible;
    } else if (group.type === "OCMD") {
      if (group.expression) {
        return this.#evaluateVisibilityExpression(group.expression);
      }
      if (!group.policy || group.policy === "AnyOn") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            (0, _util.warn)(`Optional content group not found: ${id}`);
            return true;
          }
          if (this.#groups.get(id).visible) {
            return true;
          }
        }
        return false;
      } else if (group.policy === "AllOn") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            (0, _util.warn)(`Optional content group not found: ${id}`);
            return true;
          }
          if (!this.#groups.get(id).visible) {
            return false;
          }
        }
        return true;
      } else if (group.policy === "AnyOff") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            (0, _util.warn)(`Optional content group not found: ${id}`);
            return true;
          }
          if (!this.#groups.get(id).visible) {
            return true;
          }
        }
        return false;
      } else if (group.policy === "AllOff") {
        for (const id of group.ids) {
          if (!this.#groups.has(id)) {
            (0, _util.warn)(`Optional content group not found: ${id}`);
            return true;
          }
          if (this.#groups.get(id).visible) {
            return false;
          }
        }
        return true;
      }
      (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
      return true;
    }
    (0, _util.warn)(`Unknown group type ${group.type}.`);
    return true;
  }
  setVisibility(id, visible = true) {
    if (!this.#groups.has(id)) {
      (0, _util.warn)(`Optional content group not found: ${id}`);
      return;
    }
    this.#groups.get(id)._setVisible(INTERNAL, !!visible);
    this.#cachedGetHash = null;
  }
  get hasInitialVisibility() {
    return this.getHash() === this.#initialHash;
  }
  getOrder() {
    if (!this.#groups.size) {
      return null;
    }
    if (this.#order) {
      return this.#order.slice();
    }
    return [...this.#groups.keys()];
  }
  getGroups() {
    return this.#groups.size > 0 ? (0, _util.objectFromMap)(this.#groups) : null;
  }
  getGroup(id) {
    return this.#groups.get(id) || null;
  }
  getHash() {
    if (this.#cachedGetHash !== null) {
      return this.#cachedGetHash;
    }
    const hash = new _murmurhash.MurmurHash3_64();
    for (const [id, group] of this.#groups) {
      hash.update(`${id}:${group.visible}`);
    }
    return this.#cachedGetHash = hash.hexdigest();
  }
}
exports.OptionalContentConfig = OptionalContentConfig;

/***/ }),
/* 18 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFDataTransportStream = void 0;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
class PDFDataTransportStream {
  constructor({
    length,
    initialData,
    progressiveDone = false,
    contentDispositionFilename = null,
    disableRange = false,
    disableStream = false
  }, pdfDataRangeTransport) {
    (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
    this._queuedChunks = [];
    this._progressiveDone = progressiveDone;
    this._contentDispositionFilename = contentDispositionFilename;
    if (initialData?.length > 0) {
      const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer;
      this._queuedChunks.push(buffer);
    }
    this._pdfDataRangeTransport = pdfDataRangeTransport;
    this._isStreamingSupported = !disableStream;
    this._isRangeSupported = !disableRange;
    this._contentLength = length;
    this._fullRequestReader = null;
    this._rangeReaders = [];
    this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
      this._onReceiveData({
        begin,
        chunk
      });
    });
    this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
      this._onProgress({
        loaded,
        total
      });
    });
    this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
      this._onReceiveData({
        chunk
      });
    });
    this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
      this._onProgressiveDone();
    });
    this._pdfDataRangeTransport.transportReady();
  }
  _onReceiveData({
    begin,
    chunk
  }) {
    const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer;
    if (begin === undefined) {
      if (this._fullRequestReader) {
        this._fullRequestReader._enqueue(buffer);
      } else {
        this._queuedChunks.push(buffer);
      }
    } else {
      const found = this._rangeReaders.some(function (rangeReader) {
        if (rangeReader._begin !== begin) {
          return false;
        }
        rangeReader._enqueue(buffer);
        return true;
      });
      (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
    }
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  _onProgress(evt) {
    if (evt.total === undefined) {
      this._rangeReaders[0]?.onProgress?.({
        loaded: evt.loaded
      });
    } else {
      this._fullRequestReader?.onProgress?.({
        loaded: evt.loaded,
        total: evt.total
      });
    }
  }
  _onProgressiveDone() {
    this._fullRequestReader?.progressiveDone();
    this._progressiveDone = true;
  }
  _removeRangeReader(reader) {
    const i = this._rangeReaders.indexOf(reader);
    if (i >= 0) {
      this._rangeReaders.splice(i, 1);
    }
  }
  getFullReader() {
    (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
    const queuedChunks = this._queuedChunks;
    this._queuedChunks = null;
    return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
  }
  getRangeReader(begin, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
    this._pdfDataRangeTransport.requestDataRange(begin, end);
    this._rangeReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeReaders.slice(0)) {
      reader.cancel(reason);
    }
    this._pdfDataRangeTransport.abort();
  }
}
exports.PDFDataTransportStream = PDFDataTransportStream;
class PDFDataTransportStreamReader {
  constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
    this._stream = stream;
    this._done = progressiveDone || false;
    this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
    this._queuedChunks = queuedChunks || [];
    this._loaded = 0;
    for (const chunk of this._queuedChunks) {
      this._loaded += chunk.byteLength;
    }
    this._requests = [];
    this._headersReady = Promise.resolve();
    stream._fullRequestReader = this;
    this.onProgress = null;
  }
  _enqueue(chunk) {
    if (this._done) {
      return;
    }
    if (this._requests.length > 0) {
      const requestCapability = this._requests.shift();
      requestCapability.resolve({
        value: chunk,
        done: false
      });
    } else {
      this._queuedChunks.push(chunk);
    }
    this._loaded += chunk.byteLength;
  }
  get headersReady() {
    return this._headersReady;
  }
  get filename() {
    return this._filename;
  }
  get isRangeSupported() {
    return this._stream._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._stream._isStreamingSupported;
  }
  get contentLength() {
    return this._stream._contentLength;
  }
  async read() {
    if (this._queuedChunks.length > 0) {
      const chunk = this._queuedChunks.shift();
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    const requestCapability = (0, _util.createPromiseCapability)();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
  }
  progressiveDone() {
    if (this._done) {
      return;
    }
    this._done = true;
  }
}
class PDFDataTransportStreamRangeReader {
  constructor(stream, begin, end) {
    this._stream = stream;
    this._begin = begin;
    this._end = end;
    this._queuedChunk = null;
    this._requests = [];
    this._done = false;
    this.onProgress = null;
  }
  _enqueue(chunk) {
    if (this._done) {
      return;
    }
    if (this._requests.length === 0) {
      this._queuedChunk = chunk;
    } else {
      const requestsCapability = this._requests.shift();
      requestsCapability.resolve({
        value: chunk,
        done: false
      });
      for (const requestCapability of this._requests) {
        requestCapability.resolve({
          value: undefined,
          done: true
        });
      }
      this._requests.length = 0;
    }
    this._done = true;
    this._stream._removeRangeReader(this);
  }
  get isStreamingSupported() {
    return false;
  }
  async read() {
    if (this._queuedChunk) {
      const chunk = this._queuedChunk;
      this._queuedChunk = null;
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    const requestCapability = (0, _util.createPromiseCapability)();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
    this._stream._removeRangeReader(this);
  }
}

/***/ }),
/* 19 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XfaText = void 0;
class XfaText {
  static textContent(xfa) {
    const items = [];
    const output = {
      items,
      styles: Object.create(null)
    };
    function walk(node) {
      if (!node) {
        return;
      }
      let str = null;
      const name = node.name;
      if (name === "#text") {
        str = node.value;
      } else if (!XfaText.shouldBuildText(name)) {
        return;
      } else if (node?.attributes?.textContent) {
        str = node.attributes.textContent;
      } else if (node.value) {
        str = node.value;
      }
      if (str !== null) {
        items.push({
          str
        });
      }
      if (!node.children) {
        return;
      }
      for (const child of node.children) {
        walk(child);
      }
    }
    walk(xfa);
    return output;
  }
  static shouldBuildText(name) {
    return !(name === "textarea" || name === "input" || name === "option" || name === "select");
  }
}
exports.XfaText = XfaText;

/***/ }),
/* 20 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
var _base_factory = __w_pdfjs_require__(7);
;
const fetchData = function (url) {
  return new Promise((resolve, reject) => {
    const fs = require("fs");
    fs.readFile(url, (error, data) => {
      if (error || !data) {
        reject(new Error(error));
        return;
      }
      resolve(new Uint8Array(data));
    });
  });
};
class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
  _createCanvas(width, height) {
    const Canvas = require("canvas");
    return Canvas.createCanvas(width, height);
  }
}
exports.NodeCanvasFactory = NodeCanvasFactory;
class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
  _fetchData(url, compressionType) {
    return fetchData(url).then(data => {
      return {
        cMapData: data,
        compressionType
      };
    });
  }
}
exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
  _fetchData(url) {
    return fetchData(url);
  }
}
exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;

/***/ }),
/* 21 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFNodeStream = void 0;
var _util = __w_pdfjs_require__(1);
var _network_utils = __w_pdfjs_require__(22);
;
const fs = require("fs");
const http = require("http");
const https = require("https");
const url = require("url");
const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
function parseUrl(sourceUrl) {
  const parsedUrl = url.parse(sourceUrl);
  if (parsedUrl.protocol === "file:" || parsedUrl.host) {
    return parsedUrl;
  }
  if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
    return url.parse(`file:///${sourceUrl}`);
  }
  if (!parsedUrl.host) {
    parsedUrl.protocol = "file:";
  }
  return parsedUrl;
}
class PDFNodeStream {
  constructor(source) {
    this.source = source;
    this.url = parseUrl(source.url);
    this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
    this.isFsUrl = this.url.protocol === "file:";
    this.httpHeaders = this.isHttp && source.httpHeaders || {};
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  getFullReader() {
    (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
    this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
    return this._fullRequestReader;
  }
  getRangeReader(start, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
    this._rangeRequestReaders.push(rangeReader);
    return rangeReader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
}
exports.PDFNodeStream = PDFNodeStream;
class BaseFullReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._storedError = null;
    this.onProgress = null;
    const source = stream.source;
    this._contentLength = source.length;
    this._loaded = 0;
    this._filename = null;
    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;
    this._readableStream = null;
    this._readCapability = (0, _util.createPromiseCapability)();
    this._headersCapability = (0, _util.createPromiseCapability)();
  }
  get headersReady() {
    return this._headersCapability.promise;
  }
  get filename() {
    return this._filename;
  }
  get contentLength() {
    return this._contentLength;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    if (this._storedError) {
      throw this._storedError;
    }
    const chunk = this._readableStream.read();
    if (chunk === null) {
      this._readCapability = (0, _util.createPromiseCapability)();
      return this.read();
    }
    this._loaded += chunk.length;
    this.onProgress?.({
      loaded: this._loaded,
      total: this._contentLength
    });
    const buffer = new Uint8Array(chunk).buffer;
    return {
      value: buffer,
      done: false
    };
  }
  cancel(reason) {
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }
  _error(reason) {
    this._storedError = reason;
    this._readCapability.resolve();
  }
  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on("readable", () => {
      this._readCapability.resolve();
    });
    readableStream.on("end", () => {
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });
    readableStream.on("error", reason => {
      this._error(reason);
    });
    if (!this._isStreamingSupported && this._isRangeSupported) {
      this._error(new _util.AbortException("streaming is disabled"));
    }
    if (this._storedError) {
      this._readableStream.destroy(this._storedError);
    }
  }
}
class BaseRangeReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._storedError = null;
    this.onProgress = null;
    this._loaded = 0;
    this._readableStream = null;
    this._readCapability = (0, _util.createPromiseCapability)();
    const source = stream.source;
    this._isStreamingSupported = !source.disableStream;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    if (this._storedError) {
      throw this._storedError;
    }
    const chunk = this._readableStream.read();
    if (chunk === null) {
      this._readCapability = (0, _util.createPromiseCapability)();
      return this.read();
    }
    this._loaded += chunk.length;
    this.onProgress?.({
      loaded: this._loaded
    });
    const buffer = new Uint8Array(chunk).buffer;
    return {
      value: buffer,
      done: false
    };
  }
  cancel(reason) {
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }
  _error(reason) {
    this._storedError = reason;
    this._readCapability.resolve();
  }
  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on("readable", () => {
      this._readCapability.resolve();
    });
    readableStream.on("end", () => {
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });
    readableStream.on("error", reason => {
      this._error(reason);
    });
    if (this._storedError) {
      this._readableStream.destroy(this._storedError);
    }
  }
}
function createRequestOptions(parsedUrl, headers) {
  return {
    protocol: parsedUrl.protocol,
    auth: parsedUrl.auth,
    host: parsedUrl.hostname,
    port: parsedUrl.port,
    path: parsedUrl.path,
    method: "GET",
    headers
  };
}
class PDFNodeStreamFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);
    const handleResponse = response => {
      if (response.statusCode === 404) {
        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
        this._storedError = error;
        this._headersCapability.reject(error);
        return;
      }
      this._headersCapability.resolve();
      this._setReadableStream(response);
      const getResponseHeader = name => {
        return this._readableStream.headers[name.toLowerCase()];
      };
      const {
        allowRangeRequests,
        suggestedLength
      } = (0, _network_utils.validateRangeRequestCapabilities)({
        getResponseHeader,
        isHttp: stream.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange
      });
      this._isRangeSupported = allowRangeRequests;
      this._contentLength = suggestedLength || this._contentLength;
      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
    };
    this._request = null;
    if (this._url.protocol === "http:") {
      this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
    } else {
      this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
    }
    this._request.on("error", reason => {
      this._storedError = reason;
      this._headersCapability.reject(reason);
    });
    this._request.end();
  }
}
class PDFNodeStreamRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);
    this._httpHeaders = {};
    for (const property in stream.httpHeaders) {
      const value = stream.httpHeaders[property];
      if (value === undefined) {
        continue;
      }
      this._httpHeaders[property] = value;
    }
    this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
    const handleResponse = response => {
      if (response.statusCode === 404) {
        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
        this._storedError = error;
        return;
      }
      this._setReadableStream(response);
    };
    this._request = null;
    if (this._url.protocol === "http:") {
      this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
    } else {
      this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
    }
    this._request.on("error", reason => {
      this._storedError = reason;
    });
    this._request.end();
  }
}
class PDFNodeStreamFsFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);
    let path = decodeURIComponent(this._url.path);
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, "");
    }
    fs.lstat(path, (error, stat) => {
      if (error) {
        if (error.code === "ENOENT") {
          error = new _util.MissingPDFException(`Missing PDF "${path}".`);
        }
        this._storedError = error;
        this._headersCapability.reject(error);
        return;
      }
      this._contentLength = stat.size;
      this._setReadableStream(fs.createReadStream(path));
      this._headersCapability.resolve();
    });
  }
}
class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);
    let path = decodeURIComponent(this._url.path);
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, "");
    }
    this._setReadableStream(fs.createReadStream(path, {
      start,
      end: end - 1
    }));
  }
}

/***/ }),
/* 22 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.createResponseStatusError = createResponseStatusError;
exports.extractFilenameFromHeader = extractFilenameFromHeader;
exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
exports.validateResponseStatus = validateResponseStatus;
var _util = __w_pdfjs_require__(1);
var _content_disposition = __w_pdfjs_require__(23);
var _display_utils = __w_pdfjs_require__(6);
function validateRangeRequestCapabilities({
  getResponseHeader,
  isHttp,
  rangeChunkSize,
  disableRange
}) {
  const returnValues = {
    allowRangeRequests: false,
    suggestedLength: undefined
  };
  const length = parseInt(getResponseHeader("Content-Length"), 10);
  if (!Number.isInteger(length)) {
    return returnValues;
  }
  returnValues.suggestedLength = length;
  if (length <= 2 * rangeChunkSize) {
    return returnValues;
  }
  if (disableRange || !isHttp) {
    return returnValues;
  }
  if (getResponseHeader("Accept-Ranges") !== "bytes") {
    return returnValues;
  }
  const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
  if (contentEncoding !== "identity") {
    return returnValues;
  }
  returnValues.allowRangeRequests = true;
  return returnValues;
}
function extractFilenameFromHeader(getResponseHeader) {
  const contentDisposition = getResponseHeader("Content-Disposition");
  if (contentDisposition) {
    let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
    if (filename.includes("%")) {
      try {
        filename = decodeURIComponent(filename);
      } catch (ex) {}
    }
    if ((0, _display_utils.isPdfFile)(filename)) {
      return filename;
    }
  }
  return null;
}
function createResponseStatusError(status, url) {
  if (status === 404 || status === 0 && url.startsWith("file:")) {
    return new _util.MissingPDFException('Missing PDF "' + url + '".');
  }
  return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
}
function validateResponseStatus(status) {
  return status === 200 || status === 206;
}

/***/ }),
/* 23 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
var _util = __w_pdfjs_require__(1);
function getFilenameFromContentDispositionHeader(contentDisposition) {
  let needsEncodingFixup = true;
  let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
  if (tmp) {
    tmp = tmp[1];
    let filename = rfc2616unquote(tmp);
    filename = unescape(filename);
    filename = rfc5987decode(filename);
    filename = rfc2047decode(filename);
    return fixupEncoding(filename);
  }
  tmp = rfc2231getparam(contentDisposition);
  if (tmp) {
    const filename = rfc2047decode(tmp);
    return fixupEncoding(filename);
  }
  tmp = toParamRegExp("filename", "i").exec(contentDisposition);
  if (tmp) {
    tmp = tmp[1];
    let filename = rfc2616unquote(tmp);
    filename = rfc2047decode(filename);
    return fixupEncoding(filename);
  }
  function toParamRegExp(attributePattern, flags) {
    return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
  }
  function textdecode(encoding, value) {
    if (encoding) {
      if (!/^[\x00-\xFF]+$/.test(value)) {
        return value;
      }
      try {
        const decoder = new TextDecoder(encoding, {
          fatal: true
        });
        const buffer = (0, _util.stringToBytes)(value);
        value = decoder.decode(buffer);
        needsEncodingFixup = false;
      } catch (e) {}
    }
    return value;
  }
  function fixupEncoding(value) {
    if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
      value = textdecode("utf-8", value);
      if (needsEncodingFixup) {
        value = textdecode("iso-8859-1", value);
      }
    }
    return value;
  }
  function rfc2231getparam(contentDispositionStr) {
    const matches = [];
    let match;
    const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
    while ((match = iter.exec(contentDispositionStr)) !== null) {
      let [, n, quot, part] = match;
      n = parseInt(n, 10);
      if (n in matches) {
        if (n === 0) {
          break;
        }
        continue;
      }
      matches[n] = [quot, part];
    }
    const parts = [];
    for (let n = 0; n < matches.length; ++n) {
      if (!(n in matches)) {
        break;
      }
      let [quot, part] = matches[n];
      part = rfc2616unquote(part);
      if (quot) {
        part = unescape(part);
        if (n === 0) {
          part = rfc5987decode(part);
        }
      }
      parts.push(part);
    }
    return parts.join("");
  }
  function rfc2616unquote(value) {
    if (value.startsWith('"')) {
      const parts = value.slice(1).split('\\"');
      for (let i = 0; i < parts.length; ++i) {
        const quotindex = parts[i].indexOf('"');
        if (quotindex !== -1) {
          parts[i] = parts[i].slice(0, quotindex);
          parts.length = i + 1;
        }
        parts[i] = parts[i].replace(/\\(.)/g, "$1");
      }
      value = parts.join('"');
    }
    return value;
  }
  function rfc5987decode(extvalue) {
    const encodingend = extvalue.indexOf("'");
    if (encodingend === -1) {
      return extvalue;
    }
    const encoding = extvalue.slice(0, encodingend);
    const langvalue = extvalue.slice(encodingend + 1);
    const value = langvalue.replace(/^[^']*'/, "");
    return textdecode(encoding, value);
  }
  function rfc2047decode(value) {
    if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
      return value;
    }
    return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
      if (encoding === "q" || encoding === "Q") {
        text = text.replace(/_/g, " ");
        text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
          return String.fromCharCode(parseInt(hex, 16));
        });
        return textdecode(charset, text);
      }
      try {
        text = atob(text);
      } catch (e) {}
      return textdecode(charset, text);
    });
  }
  return "";
}

/***/ }),
/* 24 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFNetworkStream = void 0;
var _util = __w_pdfjs_require__(1);
var _network_utils = __w_pdfjs_require__(22);
;
const OK_RESPONSE = 200;
const PARTIAL_CONTENT_RESPONSE = 206;
function getArrayBuffer(xhr) {
  const data = xhr.response;
  if (typeof data !== "string") {
    return data;
  }
  return (0, _util.stringToBytes)(data).buffer;
}
class NetworkManager {
  constructor(url, args = {}) {
    this.url = url;
    this.isHttp = /^https?:/i.test(url);
    this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
    this.withCredentials = args.withCredentials || false;
    this.getXhr = args.getXhr || function NetworkManager_getXhr() {
      return new XMLHttpRequest();
    };
    this.currXhrId = 0;
    this.pendingRequests = Object.create(null);
  }
  requestRange(begin, end, listeners) {
    const args = {
      begin,
      end
    };
    for (const prop in listeners) {
      args[prop] = listeners[prop];
    }
    return this.request(args);
  }
  requestFull(listeners) {
    return this.request(listeners);
  }
  request(args) {
    const xhr = this.getXhr();
    const xhrId = this.currXhrId++;
    const pendingRequest = this.pendingRequests[xhrId] = {
      xhr
    };
    xhr.open("GET", this.url);
    xhr.withCredentials = this.withCredentials;
    for (const property in this.httpHeaders) {
      const value = this.httpHeaders[property];
      if (value === undefined) {
        continue;
      }
      xhr.setRequestHeader(property, value);
    }
    if (this.isHttp && "begin" in args && "end" in args) {
      xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
      pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
    } else {
      pendingRequest.expectedStatus = OK_RESPONSE;
    }
    xhr.responseType = "arraybuffer";
    if (args.onError) {
      xhr.onerror = function (evt) {
        args.onError(xhr.status);
      };
    }
    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
    xhr.onprogress = this.onProgress.bind(this, xhrId);
    pendingRequest.onHeadersReceived = args.onHeadersReceived;
    pendingRequest.onDone = args.onDone;
    pendingRequest.onError = args.onError;
    pendingRequest.onProgress = args.onProgress;
    xhr.send(null);
    return xhrId;
  }
  onProgress(xhrId, evt) {
    const pendingRequest = this.pendingRequests[xhrId];
    if (!pendingRequest) {
      return;
    }
    pendingRequest.onProgress?.(evt);
  }
  onStateChange(xhrId, evt) {
    const pendingRequest = this.pendingRequests[xhrId];
    if (!pendingRequest) {
      return;
    }
    const xhr = pendingRequest.xhr;
    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
      pendingRequest.onHeadersReceived();
      delete pendingRequest.onHeadersReceived;
    }
    if (xhr.readyState !== 4) {
      return;
    }
    if (!(xhrId in this.pendingRequests)) {
      return;
    }
    delete this.pendingRequests[xhrId];
    if (xhr.status === 0 && this.isHttp) {
      pendingRequest.onError?.(xhr.status);
      return;
    }
    const xhrStatus = xhr.status || OK_RESPONSE;
    const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
      pendingRequest.onError?.(xhr.status);
      return;
    }
    const chunk = getArrayBuffer(xhr);
    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
      const rangeHeader = xhr.getResponseHeader("Content-Range");
      const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
      pendingRequest.onDone({
        begin: parseInt(matches[1], 10),
        chunk
      });
    } else if (chunk) {
      pendingRequest.onDone({
        begin: 0,
        chunk
      });
    } else {
      pendingRequest.onError?.(xhr.status);
    }
  }
  getRequestXhr(xhrId) {
    return this.pendingRequests[xhrId].xhr;
  }
  isPendingRequest(xhrId) {
    return xhrId in this.pendingRequests;
  }
  abortRequest(xhrId) {
    const xhr = this.pendingRequests[xhrId].xhr;
    delete this.pendingRequests[xhrId];
    xhr.abort();
  }
}
class PDFNetworkStream {
  constructor(source) {
    this._source = source;
    this._manager = new NetworkManager(source.url, {
      httpHeaders: source.httpHeaders,
      withCredentials: source.withCredentials
    });
    this._rangeChunkSize = source.rangeChunkSize;
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  _onRangeRequestReaderClosed(reader) {
    const i = this._rangeRequestReaders.indexOf(reader);
    if (i >= 0) {
      this._rangeRequestReaders.splice(i, 1);
    }
  }
  getFullReader() {
    (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
    return this._fullRequestReader;
  }
  getRangeReader(begin, end) {
    const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
    this._rangeRequestReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
}
exports.PDFNetworkStream = PDFNetworkStream;
class PDFNetworkStreamFullRequestReader {
  constructor(manager, source) {
    this._manager = manager;
    const args = {
      onHeadersReceived: this._onHeadersReceived.bind(this),
      onDone: this._onDone.bind(this),
      onError: this._onError.bind(this),
      onProgress: this._onProgress.bind(this)
    };
    this._url = source.url;
    this._fullRequestId = manager.requestFull(args);
    this._headersReceivedCapability = (0, _util.createPromiseCapability)();
    this._disableRange = source.disableRange || false;
    this._contentLength = source.length;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._isStreamingSupported = false;
    this._isRangeSupported = false;
    this._cachedChunks = [];
    this._requests = [];
    this._done = false;
    this._storedError = undefined;
    this._filename = null;
    this.onProgress = null;
  }
  _onHeadersReceived() {
    const fullRequestXhrId = this._fullRequestId;
    const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
    const getResponseHeader = name => {
      return fullRequestXhr.getResponseHeader(name);
    };
    const {
      allowRangeRequests,
      suggestedLength
    } = (0, _network_utils.validateRangeRequestCapabilities)({
      getResponseHeader,
      isHttp: this._manager.isHttp,
      rangeChunkSize: this._rangeChunkSize,
      disableRange: this._disableRange
    });
    if (allowRangeRequests) {
      this._isRangeSupported = true;
    }
    this._contentLength = suggestedLength || this._contentLength;
    this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
    if (this._isRangeSupported) {
      this._manager.abortRequest(fullRequestXhrId);
    }
    this._headersReceivedCapability.resolve();
  }
  _onDone(data) {
    if (data) {
      if (this._requests.length > 0) {
        const requestCapability = this._requests.shift();
        requestCapability.resolve({
          value: data.chunk,
          done: false
        });
      } else {
        this._cachedChunks.push(data.chunk);
      }
    }
    this._done = true;
    if (this._cachedChunks.length > 0) {
      return;
    }
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
  }
  _onError(status) {
    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
    this._headersReceivedCapability.reject(this._storedError);
    for (const requestCapability of this._requests) {
      requestCapability.reject(this._storedError);
    }
    this._requests.length = 0;
    this._cachedChunks.length = 0;
  }
  _onProgress(evt) {
    this.onProgress?.({
      loaded: evt.loaded,
      total: evt.lengthComputable ? evt.total : this._contentLength
    });
  }
  get filename() {
    return this._filename;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  get contentLength() {
    return this._contentLength;
  }
  get headersReady() {
    return this._headersReceivedCapability.promise;
  }
  async read() {
    if (this._storedError) {
      throw this._storedError;
    }
    if (this._cachedChunks.length > 0) {
      const chunk = this._cachedChunks.shift();
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    const requestCapability = (0, _util.createPromiseCapability)();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    this._headersReceivedCapability.reject(reason);
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
    if (this._manager.isPendingRequest(this._fullRequestId)) {
      this._manager.abortRequest(this._fullRequestId);
    }
    this._fullRequestReader = null;
  }
}
class PDFNetworkStreamRangeRequestReader {
  constructor(manager, begin, end) {
    this._manager = manager;
    const args = {
      onDone: this._onDone.bind(this),
      onError: this._onError.bind(this),
      onProgress: this._onProgress.bind(this)
    };
    this._url = manager.url;
    this._requestId = manager.requestRange(begin, end, args);
    this._requests = [];
    this._queuedChunk = null;
    this._done = false;
    this._storedError = undefined;
    this.onProgress = null;
    this.onClosed = null;
  }
  _close() {
    this.onClosed?.(this);
  }
  _onDone(data) {
    const chunk = data.chunk;
    if (this._requests.length > 0) {
      const requestCapability = this._requests.shift();
      requestCapability.resolve({
        value: chunk,
        done: false
      });
    } else {
      this._queuedChunk = chunk;
    }
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
    this._close();
  }
  _onError(status) {
    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
    for (const requestCapability of this._requests) {
      requestCapability.reject(this._storedError);
    }
    this._requests.length = 0;
    this._queuedChunk = null;
  }
  _onProgress(evt) {
    if (!this.isStreamingSupported) {
      this.onProgress?.({
        loaded: evt.loaded
      });
    }
  }
  get isStreamingSupported() {
    return false;
  }
  async read() {
    if (this._storedError) {
      throw this._storedError;
    }
    if (this._queuedChunk !== null) {
      const chunk = this._queuedChunk;
      this._queuedChunk = null;
      return {
        value: chunk,
        done: false
      };
    }
    if (this._done) {
      return {
        value: undefined,
        done: true
      };
    }
    const requestCapability = (0, _util.createPromiseCapability)();
    this._requests.push(requestCapability);
    return requestCapability.promise;
  }
  cancel(reason) {
    this._done = true;
    for (const requestCapability of this._requests) {
      requestCapability.resolve({
        value: undefined,
        done: true
      });
    }
    this._requests.length = 0;
    if (this._manager.isPendingRequest(this._requestId)) {
      this._manager.abortRequest(this._requestId);
    }
    this._close();
  }
}

/***/ }),
/* 25 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFFetchStream = void 0;
var _util = __w_pdfjs_require__(1);
var _network_utils = __w_pdfjs_require__(22);
;
function createFetchOptions(headers, withCredentials, abortController) {
  return {
    method: "GET",
    headers,
    signal: abortController.signal,
    mode: "cors",
    credentials: withCredentials ? "include" : "same-origin",
    redirect: "follow"
  };
}
function createHeaders(httpHeaders) {
  const headers = new Headers();
  for (const property in httpHeaders) {
    const value = httpHeaders[property];
    if (value === undefined) {
      continue;
    }
    headers.append(property, value);
  }
  return headers;
}
function getArrayBuffer(val) {
  if (val instanceof Uint8Array) {
    return val.buffer;
  }
  if (val instanceof ArrayBuffer) {
    return val;
  }
  (0, _util.warn)(`getArrayBuffer - unexpected data format: ${val}`);
  return new Uint8Array(val).buffer;
}
class PDFFetchStream {
  constructor(source) {
    this.source = source;
    this.isHttp = /^https?:/i.test(source.url);
    this.httpHeaders = this.isHttp && source.httpHeaders || {};
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  get _progressiveDataLength() {
    return this._fullRequestReader?._loaded ?? 0;
  }
  getFullReader() {
    (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFFetchStreamReader(this);
    return this._fullRequestReader;
  }
  getRangeReader(begin, end) {
    if (end <= this._progressiveDataLength) {
      return null;
    }
    const reader = new PDFFetchStreamRangeReader(this, begin, end);
    this._rangeRequestReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    this._fullRequestReader?.cancel(reason);
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
}
exports.PDFFetchStream = PDFFetchStream;
class PDFFetchStreamReader {
  constructor(stream) {
    this._stream = stream;
    this._reader = null;
    this._loaded = 0;
    this._filename = null;
    const source = stream.source;
    this._withCredentials = source.withCredentials || false;
    this._contentLength = source.length;
    this._headersCapability = (0, _util.createPromiseCapability)();
    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }
    this._abortController = new AbortController();
    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;
    this._headers = createHeaders(this._stream.httpHeaders);
    const url = source.url;
    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
        throw (0, _network_utils.createResponseStatusError)(response.status, url);
      }
      this._reader = response.body.getReader();
      this._headersCapability.resolve();
      const getResponseHeader = name => {
        return response.headers.get(name);
      };
      const {
        allowRangeRequests,
        suggestedLength
      } = (0, _network_utils.validateRangeRequestCapabilities)({
        getResponseHeader,
        isHttp: this._stream.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange
      });
      this._isRangeSupported = allowRangeRequests;
      this._contentLength = suggestedLength || this._contentLength;
      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
      if (!this._isStreamingSupported && this._isRangeSupported) {
        this.cancel(new _util.AbortException("Streaming is disabled."));
      }
    }).catch(this._headersCapability.reject);
    this.onProgress = null;
  }
  get headersReady() {
    return this._headersCapability.promise;
  }
  get filename() {
    return this._filename;
  }
  get contentLength() {
    return this._contentLength;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._headersCapability.promise;
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value,
        done
      };
    }
    this._loaded += value.byteLength;
    this.onProgress?.({
      loaded: this._loaded,
      total: this._contentLength
    });
    return {
      value: getArrayBuffer(value),
      done: false
    };
  }
  cancel(reason) {
    this._reader?.cancel(reason);
    this._abortController.abort();
  }
}
class PDFFetchStreamRangeReader {
  constructor(stream, begin, end) {
    this._stream = stream;
    this._reader = null;
    this._loaded = 0;
    const source = stream.source;
    this._withCredentials = source.withCredentials || false;
    this._readCapability = (0, _util.createPromiseCapability)();
    this._isStreamingSupported = !source.disableStream;
    this._abortController = new AbortController();
    this._headers = createHeaders(this._stream.httpHeaders);
    this._headers.append("Range", `bytes=${begin}-${end - 1}`);
    const url = source.url;
    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
        throw (0, _network_utils.createResponseStatusError)(response.status, url);
      }
      this._readCapability.resolve();
      this._reader = response.body.getReader();
    }).catch(this._readCapability.reject);
    this.onProgress = null;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  async read() {
    await this._readCapability.promise;
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value,
        done
      };
    }
    this._loaded += value.byteLength;
    this.onProgress?.({
      loaded: this._loaded
    });
    return {
      value: getArrayBuffer(value),
      done: false
    };
  }
  cancel(reason) {
    this._reader?.cancel(reason);
    this._abortController.abort();
  }
}

/***/ }),
/* 26 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.TextLayerRenderTask = void 0;
exports.renderTextLayer = renderTextLayer;
exports.updateTextLayer = updateTextLayer;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
const MAX_TEXT_DIVS_TO_RENDER = 100000;
const DEFAULT_FONT_SIZE = 30;
const DEFAULT_FONT_ASCENT = 0.8;
const ascentCache = new Map();
function getCtx(size, isOffscreenCanvasSupported) {
  let ctx;
  if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
    ctx = new OffscreenCanvas(size, size).getContext("2d", {
      alpha: false
    });
  } else {
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = size;
    ctx = canvas.getContext("2d", {
      alpha: false
    });
  }
  return ctx;
}
function getAscent(fontFamily, isOffscreenCanvasSupported) {
  const cachedAscent = ascentCache.get(fontFamily);
  if (cachedAscent) {
    return cachedAscent;
  }
  const ctx = getCtx(DEFAULT_FONT_SIZE, isOffscreenCanvasSupported);
  ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
  const metrics = ctx.measureText("");
  let ascent = metrics.fontBoundingBoxAscent;
  let descent = Math.abs(metrics.fontBoundingBoxDescent);
  if (ascent) {
    const ratio = ascent / (ascent + descent);
    ascentCache.set(fontFamily, ratio);
    ctx.canvas.width = ctx.canvas.height = 0;
    return ratio;
  }
  ctx.strokeStyle = "red";
  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  ctx.strokeText("g", 0, 0);
  let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  descent = 0;
  for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
    if (pixels[i] > 0) {
      descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
      break;
    }
  }
  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
  ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
  pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
  ascent = 0;
  for (let i = 0, ii = pixels.length; i < ii; i += 4) {
    if (pixels[i] > 0) {
      ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
      break;
    }
  }
  ctx.canvas.width = ctx.canvas.height = 0;
  if (ascent) {
    const ratio = ascent / (ascent + descent);
    ascentCache.set(fontFamily, ratio);
    return ratio;
  }
  ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
  return DEFAULT_FONT_ASCENT;
}
function appendText(task, geom, styles) {
  const textDiv = document.createElement("span");
  const textDivProperties = {
    angle: 0,
    canvasWidth: 0,
    hasText: geom.str !== "",
    hasEOL: geom.hasEOL,
    fontSize: 0
  };
  task._textDivs.push(textDiv);
  const tx = _util.Util.transform(task._transform, geom.transform);
  let angle = Math.atan2(tx[1], tx[0]);
  const style = styles[geom.fontName];
  if (style.vertical) {
    angle += Math.PI / 2;
  }
  const fontHeight = Math.hypot(tx[2], tx[3]);
  const fontAscent = fontHeight * getAscent(style.fontFamily, task._isOffscreenCanvasSupported);
  let left, top;
  if (angle === 0) {
    left = tx[4];
    top = tx[5] - fontAscent;
  } else {
    left = tx[4] + fontAscent * Math.sin(angle);
    top = tx[5] - fontAscent * Math.cos(angle);
  }
  const scaleFactorStr = "calc(var(--scale-factor)*";
  const divStyle = textDiv.style;
  if (task._container === task._rootContainer) {
    divStyle.left = `${(100 * left / task._pageWidth).toFixed(2)}%`;
    divStyle.top = `${(100 * top / task._pageHeight).toFixed(2)}%`;
  } else {
    divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`;
    divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`;
  }
  divStyle.fontSize = `${scaleFactorStr}${fontHeight.toFixed(2)}px)`;
  divStyle.fontFamily = style.fontFamily;
  textDivProperties.fontSize = fontHeight;
  textDiv.setAttribute("role", "presentation");
  textDiv.textContent = geom.str;
  textDiv.dir = geom.dir;
  if (task._fontInspectorEnabled) {
    textDiv.dataset.fontName = geom.fontName;
  }
  if (angle !== 0) {
    textDivProperties.angle = angle * (180 / Math.PI);
  }
  let shouldScaleText = false;
  if (geom.str.length > 1) {
    shouldScaleText = true;
  } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
    const absScaleX = Math.abs(geom.transform[0]),
      absScaleY = Math.abs(geom.transform[3]);
    if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
      shouldScaleText = true;
    }
  }
  if (shouldScaleText) {
    textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
  }
  task._textDivProperties.set(textDiv, textDivProperties);
  if (task._isReadableStream) {
    task._layoutText(textDiv);
  }
}
function layout(params) {
  const {
    div,
    scale,
    properties,
    ctx,
    prevFontSize,
    prevFontFamily
  } = params;
  const {
    style
  } = div;
  let transform = "";
  if (properties.canvasWidth !== 0 && properties.hasText) {
    const {
      fontFamily
    } = style;
    const {
      canvasWidth,
      fontSize
    } = properties;
    if (prevFontSize !== fontSize || prevFontFamily !== fontFamily) {
      ctx.font = `${fontSize * scale}px ${fontFamily}`;
      params.prevFontSize = fontSize;
      params.prevFontFamily = fontFamily;
    }
    const {
      width
    } = ctx.measureText(div.textContent);
    if (width > 0) {
      transform = `scaleX(${canvasWidth * scale / width})`;
    }
  }
  if (properties.angle !== 0) {
    transform = `rotate(${properties.angle}deg) ${transform}`;
  }
  if (transform.length > 0) {
    style.transform = transform;
  }
}
function render(task) {
  if (task._canceled) {
    return;
  }
  const textDivs = task._textDivs;
  const capability = task._capability;
  const textDivsLength = textDivs.length;
  if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
    capability.resolve();
    return;
  }
  if (!task._isReadableStream) {
    for (const textDiv of textDivs) {
      task._layoutText(textDiv);
    }
  }
  capability.resolve();
}
class TextLayerRenderTask {
  constructor({
    textContentSource,
    container,
    viewport,
    textDivs,
    textDivProperties,
    textContentItemsStr,
    isOffscreenCanvasSupported
  }) {
    this._textContentSource = textContentSource;
    this._isReadableStream = textContentSource instanceof ReadableStream;
    this._container = this._rootContainer = container;
    this._textDivs = textDivs || [];
    this._textContentItemsStr = textContentItemsStr || [];
    this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
    this._reader = null;
    this._textDivProperties = textDivProperties || new WeakMap();
    this._canceled = false;
    this._capability = (0, _util.createPromiseCapability)();
    this._layoutTextParams = {
      prevFontSize: null,
      prevFontFamily: null,
      div: null,
      scale: viewport.scale * (globalThis.devicePixelRatio || 1),
      properties: null,
      ctx: getCtx(0, isOffscreenCanvasSupported)
    };
    const {
      pageWidth,
      pageHeight,
      pageX,
      pageY
    } = viewport.rawDims;
    this._transform = [1, 0, 0, -1, -pageX, pageY + pageHeight];
    this._pageWidth = pageWidth;
    this._pageHeight = pageHeight;
    (0, _display_utils.setLayerDimensions)(container, viewport);
    this._capability.promise.finally(() => {
      this._layoutTextParams = null;
    }).catch(() => {});
  }
  get promise() {
    return this._capability.promise;
  }
  cancel() {
    this._canceled = true;
    if (this._reader) {
      this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
      this._reader = null;
    }
    this._capability.reject(new _util.AbortException("TextLayer task cancelled."));
  }
  _processItems(items, styleCache) {
    for (const item of items) {
      if (item.str === undefined) {
        if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") {
          const parent = this._container;
          this._container = document.createElement("span");
          this._container.classList.add("markedContent");
          if (item.id !== null) {
            this._container.setAttribute("id", `${item.id}`);
          }
          parent.append(this._container);
        } else if (item.type === "endMarkedContent") {
          this._container = this._container.parentNode;
        }
        continue;
      }
      this._textContentItemsStr.push(item.str);
      appendText(this, item, styleCache);
    }
  }
  _layoutText(textDiv) {
    const textDivProperties = this._layoutTextParams.properties = this._textDivProperties.get(textDiv);
    this._layoutTextParams.div = textDiv;
    layout(this._layoutTextParams);
    if (textDivProperties.hasText) {
      this._container.append(textDiv);
    }
    if (textDivProperties.hasEOL) {
      const br = document.createElement("br");
      br.setAttribute("role", "presentation");
      this._container.append(br);
    }
  }
  _render() {
    const capability = (0, _util.createPromiseCapability)();
    let styleCache = Object.create(null);
    if (this._isReadableStream) {
      const pump = () => {
        this._reader.read().then(({
          value,
          done
        }) => {
          if (done) {
            capability.resolve();
            return;
          }
          Object.assign(styleCache, value.styles);
          this._processItems(value.items, styleCache);
          pump();
        }, capability.reject);
      };
      this._reader = this._textContentSource.getReader();
      pump();
    } else if (this._textContentSource) {
      const {
        items,
        styles
      } = this._textContentSource;
      this._processItems(items, styles);
      capability.resolve();
    } else {
      throw new Error('No "textContentSource" parameter specified.');
    }
    capability.promise.then(() => {
      styleCache = null;
      render(this);
    }, this._capability.reject);
  }
}
exports.TextLayerRenderTask = TextLayerRenderTask;
function renderTextLayer(params) {
  if (!params.textContentSource && (params.textContent || params.textContentStream)) {
    (0, _display_utils.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters " + "will be removed in the future, please use `textContentSource` instead.");
    params.textContentSource = params.textContent || params.textContentStream;
  }
  const task = new TextLayerRenderTask(params);
  task._render();
  return task;
}
function updateTextLayer({
  container,
  viewport,
  textDivs,
  textDivProperties,
  isOffscreenCanvasSupported,
  mustRotate = true,
  mustRescale = true
}) {
  if (mustRotate) {
    (0, _display_utils.setLayerDimensions)(container, {
      rotation: viewport.rotation
    });
  }
  if (mustRescale) {
    const ctx = getCtx(0, isOffscreenCanvasSupported);
    const scale = viewport.scale * (globalThis.devicePixelRatio || 1);
    const params = {
      prevFontSize: null,
      prevFontFamily: null,
      div: null,
      scale,
      properties: null,
      ctx
    };
    for (const div of textDivs) {
      params.properties = textDivProperties.get(div);
      params.div = div;
      layout(params);
    }
  }
}

/***/ }),
/* 27 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.AnnotationEditorLayer = void 0;
var _util = __w_pdfjs_require__(1);
var _tools = __w_pdfjs_require__(5);
var _freetext = __w_pdfjs_require__(28);
var _ink = __w_pdfjs_require__(29);
var _display_utils = __w_pdfjs_require__(6);
class AnnotationEditorLayer {
  #accessibilityManager;
  #allowClick = false;
  #boundPointerup = this.pointerup.bind(this);
  #boundPointerdown = this.pointerdown.bind(this);
  #editors = new Map();
  #hadPointerDown = false;
  #isCleaningUp = false;
  #uiManager;
  static _initialized = false;
  constructor(options) {
    if (!AnnotationEditorLayer._initialized) {
      AnnotationEditorLayer._initialized = true;
      _freetext.FreeTextEditor.initialize(options.l10n);
      _ink.InkEditor.initialize(options.l10n);
    }
    options.uiManager.registerEditorTypes([_freetext.FreeTextEditor, _ink.InkEditor]);
    this.#uiManager = options.uiManager;
    this.pageIndex = options.pageIndex;
    this.div = options.div;
    this.#accessibilityManager = options.accessibilityManager;
    this.#uiManager.addLayer(this);
  }
  get isEmpty() {
    return this.#editors.size === 0;
  }
  updateToolbar(mode) {
    this.#uiManager.updateToolbar(mode);
  }
  updateMode(mode = this.#uiManager.getMode()) {
    this.#cleanup();
    if (mode === _util.AnnotationEditorType.INK) {
      this.addInkEditorIfNeeded(false);
      this.disableClick();
    } else {
      this.enableClick();
    }
    this.#uiManager.unselectAll();
    if (mode !== _util.AnnotationEditorType.NONE) {
      this.div.classList.toggle("freeTextEditing", mode === _util.AnnotationEditorType.FREETEXT);
      this.div.classList.toggle("inkEditing", mode === _util.AnnotationEditorType.INK);
      this.div.hidden = false;
    }
  }
  addInkEditorIfNeeded(isCommitting) {
    if (!isCommitting && this.#uiManager.getMode() !== _util.AnnotationEditorType.INK) {
      return;
    }
    if (!isCommitting) {
      for (const editor of this.#editors.values()) {
        if (editor.isEmpty()) {
          editor.setInBackground();
          return;
        }
      }
    }
    const editor = this.#createAndAddNewEditor({
      offsetX: 0,
      offsetY: 0
    });
    editor.setInBackground();
  }
  setEditingState(isEditing) {
    this.#uiManager.setEditingState(isEditing);
  }
  addCommands(params) {
    this.#uiManager.addCommands(params);
  }
  enable() {
    this.div.style.pointerEvents = "auto";
    for (const editor of this.#editors.values()) {
      editor.enableEditing();
    }
  }
  disable() {
    this.div.style.pointerEvents = "none";
    for (const editor of this.#editors.values()) {
      editor.disableEditing();
    }
    this.#cleanup();
    if (this.isEmpty) {
      this.div.hidden = true;
    }
  }
  setActiveEditor(editor) {
    const currentActive = this.#uiManager.getActive();
    if (currentActive === editor) {
      return;
    }
    this.#uiManager.setActiveEditor(editor);
  }
  enableClick() {
    this.div.addEventListener("pointerdown", this.#boundPointerdown);
    this.div.addEventListener("pointerup", this.#boundPointerup);
  }
  disableClick() {
    this.div.removeEventListener("pointerdown", this.#boundPointerdown);
    this.div.removeEventListener("pointerup", this.#boundPointerup);
  }
  attach(editor) {
    this.#editors.set(editor.id, editor);
  }
  detach(editor) {
    this.#editors.delete(editor.id);
    this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
  }
  remove(editor) {
    this.#uiManager.removeEditor(editor);
    this.detach(editor);
    editor.div.style.display = "none";
    setTimeout(() => {
      editor.div.style.display = "";
      editor.div.remove();
      editor.isAttachedToDOM = false;
      if (document.activeElement === document.body) {
        this.#uiManager.focusMainContainer();
      }
    }, 0);
    if (!this.#isCleaningUp) {
      this.addInkEditorIfNeeded(false);
    }
  }
  #changeParent(editor) {
    if (editor.parent === this) {
      return;
    }
    this.attach(editor);
    editor.parent?.detach(editor);
    editor.setParent(this);
    if (editor.div && editor.isAttachedToDOM) {
      editor.div.remove();
      this.div.append(editor.div);
    }
  }
  add(editor) {
    this.#changeParent(editor);
    this.#uiManager.addEditor(editor);
    this.attach(editor);
    if (!editor.isAttachedToDOM) {
      const div = editor.render();
      this.div.append(div);
      editor.isAttachedToDOM = true;
    }
    this.moveEditorInDOM(editor);
    editor.onceAdded();
    this.#uiManager.addToAnnotationStorage(editor);
  }
  moveEditorInDOM(editor) {
    this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true);
  }
  addOrRebuild(editor) {
    if (editor.needsToBeRebuilt()) {
      editor.rebuild();
    } else {
      this.add(editor);
    }
  }
  addANewEditor(editor) {
    const cmd = () => {
      this.addOrRebuild(editor);
    };
    const undo = () => {
      editor.remove();
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: true
    });
  }
  addUndoableEditor(editor) {
    const cmd = () => {
      this.addOrRebuild(editor);
    };
    const undo = () => {
      editor.remove();
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: false
    });
  }
  getNextId() {
    return this.#uiManager.getId();
  }
  #createNewEditor(params) {
    switch (this.#uiManager.getMode()) {
      case _util.AnnotationEditorType.FREETEXT:
        return new _freetext.FreeTextEditor(params);
      case _util.AnnotationEditorType.INK:
        return new _ink.InkEditor(params);
    }
    return null;
  }
  deserialize(data) {
    switch (data.annotationType) {
      case _util.AnnotationEditorType.FREETEXT:
        return _freetext.FreeTextEditor.deserialize(data, this, this.#uiManager);
      case _util.AnnotationEditorType.INK:
        return _ink.InkEditor.deserialize(data, this, this.#uiManager);
    }
    return null;
  }
  #createAndAddNewEditor(event) {
    const id = this.getNextId();
    const editor = this.#createNewEditor({
      parent: this,
      id,
      x: event.offsetX,
      y: event.offsetY,
      uiManager: this.#uiManager
    });
    if (editor) {
      this.add(editor);
    }
    return editor;
  }
  setSelected(editor) {
    this.#uiManager.setSelected(editor);
  }
  toggleSelected(editor) {
    this.#uiManager.toggleSelected(editor);
  }
  isSelected(editor) {
    return this.#uiManager.isSelected(editor);
  }
  unselect(editor) {
    this.#uiManager.unselect(editor);
  }
  pointerup(event) {
    const {
      isMac
    } = _util.FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      return;
    }
    if (event.target !== this.div) {
      return;
    }
    if (!this.#hadPointerDown) {
      return;
    }
    this.#hadPointerDown = false;
    if (!this.#allowClick) {
      this.#allowClick = true;
      return;
    }
    this.#createAndAddNewEditor(event);
  }
  pointerdown(event) {
    const {
      isMac
    } = _util.FeatureTest.platform;
    if (event.button !== 0 || event.ctrlKey && isMac) {
      return;
    }
    if (event.target !== this.div) {
      return;
    }
    this.#hadPointerDown = true;
    const editor = this.#uiManager.getActive();
    this.#allowClick = !editor || editor.isEmpty();
  }
  drop(event) {
    const id = event.dataTransfer.getData("text/plain");
    const editor = this.#uiManager.getEditor(id);
    if (!editor) {
      return;
    }
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";
    this.#changeParent(editor);
    const rect = this.div.getBoundingClientRect();
    const endX = event.clientX - rect.x;
    const endY = event.clientY - rect.y;
    editor.translate(endX - editor.startX, endY - editor.startY);
    this.moveEditorInDOM(editor);
    editor.div.focus();
  }
  dragover(event) {
    event.preventDefault();
  }
  destroy() {
    if (this.#uiManager.getActive()?.parent === this) {
      this.#uiManager.setActiveEditor(null);
    }
    for (const editor of this.#editors.values()) {
      this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv);
      editor.setParent(null);
      editor.isAttachedToDOM = false;
      editor.div.remove();
    }
    this.div = null;
    this.#editors.clear();
    this.#uiManager.removeLayer(this);
  }
  #cleanup() {
    this.#isCleaningUp = true;
    for (const editor of this.#editors.values()) {
      if (editor.isEmpty()) {
        editor.remove();
      }
    }
    this.#isCleaningUp = false;
  }
  render({
    viewport
  }) {
    this.viewport = viewport;
    (0, _display_utils.setLayerDimensions)(this.div, viewport);
    (0, _tools.bindEvents)(this, this.div, ["dragover", "drop"]);
    for (const editor of this.#uiManager.getEditors(this.pageIndex)) {
      this.add(editor);
    }
    this.updateMode();
  }
  update({
    viewport
  }) {
    this.#uiManager.commitOrRemove();
    this.viewport = viewport;
    (0, _display_utils.setLayerDimensions)(this.div, {
      rotation: viewport.rotation
    });
    this.updateMode();
  }
  get pageDimensions() {
    const {
      pageWidth,
      pageHeight
    } = this.viewport.rawDims;
    return [pageWidth, pageHeight];
  }
}
exports.AnnotationEditorLayer = AnnotationEditorLayer;

/***/ }),
/* 28 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FreeTextEditor = void 0;
var _util = __w_pdfjs_require__(1);
var _tools = __w_pdfjs_require__(5);
var _editor = __w_pdfjs_require__(4);
class FreeTextEditor extends _editor.AnnotationEditor {
  #boundEditorDivBlur = this.editorDivBlur.bind(this);
  #boundEditorDivFocus = this.editorDivFocus.bind(this);
  #boundEditorDivInput = this.editorDivInput.bind(this);
  #boundEditorDivKeydown = this.editorDivKeydown.bind(this);
  #color;
  #content = "";
  #editorDivId = `${this.id}-editor`;
  #hasAlreadyBeenCommitted = false;
  #fontSize;
  static _freeTextDefaultContent = "";
  static _l10nPromise;
  static _internalPadding = 0;
  static _defaultColor = null;
  static _defaultFontSize = 10;
  static _keyboardManager = new _tools.KeyboardManager([[["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], FreeTextEditor.prototype.commitOrRemove]]);
  static _type = "freetext";
  constructor(params) {
    super({
      ...params,
      name: "freeTextEditor"
    });
    this.#color = params.color || FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
    this.#fontSize = params.fontSize || FreeTextEditor._defaultFontSize;
  }
  static initialize(l10n) {
    this._l10nPromise = new Map(["free_text2_default_content", "editor_free_text2_aria_label"].map(str => [str, l10n.get(str)]));
    const style = getComputedStyle(document.documentElement);
    this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding"));
  }
  static updateDefaultParams(type, value) {
    switch (type) {
      case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
        FreeTextEditor._defaultFontSize = value;
        break;
      case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
        FreeTextEditor._defaultColor = value;
        break;
    }
  }
  updateParams(type, value) {
    switch (type) {
      case _util.AnnotationEditorParamsType.FREETEXT_SIZE:
        this.#updateFontSize(value);
        break;
      case _util.AnnotationEditorParamsType.FREETEXT_COLOR:
        this.#updateColor(value);
        break;
    }
  }
  static get defaultPropertiesToUpdate() {
    return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, FreeTextEditor._defaultFontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, FreeTextEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor]];
  }
  get propertiesToUpdate() {
    return [[_util.AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [_util.AnnotationEditorParamsType.FREETEXT_COLOR, this.#color]];
  }
  #updateFontSize(fontSize) {
    const setFontsize = size => {
      this.editorDiv.style.fontSize = `calc(${size}px * var(--scale-factor))`;
      this.translate(0, -(size - this.#fontSize) * this.parentScale);
      this.#fontSize = size;
      this.#setEditorDimensions();
    };
    const savedFontsize = this.#fontSize;
    this.addCommands({
      cmd: () => {
        setFontsize(fontSize);
      },
      undo: () => {
        setFontsize(savedFontsize);
      },
      mustExec: true,
      type: _util.AnnotationEditorParamsType.FREETEXT_SIZE,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  #updateColor(color) {
    const savedColor = this.#color;
    this.addCommands({
      cmd: () => {
        this.#color = this.editorDiv.style.color = color;
      },
      undo: () => {
        this.#color = this.editorDiv.style.color = savedColor;
      },
      mustExec: true,
      type: _util.AnnotationEditorParamsType.FREETEXT_COLOR,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  getInitialTranslation() {
    const scale = this.parentScale;
    return [-FreeTextEditor._internalPadding * scale, -(FreeTextEditor._internalPadding + this.#fontSize) * scale];
  }
  rebuild() {
    super.rebuild();
    if (this.div === null) {
      return;
    }
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
    }
  }
  enableEditMode() {
    if (this.isInEditMode()) {
      return;
    }
    this.parent.setEditingState(false);
    this.parent.updateToolbar(_util.AnnotationEditorType.FREETEXT);
    super.enableEditMode();
    this.overlayDiv.classList.remove("enabled");
    this.editorDiv.contentEditable = true;
    this.div.draggable = false;
    this.div.removeAttribute("aria-activedescendant");
    this.editorDiv.addEventListener("keydown", this.#boundEditorDivKeydown);
    this.editorDiv.addEventListener("focus", this.#boundEditorDivFocus);
    this.editorDiv.addEventListener("blur", this.#boundEditorDivBlur);
    this.editorDiv.addEventListener("input", this.#boundEditorDivInput);
  }
  disableEditMode() {
    if (!this.isInEditMode()) {
      return;
    }
    this.parent.setEditingState(true);
    super.disableEditMode();
    this.overlayDiv.classList.add("enabled");
    this.editorDiv.contentEditable = false;
    this.div.setAttribute("aria-activedescendant", this.#editorDivId);
    this.div.draggable = true;
    this.editorDiv.removeEventListener("keydown", this.#boundEditorDivKeydown);
    this.editorDiv.removeEventListener("focus", this.#boundEditorDivFocus);
    this.editorDiv.removeEventListener("blur", this.#boundEditorDivBlur);
    this.editorDiv.removeEventListener("input", this.#boundEditorDivInput);
    this.div.focus({
      preventScroll: true
    });
    this.isEditing = false;
    this.parent.div.classList.add("freeTextEditing");
  }
  focusin(event) {
    super.focusin(event);
    if (event.target !== this.editorDiv) {
      this.editorDiv.focus();
    }
  }
  onceAdded() {
    if (this.width) {
      return;
    }
    this.enableEditMode();
    this.editorDiv.focus();
  }
  isEmpty() {
    return !this.editorDiv || this.editorDiv.innerText.trim() === "";
  }
  remove() {
    this.isEditing = false;
    this.parent.setEditingState(true);
    this.parent.div.classList.add("freeTextEditing");
    super.remove();
  }
  #extractText() {
    const divs = this.editorDiv.getElementsByTagName("div");
    if (divs.length === 0) {
      return this.editorDiv.innerText;
    }
    const buffer = [];
    for (const div of divs) {
      buffer.push(div.innerText.replace(/\r\n?|\n/, ""));
    }
    return buffer.join("\n");
  }
  #setEditorDimensions() {
    const [parentWidth, parentHeight] = this.parentDimensions;
    let rect;
    if (this.isAttachedToDOM) {
      rect = this.div.getBoundingClientRect();
    } else {
      const {
        currentLayer,
        div
      } = this;
      const savedDisplay = div.style.display;
      div.style.display = "hidden";
      currentLayer.div.append(this.div);
      rect = div.getBoundingClientRect();
      div.remove();
      div.style.display = savedDisplay;
    }
    this.width = rect.width / parentWidth;
    this.height = rect.height / parentHeight;
  }
  commit() {
    if (!this.isInEditMode()) {
      return;
    }
    super.commit();
    if (!this.#hasAlreadyBeenCommitted) {
      this.#hasAlreadyBeenCommitted = true;
      this.parent.addUndoableEditor(this);
    }
    this.disableEditMode();
    this.#content = this.#extractText().trimEnd();
    this.#setEditorDimensions();
  }
  shouldGetKeyboardEvents() {
    return this.isInEditMode();
  }
  dblclick(event) {
    this.enableEditMode();
    this.editorDiv.focus();
  }
  keydown(event) {
    if (event.target === this.div && event.key === "Enter") {
      this.enableEditMode();
      this.editorDiv.focus();
    }
  }
  editorDivKeydown(event) {
    FreeTextEditor._keyboardManager.exec(this, event);
  }
  editorDivFocus(event) {
    this.isEditing = true;
  }
  editorDivBlur(event) {
    this.isEditing = false;
  }
  editorDivInput(event) {
    this.parent.div.classList.toggle("freeTextEditing", this.isEmpty());
  }
  disableEditing() {
    this.editorDiv.setAttribute("role", "comment");
    this.editorDiv.removeAttribute("aria-multiline");
  }
  enableEditing() {
    this.editorDiv.setAttribute("role", "textbox");
    this.editorDiv.setAttribute("aria-multiline", true);
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    if (this.width) {
      baseX = this.x;
      baseY = this.y;
    }
    super.render();
    this.editorDiv = document.createElement("div");
    this.editorDiv.className = "internal";
    this.editorDiv.setAttribute("id", this.#editorDivId);
    this.enableEditing();
    FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then(msg => this.editorDiv?.setAttribute("aria-label", msg));
    FreeTextEditor._l10nPromise.get("free_text2_default_content").then(msg => this.editorDiv?.setAttribute("default-content", msg));
    this.editorDiv.contentEditable = true;
    const {
      style
    } = this.editorDiv;
    style.fontSize = `calc(${this.#fontSize}px * var(--scale-factor))`;
    style.color = this.#color;
    this.div.append(this.editorDiv);
    this.overlayDiv = document.createElement("div");
    this.overlayDiv.classList.add("overlay", "enabled");
    this.div.append(this.overlayDiv);
    (0, _tools.bindEvents)(this, this.div, ["dblclick", "keydown"]);
    if (this.width) {
      const [parentWidth, parentHeight] = this.parentDimensions;
      this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
      for (const line of this.#content.split("\n")) {
        const div = document.createElement("div");
        div.append(line ? document.createTextNode(line) : document.createElement("br"));
        this.editorDiv.append(div);
      }
      this.div.draggable = true;
      this.editorDiv.contentEditable = false;
    } else {
      this.div.draggable = false;
      this.editorDiv.contentEditable = true;
    }
    return this.div;
  }
  get contentDiv() {
    return this.editorDiv;
  }
  static deserialize(data, parent, uiManager) {
    const editor = super.deserialize(data, parent, uiManager);
    editor.#fontSize = data.fontSize;
    editor.#color = _util.Util.makeHexColor(...data.color);
    editor.#content = data.value;
    return editor;
  }
  serialize() {
    if (this.isEmpty()) {
      return null;
    }
    const padding = FreeTextEditor._internalPadding * this.parentScale;
    const rect = this.getRect(padding, padding);
    const color = _editor.AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.#color);
    return {
      annotationType: _util.AnnotationEditorType.FREETEXT,
      color,
      fontSize: this.#fontSize,
      value: this.#content,
      pageIndex: this.pageIndex,
      rect,
      rotation: this.rotation
    };
  }
}
exports.FreeTextEditor = FreeTextEditor;

/***/ }),
/* 29 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.InkEditor = void 0;
Object.defineProperty(exports, "fitCurve", ({
  enumerable: true,
  get: function () {
    return _pdfjsFitCurve.fitCurve;
  }
}));
var _util = __w_pdfjs_require__(1);
var _editor = __w_pdfjs_require__(4);
var _pdfjsFitCurve = __w_pdfjs_require__(30);
var _tools = __w_pdfjs_require__(5);
const RESIZER_SIZE = 16;
const TIME_TO_WAIT_BEFORE_FIXING_DIMS = 100;
class InkEditor extends _editor.AnnotationEditor {
  #aspectRatio = 0;
  #baseHeight = 0;
  #baseWidth = 0;
  #boundCanvasPointermove = this.canvasPointermove.bind(this);
  #boundCanvasPointerleave = this.canvasPointerleave.bind(this);
  #boundCanvasPointerup = this.canvasPointerup.bind(this);
  #boundCanvasPointerdown = this.canvasPointerdown.bind(this);
  #disableEditing = false;
  #isCanvasInitialized = false;
  #lastPoint = null;
  #observer = null;
  #realWidth = 0;
  #realHeight = 0;
  #requestFrameCallback = null;
  static _defaultColor = null;
  static _defaultOpacity = 1;
  static _defaultThickness = 1;
  static _l10nPromise;
  static _type = "ink";
  constructor(params) {
    super({
      ...params,
      name: "inkEditor"
    });
    this.color = params.color || null;
    this.thickness = params.thickness || null;
    this.opacity = params.opacity || null;
    this.paths = [];
    this.bezierPath2D = [];
    this.currentPath = [];
    this.scaleFactor = 1;
    this.translationX = this.translationY = 0;
    this.x = 0;
    this.y = 0;
  }
  static initialize(l10n) {
    this._l10nPromise = new Map(["editor_ink_canvas_aria_label", "editor_ink2_aria_label"].map(str => [str, l10n.get(str)]));
  }
  static updateDefaultParams(type, value) {
    switch (type) {
      case _util.AnnotationEditorParamsType.INK_THICKNESS:
        InkEditor._defaultThickness = value;
        break;
      case _util.AnnotationEditorParamsType.INK_COLOR:
        InkEditor._defaultColor = value;
        break;
      case _util.AnnotationEditorParamsType.INK_OPACITY:
        InkEditor._defaultOpacity = value / 100;
        break;
    }
  }
  updateParams(type, value) {
    switch (type) {
      case _util.AnnotationEditorParamsType.INK_THICKNESS:
        this.#updateThickness(value);
        break;
      case _util.AnnotationEditorParamsType.INK_COLOR:
        this.#updateColor(value);
        break;
      case _util.AnnotationEditorParamsType.INK_OPACITY:
        this.#updateOpacity(value);
        break;
    }
  }
  static get defaultPropertiesToUpdate() {
    return [[_util.AnnotationEditorParamsType.INK_THICKNESS, InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(InkEditor._defaultOpacity * 100)]];
  }
  get propertiesToUpdate() {
    return [[_util.AnnotationEditorParamsType.INK_THICKNESS, this.thickness || InkEditor._defaultThickness], [_util.AnnotationEditorParamsType.INK_COLOR, this.color || InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor], [_util.AnnotationEditorParamsType.INK_OPACITY, Math.round(100 * (this.opacity ?? InkEditor._defaultOpacity))]];
  }
  #updateThickness(thickness) {
    const savedThickness = this.thickness;
    this.addCommands({
      cmd: () => {
        this.thickness = thickness;
        this.#fitToContent();
      },
      undo: () => {
        this.thickness = savedThickness;
        this.#fitToContent();
      },
      mustExec: true,
      type: _util.AnnotationEditorParamsType.INK_THICKNESS,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  #updateColor(color) {
    const savedColor = this.color;
    this.addCommands({
      cmd: () => {
        this.color = color;
        this.#redraw();
      },
      undo: () => {
        this.color = savedColor;
        this.#redraw();
      },
      mustExec: true,
      type: _util.AnnotationEditorParamsType.INK_COLOR,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  #updateOpacity(opacity) {
    opacity /= 100;
    const savedOpacity = this.opacity;
    this.addCommands({
      cmd: () => {
        this.opacity = opacity;
        this.#redraw();
      },
      undo: () => {
        this.opacity = savedOpacity;
        this.#redraw();
      },
      mustExec: true,
      type: _util.AnnotationEditorParamsType.INK_OPACITY,
      overwriteIfSameType: true,
      keepUndo: true
    });
  }
  rebuild() {
    super.rebuild();
    if (this.div === null) {
      return;
    }
    if (!this.canvas) {
      this.#createCanvas();
      this.#createObserver();
    }
    if (!this.isAttachedToDOM) {
      this.parent.add(this);
      this.#setCanvasDims();
    }
    this.#fitToContent();
  }
  remove() {
    if (this.canvas === null) {
      return;
    }
    if (!this.isEmpty()) {
      this.commit();
    }
    this.canvas.width = this.canvas.height = 0;
    this.canvas.remove();
    this.canvas = null;
    this.#observer.disconnect();
    this.#observer = null;
    super.remove();
  }
  setParent(parent) {
    if (!this.parent && parent) {
      this._uiManager.removeShouldRescale(this);
    } else if (this.parent && parent === null) {
      this._uiManager.addShouldRescale(this);
    }
    super.setParent(parent);
  }
  onScaleChanging() {
    const [parentWidth, parentHeight] = this.parentDimensions;
    const width = this.width * parentWidth;
    const height = this.height * parentHeight;
    this.setDimensions(width, height);
  }
  enableEditMode() {
    if (this.#disableEditing || this.canvas === null) {
      return;
    }
    super.enableEditMode();
    this.div.draggable = false;
    this.canvas.addEventListener("pointerdown", this.#boundCanvasPointerdown);
    this.canvas.addEventListener("pointerup", this.#boundCanvasPointerup);
  }
  disableEditMode() {
    if (!this.isInEditMode() || this.canvas === null) {
      return;
    }
    super.disableEditMode();
    this.div.draggable = !this.isEmpty();
    this.div.classList.remove("editing");
    this.canvas.removeEventListener("pointerdown", this.#boundCanvasPointerdown);
    this.canvas.removeEventListener("pointerup", this.#boundCanvasPointerup);
  }
  onceAdded() {
    this.div.draggable = !this.isEmpty();
  }
  isEmpty() {
    return this.paths.length === 0 || this.paths.length === 1 && this.paths[0].length === 0;
  }
  #getInitialBBox() {
    const {
      parentRotation,
      parentDimensions: [width, height]
    } = this;
    switch (parentRotation) {
      case 90:
        return [0, height, height, width];
      case 180:
        return [width, height, width, height];
      case 270:
        return [width, 0, height, width];
      default:
        return [0, 0, width, height];
    }
  }
  #setStroke() {
    const {
      ctx,
      color,
      opacity,
      thickness,
      parentScale,
      scaleFactor
    } = this;
    ctx.lineWidth = thickness * parentScale / scaleFactor;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.miterLimit = 10;
    ctx.strokeStyle = `${color}${(0, _tools.opacityToHex)(opacity)}`;
  }
  #startDrawing(x, y) {
    this.isEditing = true;
    if (!this.#isCanvasInitialized) {
      this.#isCanvasInitialized = true;
      this.#setCanvasDims();
      this.thickness ||= InkEditor._defaultThickness;
      this.color ||= InkEditor._defaultColor || _editor.AnnotationEditor._defaultLineColor;
      this.opacity ??= InkEditor._defaultOpacity;
    }
    this.currentPath.push([x, y]);
    this.#lastPoint = null;
    this.#setStroke();
    this.ctx.beginPath();
    this.ctx.moveTo(x, y);
    this.#requestFrameCallback = () => {
      if (!this.#requestFrameCallback) {
        return;
      }
      if (this.#lastPoint) {
        if (this.isEmpty()) {
          this.ctx.setTransform(1, 0, 0, 1, 0, 0);
          this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        } else {
          this.#redraw();
        }
        this.ctx.lineTo(...this.#lastPoint);
        this.#lastPoint = null;
        this.ctx.stroke();
      }
      window.requestAnimationFrame(this.#requestFrameCallback);
    };
    window.requestAnimationFrame(this.#requestFrameCallback);
  }
  #draw(x, y) {
    const [lastX, lastY] = this.currentPath.at(-1);
    if (x === lastX && y === lastY) {
      return;
    }
    this.currentPath.push([x, y]);
    this.#lastPoint = [x, y];
  }
  #stopDrawing(x, y) {
    this.ctx.closePath();
    this.#requestFrameCallback = null;
    x = Math.min(Math.max(x, 0), this.canvas.width);
    y = Math.min(Math.max(y, 0), this.canvas.height);
    const [lastX, lastY] = this.currentPath.at(-1);
    if (x !== lastX || y !== lastY) {
      this.currentPath.push([x, y]);
    }
    let bezier;
    if (this.currentPath.length !== 1) {
      bezier = (0, _pdfjsFitCurve.fitCurve)(this.currentPath, 30, null);
    } else {
      const xy = [x, y];
      bezier = [[xy, xy.slice(), xy.slice(), xy]];
    }
    const path2D = InkEditor.#buildPath2D(bezier);
    this.currentPath.length = 0;
    const cmd = () => {
      this.paths.push(bezier);
      this.bezierPath2D.push(path2D);
      this.rebuild();
    };
    const undo = () => {
      this.paths.pop();
      this.bezierPath2D.pop();
      if (this.paths.length === 0) {
        this.remove();
      } else {
        if (!this.canvas) {
          this.#createCanvas();
          this.#createObserver();
        }
        this.#fitToContent();
      }
    };
    this.addCommands({
      cmd,
      undo,
      mustExec: true
    });
  }
  #redraw() {
    if (this.isEmpty()) {
      this.#updateTransform();
      return;
    }
    this.#setStroke();
    const {
      canvas,
      ctx
    } = this;
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    this.#updateTransform();
    for (const path of this.bezierPath2D) {
      ctx.stroke(path);
    }
  }
  commit() {
    if (this.#disableEditing) {
      return;
    }
    super.commit();
    this.isEditing = false;
    this.disableEditMode();
    this.setInForeground();
    this.#disableEditing = true;
    this.div.classList.add("disabled");
    this.#fitToContent(true);
    this.parent.addInkEditorIfNeeded(true);
    this.parent.moveEditorInDOM(this);
    this.div.focus({
      preventScroll: true
    });
  }
  focusin(event) {
    super.focusin(event);
    this.enableEditMode();
  }
  canvasPointerdown(event) {
    if (event.button !== 0 || !this.isInEditMode() || this.#disableEditing) {
      return;
    }
    this.setInForeground();
    if (event.type !== "mouse") {
      this.div.focus();
    }
    event.stopPropagation();
    this.canvas.addEventListener("pointerleave", this.#boundCanvasPointerleave);
    this.canvas.addEventListener("pointermove", this.#boundCanvasPointermove);
    this.#startDrawing(event.offsetX, event.offsetY);
  }
  canvasPointermove(event) {
    event.stopPropagation();
    this.#draw(event.offsetX, event.offsetY);
  }
  canvasPointerup(event) {
    if (event.button !== 0) {
      return;
    }
    if (this.isInEditMode() && this.currentPath.length !== 0) {
      event.stopPropagation();
      this.#endDrawing(event);
      this.setInBackground();
    }
  }
  canvasPointerleave(event) {
    this.#endDrawing(event);
    this.setInBackground();
  }
  #endDrawing(event) {
    this.#stopDrawing(event.offsetX, event.offsetY);
    this.canvas.removeEventListener("pointerleave", this.#boundCanvasPointerleave);
    this.canvas.removeEventListener("pointermove", this.#boundCanvasPointermove);
    this.addToAnnotationStorage();
  }
  #createCanvas() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = this.canvas.height = 0;
    this.canvas.className = "inkEditorCanvas";
    InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then(msg => this.canvas?.setAttribute("aria-label", msg));
    this.div.append(this.canvas);
    this.ctx = this.canvas.getContext("2d");
  }
  #createObserver() {
    let timeoutId = null;
    this.#observer = new ResizeObserver(entries => {
      const rect = entries[0].contentRect;
      if (rect.width && rect.height) {
        if (timeoutId !== null) {
          clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
          this.fixDims();
          timeoutId = null;
        }, TIME_TO_WAIT_BEFORE_FIXING_DIMS);
        this.setDimensions(rect.width, rect.height);
      }
    });
    this.#observer.observe(this.div);
  }
  render() {
    if (this.div) {
      return this.div;
    }
    let baseX, baseY;
    if (this.width) {
      baseX = this.x;
      baseY = this.y;
    }
    super.render();
    InkEditor._l10nPromise.get("editor_ink2_aria_label").then(msg => this.div?.setAttribute("aria-label", msg));
    const [x, y, w, h] = this.#getInitialBBox();
    this.setAt(x, y, 0, 0);
    this.setDims(w, h);
    this.#createCanvas();
    if (this.width) {
      const [parentWidth, parentHeight] = this.parentDimensions;
      this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight);
      this.#isCanvasInitialized = true;
      this.#setCanvasDims();
      this.setDims(this.width * parentWidth, this.height * parentHeight);
      this.#redraw();
      this.#setMinDims();
      this.div.classList.add("disabled");
    } else {
      this.div.classList.add("editing");
      this.enableEditMode();
    }
    this.#createObserver();
    return this.div;
  }
  #setCanvasDims() {
    if (!this.#isCanvasInitialized) {
      return;
    }
    const [parentWidth, parentHeight] = this.parentDimensions;
    this.canvas.width = Math.ceil(this.width * parentWidth);
    this.canvas.height = Math.ceil(this.height * parentHeight);
    this.#updateTransform();
  }
  setDimensions(width, height) {
    const roundedWidth = Math.round(width);
    const roundedHeight = Math.round(height);
    if (this.#realWidth === roundedWidth && this.#realHeight === roundedHeight) {
      return;
    }
    this.#realWidth = roundedWidth;
    this.#realHeight = roundedHeight;
    this.canvas.style.visibility = "hidden";
    if (this.#aspectRatio && Math.abs(this.#aspectRatio - width / height) > 1e-2) {
      height = Math.ceil(width / this.#aspectRatio);
      this.setDims(width, height);
    }
    const [parentWidth, parentHeight] = this.parentDimensions;
    this.width = width / parentWidth;
    this.height = height / parentHeight;
    if (this.#disableEditing) {
      this.#setScaleFactor(width, height);
    }
    this.#setCanvasDims();
    this.#redraw();
    this.canvas.style.visibility = "visible";
  }
  #setScaleFactor(width, height) {
    const padding = this.#getPadding();
    const scaleFactorW = (width - padding) / this.#baseWidth;
    const scaleFactorH = (height - padding) / this.#baseHeight;
    this.scaleFactor = Math.min(scaleFactorW, scaleFactorH);
  }
  #updateTransform() {
    const padding = this.#getPadding() / 2;
    this.ctx.setTransform(this.scaleFactor, 0, 0, this.scaleFactor, this.translationX * this.scaleFactor + padding, this.translationY * this.scaleFactor + padding);
  }
  static #buildPath2D(bezier) {
    const path2D = new Path2D();
    for (let i = 0, ii = bezier.length; i < ii; i++) {
      const [first, control1, control2, second] = bezier[i];
      if (i === 0) {
        path2D.moveTo(...first);
      }
      path2D.bezierCurveTo(control1[0], control1[1], control2[0], control2[1], second[0], second[1]);
    }
    return path2D;
  }
  #serializePaths(s, tx, ty, h) {
    const NUMBER_OF_POINTS_ON_BEZIER_CURVE = 4;
    const paths = [];
    const padding = this.thickness / 2;
    let buffer, points;
    for (const bezier of this.paths) {
      buffer = [];
      points = [];
      for (let i = 0, ii = bezier.length; i < ii; i++) {
        const [first, control1, control2, second] = bezier[i];
        const p10 = s * (first[0] + tx) + padding;
        const p11 = h - s * (first[1] + ty) - padding;
        const p20 = s * (control1[0] + tx) + padding;
        const p21 = h - s * (control1[1] + ty) - padding;
        const p30 = s * (control2[0] + tx) + padding;
        const p31 = h - s * (control2[1] + ty) - padding;
        const p40 = s * (second[0] + tx) + padding;
        const p41 = h - s * (second[1] + ty) - padding;
        if (i === 0) {
          buffer.push(p10, p11);
          points.push(p10, p11);
        }
        buffer.push(p20, p21, p30, p31, p40, p41);
        this.#extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, NUMBER_OF_POINTS_ON_BEZIER_CURVE, points);
      }
      paths.push({
        bezier: buffer,
        points
      });
    }
    return paths;
  }
  #extractPointsOnBezier(p10, p11, p20, p21, p30, p31, p40, p41, n, points) {
    if (this.#isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41)) {
      points.push(p40, p41);
      return;
    }
    for (let i = 1; i < n - 1; i++) {
      const t = i / n;
      const mt = 1 - t;
      let q10 = t * p10 + mt * p20;
      let q11 = t * p11 + mt * p21;
      let q20 = t * p20 + mt * p30;
      let q21 = t * p21 + mt * p31;
      const q30 = t * p30 + mt * p40;
      const q31 = t * p31 + mt * p41;
      q10 = t * q10 + mt * q20;
      q11 = t * q11 + mt * q21;
      q20 = t * q20 + mt * q30;
      q21 = t * q21 + mt * q31;
      q10 = t * q10 + mt * q20;
      q11 = t * q11 + mt * q21;
      points.push(q10, q11);
    }
    points.push(p40, p41);
  }
  #isAlmostFlat(p10, p11, p20, p21, p30, p31, p40, p41) {
    const tol = 10;
    const ax = (3 * p20 - 2 * p10 - p40) ** 2;
    const ay = (3 * p21 - 2 * p11 - p41) ** 2;
    const bx = (3 * p30 - p10 - 2 * p40) ** 2;
    const by = (3 * p31 - p11 - 2 * p41) ** 2;
    return Math.max(ax, bx) + Math.max(ay, by) <= tol;
  }
  #getBbox() {
    let xMin = Infinity;
    let xMax = -Infinity;
    let yMin = Infinity;
    let yMax = -Infinity;
    for (const path of this.paths) {
      for (const [first, control1, control2, second] of path) {
        const bbox = _util.Util.bezierBoundingBox(...first, ...control1, ...control2, ...second);
        xMin = Math.min(xMin, bbox[0]);
        yMin = Math.min(yMin, bbox[1]);
        xMax = Math.max(xMax, bbox[2]);
        yMax = Math.max(yMax, bbox[3]);
      }
    }
    return [xMin, yMin, xMax, yMax];
  }
  #getPadding() {
    return this.#disableEditing ? Math.ceil(this.thickness * this.parentScale) : 0;
  }
  #fitToContent(firstTime = false) {
    if (this.isEmpty()) {
      return;
    }
    if (!this.#disableEditing) {
      this.#redraw();
      return;
    }
    const bbox = this.#getBbox();
    const padding = this.#getPadding();
    this.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
    this.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
    const width = Math.ceil(padding + this.#baseWidth * this.scaleFactor);
    const height = Math.ceil(padding + this.#baseHeight * this.scaleFactor);
    const [parentWidth, parentHeight] = this.parentDimensions;
    this.width = width / parentWidth;
    this.height = height / parentHeight;
    this.#aspectRatio = width / height;
    this.#setMinDims();
    const prevTranslationX = this.translationX;
    const prevTranslationY = this.translationY;
    this.translationX = -bbox[0];
    this.translationY = -bbox[1];
    this.#setCanvasDims();
    this.#redraw();
    this.#realWidth = width;
    this.#realHeight = height;
    this.setDims(width, height);
    const unscaledPadding = firstTime ? padding / this.scaleFactor / 2 : 0;
    this.translate(prevTranslationX - this.translationX - unscaledPadding, prevTranslationY - this.translationY - unscaledPadding);
  }
  #setMinDims() {
    const {
      style
    } = this.div;
    if (this.#aspectRatio >= 1) {
      style.minHeight = `${RESIZER_SIZE}px`;
      style.minWidth = `${Math.round(this.#aspectRatio * RESIZER_SIZE)}px`;
    } else {
      style.minWidth = `${RESIZER_SIZE}px`;
      style.minHeight = `${Math.round(RESIZER_SIZE / this.#aspectRatio)}px`;
    }
  }
  static deserialize(data, parent, uiManager) {
    const editor = super.deserialize(data, parent, uiManager);
    editor.thickness = data.thickness;
    editor.color = _util.Util.makeHexColor(...data.color);
    editor.opacity = data.opacity;
    const [pageWidth, pageHeight] = editor.pageDimensions;
    const width = editor.width * pageWidth;
    const height = editor.height * pageHeight;
    const scaleFactor = editor.parentScale;
    const padding = data.thickness / 2;
    editor.#aspectRatio = width / height;
    editor.#disableEditing = true;
    editor.#realWidth = Math.round(width);
    editor.#realHeight = Math.round(height);
    for (const {
      bezier
    } of data.paths) {
      const path = [];
      editor.paths.push(path);
      let p0 = scaleFactor * (bezier[0] - padding);
      let p1 = scaleFactor * (height - bezier[1] - padding);
      for (let i = 2, ii = bezier.length; i < ii; i += 6) {
        const p10 = scaleFactor * (bezier[i] - padding);
        const p11 = scaleFactor * (height - bezier[i + 1] - padding);
        const p20 = scaleFactor * (bezier[i + 2] - padding);
        const p21 = scaleFactor * (height - bezier[i + 3] - padding);
        const p30 = scaleFactor * (bezier[i + 4] - padding);
        const p31 = scaleFactor * (height - bezier[i + 5] - padding);
        path.push([[p0, p1], [p10, p11], [p20, p21], [p30, p31]]);
        p0 = p30;
        p1 = p31;
      }
      const path2D = this.#buildPath2D(path);
      editor.bezierPath2D.push(path2D);
    }
    const bbox = editor.#getBbox();
    editor.#baseWidth = Math.max(RESIZER_SIZE, bbox[2] - bbox[0]);
    editor.#baseHeight = Math.max(RESIZER_SIZE, bbox[3] - bbox[1]);
    editor.#setScaleFactor(width, height);
    return editor;
  }
  serialize() {
    if (this.isEmpty()) {
      return null;
    }
    const rect = this.getRect(0, 0);
    const height = this.rotation % 180 === 0 ? rect[3] - rect[1] : rect[2] - rect[0];
    const color = _editor.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);
    return {
      annotationType: _util.AnnotationEditorType.INK,
      color,
      thickness: this.thickness,
      opacity: this.opacity,
      paths: this.#serializePaths(this.scaleFactor / this.parentScale, this.translationX, this.translationY, height),
      pageIndex: this.pageIndex,
      rect,
      rotation: this.rotation
    };
  }
}
exports.InkEditor = InkEditor;

/***/ }),
/* 30 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.fitCurve = void 0;
const fitCurve = __w_pdfjs_require__(31);
exports.fitCurve = fitCurve;

/***/ }),
/* 31 */
/***/ ((module) => {



function fitCurve(points, maxError, progressCallback) {
  if (!Array.isArray(points)) {
    throw new TypeError("First argument should be an array");
  }
  points.forEach(point => {
    if (!Array.isArray(point) || point.some(item => typeof item !== 'number') || point.length !== points[0].length) {
      throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.");
    }
  });
  points = points.filter((point, i) => i === 0 || !point.every((val, j) => val === points[i - 1][j]));
  if (points.length < 2) {
    return [];
  }
  const len = points.length;
  const leftTangent = createTangent(points[1], points[0]);
  const rightTangent = createTangent(points[len - 2], points[len - 1]);
  return fitCubic(points, leftTangent, rightTangent, maxError, progressCallback);
}
function fitCubic(points, leftTangent, rightTangent, error, progressCallback) {
  const MaxIterations = 20;
  var bezCurve, u, uPrime, maxError, prevErr, splitPoint, prevSplit, centerVector, toCenterTangent, fromCenterTangent, beziers, dist, i;
  if (points.length === 2) {
    dist = maths.vectorLen(maths.subtract(points[0], points[1])) / 3.0;
    bezCurve = [points[0], maths.addArrays(points[0], maths.mulItems(leftTangent, dist)), maths.addArrays(points[1], maths.mulItems(rightTangent, dist)), points[1]];
    return [bezCurve];
  }
  u = chordLengthParameterize(points);
  [bezCurve, maxError, splitPoint] = generateAndReport(points, u, u, leftTangent, rightTangent, progressCallback);
  if (maxError === 0 || maxError < error) {
    return [bezCurve];
  }
  if (maxError < error * error) {
    uPrime = u;
    prevErr = maxError;
    prevSplit = splitPoint;
    for (i = 0; i < MaxIterations; i++) {
      uPrime = reparameterize(bezCurve, points, uPrime);
      [bezCurve, maxError, splitPoint] = generateAndReport(points, u, uPrime, leftTangent, rightTangent, progressCallback);
      if (maxError < error) {
        return [bezCurve];
      } else if (splitPoint === prevSplit) {
        let errChange = maxError / prevErr;
        if (errChange > .9999 && errChange < 1.0001) {
          break;
        }
      }
      prevErr = maxError;
      prevSplit = splitPoint;
    }
  }
  beziers = [];
  centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint + 1]);
  if (centerVector.every(val => val === 0)) {
    centerVector = maths.subtract(points[splitPoint - 1], points[splitPoint]);
    [centerVector[0], centerVector[1]] = [-centerVector[1], centerVector[0]];
  }
  toCenterTangent = maths.normalize(centerVector);
  fromCenterTangent = maths.mulItems(toCenterTangent, -1);
  beziers = beziers.concat(fitCubic(points.slice(0, splitPoint + 1), leftTangent, toCenterTangent, error, progressCallback));
  beziers = beziers.concat(fitCubic(points.slice(splitPoint), fromCenterTangent, rightTangent, error, progressCallback));
  return beziers;
}
;
function generateAndReport(points, paramsOrig, paramsPrime, leftTangent, rightTangent, progressCallback) {
  var bezCurve, maxError, splitPoint;
  bezCurve = generateBezier(points, paramsPrime, leftTangent, rightTangent, progressCallback);
  [maxError, splitPoint] = computeMaxError(points, bezCurve, paramsOrig);
  if (progressCallback) {
    progressCallback({
      bez: bezCurve,
      points: points,
      params: paramsOrig,
      maxErr: maxError,
      maxPoint: splitPoint
    });
  }
  return [bezCurve, maxError, splitPoint];
}
function generateBezier(points, parameters, leftTangent, rightTangent) {
  var bezCurve,
    A,
    a,
    C,
    X,
    det_C0_C1,
    det_C0_X,
    det_X_C1,
    alpha_l,
    alpha_r,
    epsilon,
    segLength,
    i,
    len,
    tmp,
    u,
    ux,
    firstPoint = points[0],
    lastPoint = points[points.length - 1];
  bezCurve = [firstPoint, null, null, lastPoint];
  A = maths.zeros_Xx2x2(parameters.length);
  for (i = 0, len = parameters.length; i < len; i++) {
    u = parameters[i];
    ux = 1 - u;
    a = A[i];
    a[0] = maths.mulItems(leftTangent, 3 * u * (ux * ux));
    a[1] = maths.mulItems(rightTangent, 3 * ux * (u * u));
  }
  C = [[0, 0], [0, 0]];
  X = [0, 0];
  for (i = 0, len = points.length; i < len; i++) {
    u = parameters[i];
    a = A[i];
    C[0][0] += maths.dot(a[0], a[0]);
    C[0][1] += maths.dot(a[0], a[1]);
    C[1][0] += maths.dot(a[0], a[1]);
    C[1][1] += maths.dot(a[1], a[1]);
    tmp = maths.subtract(points[i], bezier.q([firstPoint, firstPoint, lastPoint, lastPoint], u));
    X[0] += maths.dot(a[0], tmp);
    X[1] += maths.dot(a[1], tmp);
  }
  det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
  det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
  alpha_l = det_C0_C1 === 0 ? 0 : det_X_C1 / det_C0_C1;
  alpha_r = det_C0_C1 === 0 ? 0 : det_C0_X / det_C0_C1;
  segLength = maths.vectorLen(maths.subtract(firstPoint, lastPoint));
  epsilon = 1.0e-6 * segLength;
  if (alpha_l < epsilon || alpha_r < epsilon) {
    bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, segLength / 3.0));
    bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, segLength / 3.0));
  } else {
    bezCurve[1] = maths.addArrays(firstPoint, maths.mulItems(leftTangent, alpha_l));
    bezCurve[2] = maths.addArrays(lastPoint, maths.mulItems(rightTangent, alpha_r));
  }
  return bezCurve;
}
;
function reparameterize(bezier, points, parameters) {
  return parameters.map((p, i) => newtonRaphsonRootFind(bezier, points[i], p));
}
;
function newtonRaphsonRootFind(bez, point, u) {
  var d = maths.subtract(bezier.q(bez, u), point),
    qprime = bezier.qprime(bez, u),
    numerator = maths.mulMatrix(d, qprime),
    denominator = maths.sum(maths.squareItems(qprime)) + 2 * maths.mulMatrix(d, bezier.qprimeprime(bez, u));
  if (denominator === 0) {
    return u;
  } else {
    return u - numerator / denominator;
  }
}
;
function chordLengthParameterize(points) {
  var u = [],
    currU,
    prevU,
    prevP;
  points.forEach((p, i) => {
    currU = i ? prevU + maths.vectorLen(maths.subtract(p, prevP)) : 0;
    u.push(currU);
    prevU = currU;
    prevP = p;
  });
  u = u.map(x => x / prevU);
  return u;
}
;
function computeMaxError(points, bez, parameters) {
  var dist, maxDist, splitPoint, v, i, count, point, t;
  maxDist = 0;
  splitPoint = Math.floor(points.length / 2);
  const t_distMap = mapTtoRelativeDistances(bez, 10);
  for (i = 0, count = points.length; i < count; i++) {
    point = points[i];
    t = find_t(bez, parameters[i], t_distMap, 10);
    v = maths.subtract(bezier.q(bez, t), point);
    dist = v[0] * v[0] + v[1] * v[1];
    if (dist > maxDist) {
      maxDist = dist;
      splitPoint = i;
    }
  }
  return [maxDist, splitPoint];
}
;
var mapTtoRelativeDistances = function (bez, B_parts) {
  var B_t_curr;
  var B_t_dist = [0];
  var B_t_prev = bez[0];
  var sumLen = 0;
  for (var i = 1; i <= B_parts; i++) {
    B_t_curr = bezier.q(bez, i / B_parts);
    sumLen += maths.vectorLen(maths.subtract(B_t_curr, B_t_prev));
    B_t_dist.push(sumLen);
    B_t_prev = B_t_curr;
  }
  B_t_dist = B_t_dist.map(x => x / sumLen);
  return B_t_dist;
};
function find_t(bez, param, t_distMap, B_parts) {
  if (param < 0) {
    return 0;
  }
  if (param > 1) {
    return 1;
  }
  var lenMax, lenMin, tMax, tMin, t;
  for (var i = 1; i <= B_parts; i++) {
    if (param <= t_distMap[i]) {
      tMin = (i - 1) / B_parts;
      tMax = i / B_parts;
      lenMin = t_distMap[i - 1];
      lenMax = t_distMap[i];
      t = (param - lenMin) / (lenMax - lenMin) * (tMax - tMin) + tMin;
      break;
    }
  }
  return t;
}
function createTangent(pointA, pointB) {
  return maths.normalize(maths.subtract(pointA, pointB));
}
class maths {
  static zeros_Xx2x2(x) {
    var zs = [];
    while (x--) {
      zs.push([0, 0]);
    }
    return zs;
  }
  static mulItems(items, multiplier) {
    return items.map(x => x * multiplier);
  }
  static mulMatrix(m1, m2) {
    return m1.reduce((sum, x1, i) => sum + x1 * m2[i], 0);
  }
  static subtract(arr1, arr2) {
    return arr1.map((x1, i) => x1 - arr2[i]);
  }
  static addArrays(arr1, arr2) {
    return arr1.map((x1, i) => x1 + arr2[i]);
  }
  static addItems(items, addition) {
    return items.map(x => x + addition);
  }
  static sum(items) {
    return items.reduce((sum, x) => sum + x);
  }
  static dot(m1, m2) {
    return maths.mulMatrix(m1, m2);
  }
  static vectorLen(v) {
    return Math.hypot(...v);
  }
  static divItems(items, divisor) {
    return items.map(x => x / divisor);
  }
  static squareItems(items) {
    return items.map(x => x * x);
  }
  static normalize(v) {
    return this.divItems(v, this.vectorLen(v));
  }
}
class bezier {
  static q(ctrlPoly, t) {
    var tx = 1.0 - t;
    var pA = maths.mulItems(ctrlPoly[0], tx * tx * tx),
      pB = maths.mulItems(ctrlPoly[1], 3 * tx * tx * t),
      pC = maths.mulItems(ctrlPoly[2], 3 * tx * t * t),
      pD = maths.mulItems(ctrlPoly[3], t * t * t);
    return maths.addArrays(maths.addArrays(pA, pB), maths.addArrays(pC, pD));
  }
  static qprime(ctrlPoly, t) {
    var tx = 1.0 - t;
    var pA = maths.mulItems(maths.subtract(ctrlPoly[1], ctrlPoly[0]), 3 * tx * tx),
      pB = maths.mulItems(maths.subtract(ctrlPoly[2], ctrlPoly[1]), 6 * tx * t),
      pC = maths.mulItems(maths.subtract(ctrlPoly[3], ctrlPoly[2]), 3 * t * t);
    return maths.addArrays(maths.addArrays(pA, pB), pC);
  }
  static qprimeprime(ctrlPoly, t) {
    return maths.addArrays(maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[2], maths.mulItems(ctrlPoly[1], 2)), ctrlPoly[0]), 6 * (1.0 - t)), maths.mulItems(maths.addArrays(maths.subtract(ctrlPoly[3], maths.mulItems(ctrlPoly[2], 2)), ctrlPoly[1]), 6 * t));
  }
}
module.exports = fitCurve;
module.exports.fitCubic = fitCubic;
module.exports.createTangent = createTangent;

/***/ }),
/* 32 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.AnnotationLayer = void 0;
var _util = __w_pdfjs_require__(1);
var _display_utils = __w_pdfjs_require__(6);
var _annotation_storage = __w_pdfjs_require__(3);
var _scripting_utils = __w_pdfjs_require__(33);
var _xfa_layer = __w_pdfjs_require__(34);
const DEFAULT_TAB_INDEX = 1000;
const DEFAULT_FONT_SIZE = 9;
const GetElementsByNameSet = new WeakSet();
function getRectDims(rect) {
  return {
    width: rect[2] - rect[0],
    height: rect[3] - rect[1]
  };
}
class AnnotationElementFactory {
  static create(parameters) {
    const subtype = parameters.data.annotationType;
    switch (subtype) {
      case _util.AnnotationType.LINK:
        return new LinkAnnotationElement(parameters);
      case _util.AnnotationType.TEXT:
        return new TextAnnotationElement(parameters);
      case _util.AnnotationType.WIDGET:
        const fieldType = parameters.data.fieldType;
        switch (fieldType) {
          case "Tx":
            return new TextWidgetAnnotationElement(parameters);
          case "Btn":
            if (parameters.data.radioButton) {
              return new RadioButtonWidgetAnnotationElement(parameters);
            } else if (parameters.data.checkBox) {
              return new CheckboxWidgetAnnotationElement(parameters);
            }
            return new PushButtonWidgetAnnotationElement(parameters);
          case "Ch":
            return new ChoiceWidgetAnnotationElement(parameters);
        }
        return new WidgetAnnotationElement(parameters);
      case _util.AnnotationType.POPUP:
        return new PopupAnnotationElement(parameters);
      case _util.AnnotationType.FREETEXT:
        return new FreeTextAnnotationElement(parameters);
      case _util.AnnotationType.LINE:
        return new LineAnnotationElement(parameters);
      case _util.AnnotationType.SQUARE:
        return new SquareAnnotationElement(parameters);
      case _util.AnnotationType.CIRCLE:
        return new CircleAnnotationElement(parameters);
      case _util.AnnotationType.POLYLINE:
        return new PolylineAnnotationElement(parameters);
      case _util.AnnotationType.CARET:
        return new CaretAnnotationElement(parameters);
      case _util.AnnotationType.INK:
        return new InkAnnotationElement(parameters);
      case _util.AnnotationType.POLYGON:
        return new PolygonAnnotationElement(parameters);
      case _util.AnnotationType.HIGHLIGHT:
        return new HighlightAnnotationElement(parameters);
      case _util.AnnotationType.UNDERLINE:
        return new UnderlineAnnotationElement(parameters);
      case _util.AnnotationType.SQUIGGLY:
        return new SquigglyAnnotationElement(parameters);
      case _util.AnnotationType.STRIKEOUT:
        return new StrikeOutAnnotationElement(parameters);
      case _util.AnnotationType.STAMP:
        return new StampAnnotationElement(parameters);
      case _util.AnnotationType.FILEATTACHMENT:
        return new FileAttachmentAnnotationElement(parameters);
      default:
        return new AnnotationElement(parameters);
    }
  }
}
class AnnotationElement {
  constructor(parameters, {
    isRenderable = false,
    ignoreBorder = false,
    createQuadrilaterals = false
  } = {}) {
    this.isRenderable = isRenderable;
    this.data = parameters.data;
    this.layer = parameters.layer;
    this.page = parameters.page;
    this.viewport = parameters.viewport;
    this.linkService = parameters.linkService;
    this.downloadManager = parameters.downloadManager;
    this.imageResourcesPath = parameters.imageResourcesPath;
    this.renderForms = parameters.renderForms;
    this.svgFactory = parameters.svgFactory;
    this.annotationStorage = parameters.annotationStorage;
    this.enableScripting = parameters.enableScripting;
    this.hasJSActions = parameters.hasJSActions;
    this._fieldObjects = parameters.fieldObjects;
    if (isRenderable) {
      this.container = this._createContainer(ignoreBorder);
    }
    if (createQuadrilaterals) {
      this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
    }
  }
  _createContainer(ignoreBorder = false) {
    const {
      data,
      page,
      viewport
    } = this;
    const container = document.createElement("section");
    container.setAttribute("data-annotation-id", data.id);
    const {
      pageWidth,
      pageHeight,
      pageX,
      pageY
    } = viewport.rawDims;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
    if (!ignoreBorder && data.borderStyle.width > 0) {
      container.style.borderWidth = `${data.borderStyle.width}px`;
      const horizontalRadius = data.borderStyle.horizontalCornerRadius;
      const verticalRadius = data.borderStyle.verticalCornerRadius;
      if (horizontalRadius > 0 || verticalRadius > 0) {
        const radius = `calc(${horizontalRadius}px * var(--scale-factor)) / calc(${verticalRadius}px * var(--scale-factor))`;
        container.style.borderRadius = radius;
      } else if (this instanceof RadioButtonWidgetAnnotationElement) {
        const radius = `calc(${width}px * var(--scale-factor)) / calc(${height}px * var(--scale-factor))`;
        container.style.borderRadius = radius;
      }
      switch (data.borderStyle.style) {
        case _util.AnnotationBorderStyleType.SOLID:
          container.style.borderStyle = "solid";
          break;
        case _util.AnnotationBorderStyleType.DASHED:
          container.style.borderStyle = "dashed";
          break;
        case _util.AnnotationBorderStyleType.BEVELED:
          (0, _util.warn)("Unimplemented border style: beveled");
          break;
        case _util.AnnotationBorderStyleType.INSET:
          (0, _util.warn)("Unimplemented border style: inset");
          break;
        case _util.AnnotationBorderStyleType.UNDERLINE:
          container.style.borderBottomStyle = "solid";
          break;
        default:
          break;
      }
      const borderColor = data.borderColor || null;
      if (borderColor) {
        container.style.borderColor = _util.Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0);
      } else {
        container.style.borderWidth = 0;
      }
    }
    container.style.left = `${100 * (rect[0] - pageX) / pageWidth}%`;
    container.style.top = `${100 * (rect[1] - pageY) / pageHeight}%`;
    const {
      rotation
    } = data;
    if (data.hasOwnCanvas || rotation === 0) {
      container.style.width = `${100 * width / pageWidth}%`;
      container.style.height = `${100 * height / pageHeight}%`;
    } else {
      this.setRotation(rotation, container);
    }
    return container;
  }
  setRotation(angle, container = this.container) {
    const {
      pageWidth,
      pageHeight
    } = this.viewport.rawDims;
    const {
      width,
      height
    } = getRectDims(this.data.rect);
    let elementWidth, elementHeight;
    if (angle % 180 === 0) {
      elementWidth = 100 * width / pageWidth;
      elementHeight = 100 * height / pageHeight;
    } else {
      elementWidth = 100 * height / pageWidth;
      elementHeight = 100 * width / pageHeight;
    }
    container.style.width = `${elementWidth}%`;
    container.style.height = `${elementHeight}%`;
    container.setAttribute("data-main-rotation", (360 - angle) % 360);
  }
  get _commonActions() {
    const setColor = (jsName, styleName, event) => {
      const color = event.detail[jsName];
      event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
    };
    return (0, _util.shadow)(this, "_commonActions", {
      display: event => {
        const hidden = event.detail.display % 2 === 1;
        this.container.style.visibility = hidden ? "hidden" : "visible";
        this.annotationStorage.setValue(this.data.id, {
          hidden,
          print: event.detail.display === 0 || event.detail.display === 3
        });
      },
      print: event => {
        this.annotationStorage.setValue(this.data.id, {
          print: event.detail.print
        });
      },
      hidden: event => {
        this.container.style.visibility = event.detail.hidden ? "hidden" : "visible";
        this.annotationStorage.setValue(this.data.id, {
          hidden: event.detail.hidden
        });
      },
      focus: event => {
        setTimeout(() => event.target.focus({
          preventScroll: false
        }), 0);
      },
      userName: event => {
        event.target.title = event.detail.userName;
      },
      readonly: event => {
        if (event.detail.readonly) {
          event.target.setAttribute("readonly", "");
        } else {
          event.target.removeAttribute("readonly");
        }
      },
      required: event => {
        this._setRequired(event.target, event.detail.required);
      },
      bgColor: event => {
        setColor("bgColor", "backgroundColor", event);
      },
      fillColor: event => {
        setColor("fillColor", "backgroundColor", event);
      },
      fgColor: event => {
        setColor("fgColor", "color", event);
      },
      textColor: event => {
        setColor("textColor", "color", event);
      },
      borderColor: event => {
        setColor("borderColor", "borderColor", event);
      },
      strokeColor: event => {
        setColor("strokeColor", "borderColor", event);
      },
      rotation: event => {
        const angle = event.detail.rotation;
        this.setRotation(angle);
        this.annotationStorage.setValue(this.data.id, {
          rotation: angle
        });
      }
    });
  }
  _dispatchEventFromSandbox(actions, jsEvent) {
    const commonActions = this._commonActions;
    for (const name of Object.keys(jsEvent.detail)) {
      const action = actions[name] || commonActions[name];
      action?.(jsEvent);
    }
  }
  _setDefaultPropertiesFromJS(element) {
    if (!this.enableScripting) {
      return;
    }
    const storedData = this.annotationStorage.getRawValue(this.data.id);
    if (!storedData) {
      return;
    }
    const commonActions = this._commonActions;
    for (const [actionName, detail] of Object.entries(storedData)) {
      const action = commonActions[actionName];
      if (action) {
        const eventProxy = {
          detail: {
            [actionName]: detail
          },
          target: element
        };
        action(eventProxy);
        delete storedData[actionName];
      }
    }
  }
  _createQuadrilaterals(ignoreBorder = false) {
    if (!this.data.quadPoints) {
      return null;
    }
    const quadrilaterals = [];
    const savedRect = this.data.rect;
    for (const quadPoint of this.data.quadPoints) {
      this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
      quadrilaterals.push(this._createContainer(ignoreBorder));
    }
    this.data.rect = savedRect;
    return quadrilaterals;
  }
  _createPopup(trigger, data) {
    let container = this.container;
    if (this.quadrilaterals) {
      trigger = trigger || this.quadrilaterals;
      container = this.quadrilaterals[0];
    }
    if (!trigger) {
      trigger = document.createElement("div");
      trigger.className = "popupTriggerArea";
      container.append(trigger);
    }
    const popupElement = new PopupElement({
      container,
      trigger,
      color: data.color,
      titleObj: data.titleObj,
      modificationDate: data.modificationDate,
      contentsObj: data.contentsObj,
      richText: data.richText,
      hideWrapper: true
    });
    const popup = popupElement.render();
    popup.style.left = "100%";
    container.append(popup);
  }
  _renderQuadrilaterals(className) {
    for (const quadrilateral of this.quadrilaterals) {
      quadrilateral.className = className;
    }
    return this.quadrilaterals;
  }
  render() {
    (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
  }
  _getElementsByName(name, skipId = null) {
    const fields = [];
    if (this._fieldObjects) {
      const fieldObj = this._fieldObjects[name];
      if (fieldObj) {
        for (const {
          page,
          id,
          exportValues
        } of fieldObj) {
          if (page === -1) {
            continue;
          }
          if (id === skipId) {
            continue;
          }
          const exportValue = typeof exportValues === "string" ? exportValues : null;
          const domElement = document.querySelector(`[data-element-id="${id}"]`);
          if (domElement && !GetElementsByNameSet.has(domElement)) {
            (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
            continue;
          }
          fields.push({
            id,
            exportValue,
            domElement
          });
        }
      }
      return fields;
    }
    for (const domElement of document.getElementsByName(name)) {
      const {
        exportValue
      } = domElement;
      const id = domElement.getAttribute("data-element-id");
      if (id === skipId) {
        continue;
      }
      if (!GetElementsByNameSet.has(domElement)) {
        continue;
      }
      fields.push({
        id,
        exportValue,
        domElement
      });
    }
    return fields;
  }
}
class LinkAnnotationElement extends AnnotationElement {
  constructor(parameters, options = null) {
    super(parameters, {
      isRenderable: true,
      ignoreBorder: !!options?.ignoreBorder,
      createQuadrilaterals: true
    });
    this.isTooltipOnly = parameters.data.isTooltipOnly;
  }
  render() {
    const {
      data,
      linkService
    } = this;
    const link = document.createElement("a");
    link.setAttribute("data-element-id", data.id);
    let isBound = false;
    if (data.url) {
      linkService.addLinkAttributes(link, data.url, data.newWindow);
      isBound = true;
    } else if (data.action) {
      this._bindNamedAction(link, data.action);
      isBound = true;
    } else if (data.attachment) {
      this._bindAttachment(link, data.attachment);
      isBound = true;
    } else if (data.setOCGState) {
      this.#bindSetOCGState(link, data.setOCGState);
      isBound = true;
    } else if (data.dest) {
      this._bindLink(link, data.dest);
      isBound = true;
    } else {
      if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
        this._bindJSAction(link, data);
        isBound = true;
      }
      if (data.resetForm) {
        this._bindResetFormAction(link, data.resetForm);
        isBound = true;
      } else if (this.isTooltipOnly && !isBound) {
        this._bindLink(link, "");
        isBound = true;
      }
    }
    if (this.quadrilaterals) {
      return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
        const linkElement = index === 0 ? link : link.cloneNode();
        quadrilateral.append(linkElement);
        return quadrilateral;
      });
    }
    this.container.className = "linkAnnotation";
    if (isBound) {
      this.container.append(link);
    }
    return this.container;
  }
  #setInternalLink() {
    this.container.setAttribute("data-internal-link", "");
  }
  _bindLink(link, destination) {
    link.href = this.linkService.getDestinationHash(destination);
    link.onclick = () => {
      if (destination) {
        this.linkService.goToDestination(destination);
      }
      return false;
    };
    if (destination || destination === "") {
      this.#setInternalLink();
    }
  }
  _bindNamedAction(link, action) {
    link.href = this.linkService.getAnchorUrl("");
    link.onclick = () => {
      this.linkService.executeNamedAction(action);
      return false;
    };
    this.#setInternalLink();
  }
  _bindAttachment(link, attachment) {
    link.href = this.linkService.getAnchorUrl("");
    link.onclick = () => {
      this.downloadManager?.openOrDownloadData(this.container, attachment.content, attachment.filename);
      return false;
    };
    this.#setInternalLink();
  }
  #bindSetOCGState(link, action) {
    link.href = this.linkService.getAnchorUrl("");
    link.onclick = () => {
      this.linkService.executeSetOCGState(action);
      return false;
    };
    this.#setInternalLink();
  }
  _bindJSAction(link, data) {
    link.href = this.linkService.getAnchorUrl("");
    const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
    for (const name of Object.keys(data.actions)) {
      const jsName = map.get(name);
      if (!jsName) {
        continue;
      }
      link[jsName] = () => {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: data.id,
            name
          }
        });
        return false;
      };
    }
    if (!link.onclick) {
      link.onclick = () => false;
    }
    this.#setInternalLink();
  }
  _bindResetFormAction(link, resetForm) {
    const otherClickAction = link.onclick;
    if (!otherClickAction) {
      link.href = this.linkService.getAnchorUrl("");
    }
    this.#setInternalLink();
    if (!this._fieldObjects) {
      (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
      if (!otherClickAction) {
        link.onclick = () => false;
      }
      return;
    }
    link.onclick = () => {
      otherClickAction?.();
      const {
        fields: resetFormFields,
        refs: resetFormRefs,
        include
      } = resetForm;
      const allFields = [];
      if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
        const fieldIds = new Set(resetFormRefs);
        for (const fieldName of resetFormFields) {
          const fields = this._fieldObjects[fieldName] || [];
          for (const {
            id
          } of fields) {
            fieldIds.add(id);
          }
        }
        for (const fields of Object.values(this._fieldObjects)) {
          for (const field of fields) {
            if (fieldIds.has(field.id) === include) {
              allFields.push(field);
            }
          }
        }
      } else {
        for (const fields of Object.values(this._fieldObjects)) {
          allFields.push(...fields);
        }
      }
      const storage = this.annotationStorage;
      const allIds = [];
      for (const field of allFields) {
        const {
          id
        } = field;
        allIds.push(id);
        switch (field.type) {
          case "text":
            {
              const value = field.defaultValue || "";
              storage.setValue(id, {
                value
              });
              break;
            }
          case "checkbox":
          case "radiobutton":
            {
              const value = field.defaultValue === field.exportValues;
              storage.setValue(id, {
                value
              });
              break;
            }
          case "combobox":
          case "listbox":
            {
              const value = field.defaultValue || "";
              storage.setValue(id, {
                value
              });
              break;
            }
          default:
            continue;
        }
        const domElement = document.querySelector(`[data-element-id="${id}"]`);
        if (!domElement) {
          continue;
        } else if (!GetElementsByNameSet.has(domElement)) {
          (0, _util.warn)(`_bindResetFormAction - element not allowed: ${id}`);
          continue;
        }
        domElement.dispatchEvent(new Event("resetform"));
      }
      if (this.enableScripting) {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: "app",
            ids: allIds,
            name: "ResetForm"
          }
        });
      }
      return false;
    };
  }
}
class TextAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable
    });
  }
  render() {
    this.container.className = "textAnnotation";
    const image = document.createElement("img");
    image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
    image.alt = "[{{type}} Annotation]";
    image.dataset.l10nId = "text_annotation_type";
    image.dataset.l10nArgs = JSON.stringify({
      type: this.data.name
    });
    if (!this.data.hasPopup) {
      this._createPopup(image, this.data);
    }
    this.container.append(image);
    return this.container;
  }
}
class WidgetAnnotationElement extends AnnotationElement {
  render() {
    if (this.data.alternativeText) {
      this.container.title = this.data.alternativeText;
    }
    return this.container;
  }
  _getKeyModifier(event) {
    const {
      isWin,
      isMac
    } = _util.FeatureTest.platform;
    return isWin && event.ctrlKey || isMac && event.metaKey;
  }
  _setEventListener(element, baseName, eventName, valueGetter) {
    if (baseName.includes("mouse")) {
      element.addEventListener(baseName, event => {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: this.data.id,
            name: eventName,
            value: valueGetter(event),
            shift: event.shiftKey,
            modifier: this._getKeyModifier(event)
          }
        });
      });
    } else {
      element.addEventListener(baseName, event => {
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id: this.data.id,
            name: eventName,
            value: valueGetter(event)
          }
        });
      });
    }
  }
  _setEventListeners(element, names, getter) {
    for (const [baseName, eventName] of names) {
      if (eventName === "Action" || this.data.actions?.[eventName]) {
        this._setEventListener(element, baseName, eventName, getter);
      }
    }
  }
  _setBackgroundColor(element) {
    const color = this.data.backgroundColor || null;
    element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
  }
  _setTextStyle(element) {
    const TEXT_ALIGNMENT = ["left", "center", "right"];
    const {
      fontColor
    } = this.data.defaultAppearanceData;
    const fontSize = this.data.defaultAppearanceData.fontSize || DEFAULT_FONT_SIZE;
    const style = element.style;
    let computedFontSize;
    const BORDER_SIZE = 2;
    const roundToOneDecimal = x => Math.round(10 * x) / 10;
    if (this.data.multiLine) {
      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
      const numberOfLines = Math.round(height / (_util.LINE_FACTOR * fontSize)) || 1;
      const lineHeight = height / numberOfLines;
      computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / _util.LINE_FACTOR));
    } else {
      const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE);
      computedFontSize = Math.min(fontSize, roundToOneDecimal(height / _util.LINE_FACTOR));
    }
    style.fontSize = `calc(${computedFontSize}px * var(--scale-factor))`;
    style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
    if (this.data.textAlignment !== null) {
      style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
    }
  }
  _setRequired(element, isRequired) {
    if (isRequired) {
      element.setAttribute("required", true);
    } else {
      element.removeAttribute("required");
    }
    element.setAttribute("aria-required", isRequired);
  }
}
class TextWidgetAnnotationElement extends WidgetAnnotationElement {
  constructor(parameters) {
    const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
    super(parameters, {
      isRenderable
    });
  }
  setPropertyOnSiblings(base, key, value, keyInStorage) {
    const storage = this.annotationStorage;
    for (const element of this._getElementsByName(base.name, base.id)) {
      if (element.domElement) {
        element.domElement[key] = value;
      }
      storage.setValue(element.id, {
        [keyInStorage]: value
      });
    }
  }
  render() {
    const storage = this.annotationStorage;
    const id = this.data.id;
    this.container.className = "textWidgetAnnotation";
    let element = null;
    if (this.renderForms) {
      const storedData = storage.getValue(id, {
        value: this.data.fieldValue
      });
      let textContent = storedData.formattedValue || storedData.value || "";
      const maxLen = storage.getValue(id, {
        charLimit: this.data.maxLen
      }).charLimit;
      if (maxLen && textContent.length > maxLen) {
        textContent = textContent.slice(0, maxLen);
      }
      const elementData = {
        userValue: textContent,
        formattedValue: null,
        lastCommittedValue: null,
        commitKey: 1
      };
      if (this.data.multiLine) {
        element = document.createElement("textarea");
        element.textContent = textContent;
        if (this.data.doNotScroll) {
          element.style.overflowY = "hidden";
        }
      } else {
        element = document.createElement("input");
        element.type = "text";
        element.setAttribute("value", textContent);
        if (this.data.doNotScroll) {
          element.style.overflowX = "hidden";
        }
      }
      GetElementsByNameSet.add(element);
      element.setAttribute("data-element-id", id);
      element.disabled = this.data.readOnly;
      element.name = this.data.fieldName;
      element.tabIndex = DEFAULT_TAB_INDEX;
      this._setRequired(element, this.data.required);
      if (maxLen) {
        element.maxLength = maxLen;
      }
      element.addEventListener("input", event => {
        storage.setValue(id, {
          value: event.target.value
        });
        this.setPropertyOnSiblings(element, "value", event.target.value, "value");
      });
      element.addEventListener("resetform", event => {
        const defaultValue = this.data.defaultFieldValue ?? "";
        element.value = elementData.userValue = defaultValue;
        elementData.formattedValue = null;
      });
      let blurListener = event => {
        const {
          formattedValue
        } = elementData;
        if (formattedValue !== null && formattedValue !== undefined) {
          event.target.value = formattedValue;
        }
        event.target.scrollLeft = 0;
      };
      if (this.enableScripting && this.hasJSActions) {
        element.addEventListener("focus", event => {
          const {
            target
          } = event;
          if (elementData.userValue) {
            target.value = elementData.userValue;
          }
          elementData.lastCommittedValue = target.value;
          elementData.commitKey = 1;
        });
        element.addEventListener("updatefromsandbox", jsEvent => {
          const actions = {
            value(event) {
              elementData.userValue = event.detail.value ?? "";
              storage.setValue(id, {
                value: elementData.userValue.toString()
              });
              event.target.value = elementData.userValue;
            },
            formattedValue(event) {
              const {
                formattedValue
              } = event.detail;
              elementData.formattedValue = formattedValue;
              if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
                event.target.value = formattedValue;
              }
              storage.setValue(id, {
                formattedValue
              });
            },
            selRange(event) {
              event.target.setSelectionRange(...event.detail.selRange);
            },
            charLimit: event => {
              const {
                charLimit
              } = event.detail;
              const {
                target
              } = event;
              if (charLimit === 0) {
                target.removeAttribute("maxLength");
                return;
              }
              target.setAttribute("maxLength", charLimit);
              let value = elementData.userValue;
              if (!value || value.length <= charLimit) {
                return;
              }
              value = value.slice(0, charLimit);
              target.value = elementData.userValue = value;
              storage.setValue(id, {
                value
              });
              this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
                source: this,
                detail: {
                  id,
                  name: "Keystroke",
                  value,
                  willCommit: true,
                  commitKey: 1,
                  selStart: target.selectionStart,
                  selEnd: target.selectionEnd
                }
              });
            }
          };
          this._dispatchEventFromSandbox(actions, jsEvent);
        });
        element.addEventListener("keydown", event => {
          elementData.commitKey = 1;
          let commitKey = -1;
          if (event.key === "Escape") {
            commitKey = 0;
          } else if (event.key === "Enter" && !this.data.multiLine) {
            commitKey = 2;
          } else if (event.key === "Tab") {
            elementData.commitKey = 3;
          }
          if (commitKey === -1) {
            return;
          }
          const {
            value
          } = event.target;
          if (elementData.lastCommittedValue === value) {
            return;
          }
          elementData.lastCommittedValue = value;
          elementData.userValue = value;
          this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
            source: this,
            detail: {
              id,
              name: "Keystroke",
              value,
              willCommit: true,
              commitKey,
              selStart: event.target.selectionStart,
              selEnd: event.target.selectionEnd
            }
          });
        });
        const _blurListener = blurListener;
        blurListener = null;
        element.addEventListener("blur", event => {
          if (!event.relatedTarget) {
            return;
          }
          const {
            value
          } = event.target;
          elementData.userValue = value;
          if (elementData.lastCommittedValue !== value) {
            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
              source: this,
              detail: {
                id,
                name: "Keystroke",
                value,
                willCommit: true,
                commitKey: elementData.commitKey,
                selStart: event.target.selectionStart,
                selEnd: event.target.selectionEnd
              }
            });
          }
          _blurListener(event);
        });
        if (this.data.actions?.Keystroke) {
          element.addEventListener("beforeinput", event => {
            elementData.lastCommittedValue = null;
            const {
              data,
              target
            } = event;
            const {
              value,
              selectionStart,
              selectionEnd
            } = target;
            let selStart = selectionStart,
              selEnd = selectionEnd;
            switch (event.inputType) {
              case "deleteWordBackward":
                {
                  const match = value.substring(0, selectionStart).match(/\w*[^\w]*$/);
                  if (match) {
                    selStart -= match[0].length;
                  }
                  break;
                }
              case "deleteWordForward":
                {
                  const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
                  if (match) {
                    selEnd += match[0].length;
                  }
                  break;
                }
              case "deleteContentBackward":
                if (selectionStart === selectionEnd) {
                  selStart -= 1;
                }
                break;
              case "deleteContentForward":
                if (selectionStart === selectionEnd) {
                  selEnd += 1;
                }
                break;
            }
            event.preventDefault();
            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
              source: this,
              detail: {
                id,
                name: "Keystroke",
                value,
                change: data || "",
                willCommit: false,
                selStart,
                selEnd
              }
            });
          });
        }
        this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
      }
      if (blurListener) {
        element.addEventListener("blur", blurListener);
      }
      if (this.data.comb) {
        const fieldWidth = this.data.rect[2] - this.data.rect[0];
        const combWidth = fieldWidth / maxLen;
        element.classList.add("comb");
        element.style.letterSpacing = `calc(${combWidth}px * var(--scale-factor) - 1ch)`;
      }
    } else {
      element = document.createElement("div");
      element.textContent = this.data.fieldValue;
      element.style.verticalAlign = "middle";
      element.style.display = "table-cell";
    }
    this._setTextStyle(element);
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
}
class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    const storage = this.annotationStorage;
    const data = this.data;
    const id = data.id;
    let value = storage.getValue(id, {
      value: data.exportValue === data.fieldValue
    }).value;
    if (typeof value === "string") {
      value = value !== "Off";
      storage.setValue(id, {
        value
      });
    }
    this.container.className = "buttonWidgetAnnotation checkBox";
    const element = document.createElement("input");
    GetElementsByNameSet.add(element);
    element.setAttribute("data-element-id", id);
    element.disabled = data.readOnly;
    this._setRequired(element, this.data.required);
    element.type = "checkbox";
    element.name = data.fieldName;
    if (value) {
      element.setAttribute("checked", true);
    }
    element.setAttribute("exportValue", data.exportValue);
    element.tabIndex = DEFAULT_TAB_INDEX;
    element.addEventListener("change", event => {
      const {
        name,
        checked
      } = event.target;
      for (const checkbox of this._getElementsByName(name, id)) {
        const curChecked = checked && checkbox.exportValue === data.exportValue;
        if (checkbox.domElement) {
          checkbox.domElement.checked = curChecked;
        }
        storage.setValue(checkbox.id, {
          value: curChecked
        });
      }
      storage.setValue(id, {
        value: checked
      });
    });
    element.addEventListener("resetform", event => {
      const defaultValue = data.defaultFieldValue || "Off";
      event.target.checked = defaultValue === data.exportValue;
    });
    if (this.enableScripting && this.hasJSActions) {
      element.addEventListener("updatefromsandbox", jsEvent => {
        const actions = {
          value(event) {
            event.target.checked = event.detail.value !== "Off";
            storage.setValue(id, {
              value: event.target.checked
            });
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
    }
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
}
class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    this.container.className = "buttonWidgetAnnotation radioButton";
    const storage = this.annotationStorage;
    const data = this.data;
    const id = data.id;
    let value = storage.getValue(id, {
      value: data.fieldValue === data.buttonValue
    }).value;
    if (typeof value === "string") {
      value = value !== data.buttonValue;
      storage.setValue(id, {
        value
      });
    }
    const element = document.createElement("input");
    GetElementsByNameSet.add(element);
    element.setAttribute("data-element-id", id);
    element.disabled = data.readOnly;
    this._setRequired(element, this.data.required);
    element.type = "radio";
    element.name = data.fieldName;
    if (value) {
      element.setAttribute("checked", true);
    }
    element.tabIndex = DEFAULT_TAB_INDEX;
    element.addEventListener("change", event => {
      const {
        name,
        checked
      } = event.target;
      for (const radio of this._getElementsByName(name, id)) {
        storage.setValue(radio.id, {
          value: false
        });
      }
      storage.setValue(id, {
        value: checked
      });
    });
    element.addEventListener("resetform", event => {
      const defaultValue = data.defaultFieldValue;
      event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
    });
    if (this.enableScripting && this.hasJSActions) {
      const pdfButtonValue = data.buttonValue;
      element.addEventListener("updatefromsandbox", jsEvent => {
        const actions = {
          value: event => {
            const checked = pdfButtonValue === event.detail.value;
            for (const radio of this._getElementsByName(event.target.name)) {
              const curChecked = checked && radio.id === id;
              if (radio.domElement) {
                radio.domElement.checked = curChecked;
              }
              storage.setValue(radio.id, {
                value: curChecked
              });
            }
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
    }
    this._setBackgroundColor(element);
    this._setDefaultPropertiesFromJS(element);
    this.container.append(element);
    return this.container;
  }
}
class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      ignoreBorder: parameters.data.hasAppearance
    });
  }
  render() {
    const container = super.render();
    container.className = "buttonWidgetAnnotation pushButton";
    if (this.data.alternativeText) {
      container.title = this.data.alternativeText;
    }
    const linkElement = container.lastChild;
    if (this.enableScripting && this.hasJSActions && linkElement) {
      this._setDefaultPropertiesFromJS(linkElement);
      linkElement.addEventListener("updatefromsandbox", jsEvent => {
        this._dispatchEventFromSandbox({}, jsEvent);
      });
    }
    return container;
  }
}
class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: parameters.renderForms
    });
  }
  render() {
    this.container.className = "choiceWidgetAnnotation";
    const storage = this.annotationStorage;
    const id = this.data.id;
    const storedData = storage.getValue(id, {
      value: this.data.fieldValue
    });
    const selectElement = document.createElement("select");
    GetElementsByNameSet.add(selectElement);
    selectElement.setAttribute("data-element-id", id);
    selectElement.disabled = this.data.readOnly;
    this._setRequired(selectElement, this.data.required);
    selectElement.name = this.data.fieldName;
    selectElement.tabIndex = DEFAULT_TAB_INDEX;
    let addAnEmptyEntry = this.data.combo && this.data.options.length > 0;
    if (!this.data.combo) {
      selectElement.size = this.data.options.length;
      if (this.data.multiSelect) {
        selectElement.multiple = true;
      }
    }
    selectElement.addEventListener("resetform", event => {
      const defaultValue = this.data.defaultFieldValue;
      for (const option of selectElement.options) {
        option.selected = option.value === defaultValue;
      }
    });
    for (const option of this.data.options) {
      const optionElement = document.createElement("option");
      optionElement.textContent = option.displayValue;
      optionElement.value = option.exportValue;
      if (storedData.value.includes(option.exportValue)) {
        optionElement.setAttribute("selected", true);
        addAnEmptyEntry = false;
      }
      selectElement.append(optionElement);
    }
    let removeEmptyEntry = null;
    if (addAnEmptyEntry) {
      const noneOptionElement = document.createElement("option");
      noneOptionElement.value = " ";
      noneOptionElement.setAttribute("hidden", true);
      noneOptionElement.setAttribute("selected", true);
      selectElement.prepend(noneOptionElement);
      removeEmptyEntry = () => {
        noneOptionElement.remove();
        selectElement.removeEventListener("input", removeEmptyEntry);
        removeEmptyEntry = null;
      };
      selectElement.addEventListener("input", removeEmptyEntry);
    }
    const getValue = isExport => {
      const name = isExport ? "value" : "textContent";
      const {
        options,
        multiple
      } = selectElement;
      if (!multiple) {
        return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
      }
      return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
    };
    let selectedValues = getValue(false);
    const getItems = event => {
      const options = event.target.options;
      return Array.prototype.map.call(options, option => {
        return {
          displayValue: option.textContent,
          exportValue: option.value
        };
      });
    };
    if (this.enableScripting && this.hasJSActions) {
      selectElement.addEventListener("updatefromsandbox", jsEvent => {
        const actions = {
          value(event) {
            removeEmptyEntry?.();
            const value = event.detail.value;
            const values = new Set(Array.isArray(value) ? value : [value]);
            for (const option of selectElement.options) {
              option.selected = values.has(option.value);
            }
            storage.setValue(id, {
              value: getValue(true)
            });
            selectedValues = getValue(false);
          },
          multipleSelection(event) {
            selectElement.multiple = true;
          },
          remove(event) {
            const options = selectElement.options;
            const index = event.detail.remove;
            options[index].selected = false;
            selectElement.remove(index);
            if (options.length > 0) {
              const i = Array.prototype.findIndex.call(options, option => option.selected);
              if (i === -1) {
                options[0].selected = true;
              }
            }
            storage.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          clear(event) {
            while (selectElement.length !== 0) {
              selectElement.remove(0);
            }
            storage.setValue(id, {
              value: null,
              items: []
            });
            selectedValues = getValue(false);
          },
          insert(event) {
            const {
              index,
              displayValue,
              exportValue
            } = event.detail.insert;
            const selectChild = selectElement.children[index];
            const optionElement = document.createElement("option");
            optionElement.textContent = displayValue;
            optionElement.value = exportValue;
            if (selectChild) {
              selectChild.before(optionElement);
            } else {
              selectElement.append(optionElement);
            }
            storage.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          items(event) {
            const {
              items
            } = event.detail;
            while (selectElement.length !== 0) {
              selectElement.remove(0);
            }
            for (const item of items) {
              const {
                displayValue,
                exportValue
              } = item;
              const optionElement = document.createElement("option");
              optionElement.textContent = displayValue;
              optionElement.value = exportValue;
              selectElement.append(optionElement);
            }
            if (selectElement.options.length > 0) {
              selectElement.options[0].selected = true;
            }
            storage.setValue(id, {
              value: getValue(true),
              items: getItems(event)
            });
            selectedValues = getValue(false);
          },
          indices(event) {
            const indices = new Set(event.detail.indices);
            for (const option of event.target.options) {
              option.selected = indices.has(option.index);
            }
            storage.setValue(id, {
              value: getValue(true)
            });
            selectedValues = getValue(false);
          },
          editable(event) {
            event.target.disabled = !event.detail.editable;
          }
        };
        this._dispatchEventFromSandbox(actions, jsEvent);
      });
      selectElement.addEventListener("input", event => {
        const exportValue = getValue(true);
        storage.setValue(id, {
          value: exportValue
        });
        event.preventDefault();
        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
          source: this,
          detail: {
            id,
            name: "Keystroke",
            value: selectedValues,
            changeEx: exportValue,
            willCommit: false,
            commitKey: 1,
            keyDown: false
          }
        });
      });
      this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked);
    } else {
      selectElement.addEventListener("input", function (event) {
        storage.setValue(id, {
          value: getValue(true)
        });
      });
    }
    if (this.data.combo) {
      this._setTextStyle(selectElement);
    } else {}
    this._setBackgroundColor(selectElement);
    this._setDefaultPropertiesFromJS(selectElement);
    this.container.append(selectElement);
    return this.container;
  }
}
class PopupAnnotationElement extends AnnotationElement {
  static IGNORE_TYPES = new Set(["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"]);
  constructor(parameters) {
    const {
      data
    } = parameters;
    const isRenderable = !PopupAnnotationElement.IGNORE_TYPES.has(data.parentType) && !!(data.titleObj?.str || data.contentsObj?.str || data.richText?.str);
    super(parameters, {
      isRenderable
    });
  }
  render() {
    this.container.className = "popupAnnotation";
    const parentElements = this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);
    if (parentElements.length === 0) {
      return this.container;
    }
    const popup = new PopupElement({
      container: this.container,
      trigger: Array.from(parentElements),
      color: this.data.color,
      titleObj: this.data.titleObj,
      modificationDate: this.data.modificationDate,
      contentsObj: this.data.contentsObj,
      richText: this.data.richText
    });
    const page = this.page;
    const rect = _util.Util.normalizeRect([this.data.parentRect[0], page.view[3] - this.data.parentRect[1] + page.view[1], this.data.parentRect[2], page.view[3] - this.data.parentRect[3] + page.view[1]]);
    const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
    const popupTop = rect[1];
    const {
      pageWidth,
      pageHeight,
      pageX,
      pageY
    } = this.viewport.rawDims;
    this.container.style.left = `${100 * (popupLeft - pageX) / pageWidth}%`;
    this.container.style.top = `${100 * (popupTop - pageY) / pageHeight}%`;
    this.container.append(popup.render());
    return this.container;
  }
}
class PopupElement {
  constructor(parameters) {
    this.container = parameters.container;
    this.trigger = parameters.trigger;
    this.color = parameters.color;
    this.titleObj = parameters.titleObj;
    this.modificationDate = parameters.modificationDate;
    this.contentsObj = parameters.contentsObj;
    this.richText = parameters.richText;
    this.hideWrapper = parameters.hideWrapper || false;
    this.pinned = false;
  }
  render() {
    const BACKGROUND_ENLIGHT = 0.7;
    const wrapper = document.createElement("div");
    wrapper.className = "popupWrapper";
    this.hideElement = this.hideWrapper ? wrapper : this.container;
    this.hideElement.hidden = true;
    const popup = document.createElement("div");
    popup.className = "popup";
    const color = this.color;
    if (color) {
      const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
      const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
      const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
      popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
    }
    const title = document.createElement("h1");
    title.dir = this.titleObj.dir;
    title.textContent = this.titleObj.str;
    popup.append(title);
    const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
    if (dateObject) {
      const modificationDate = document.createElement("span");
      modificationDate.className = "popupDate";
      modificationDate.textContent = "{{date}}, {{time}}";
      modificationDate.dataset.l10nId = "annotation_date_string";
      modificationDate.dataset.l10nArgs = JSON.stringify({
        date: dateObject.toLocaleDateString(),
        time: dateObject.toLocaleTimeString()
      });
      popup.append(modificationDate);
    }
    if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
      _xfa_layer.XfaLayer.render({
        xfaHtml: this.richText.html,
        intent: "richText",
        div: popup
      });
      popup.lastChild.className = "richText popupContent";
    } else {
      const contents = this._formatContents(this.contentsObj);
      popup.append(contents);
    }
    if (!Array.isArray(this.trigger)) {
      this.trigger = [this.trigger];
    }
    for (const element of this.trigger) {
      element.addEventListener("click", this._toggle.bind(this));
      element.addEventListener("mouseover", this._show.bind(this, false));
      element.addEventListener("mouseout", this._hide.bind(this, false));
    }
    popup.addEventListener("click", this._hide.bind(this, true));
    wrapper.append(popup);
    return wrapper;
  }
  _formatContents({
    str,
    dir
  }) {
    const p = document.createElement("p");
    p.className = "popupContent";
    p.dir = dir;
    const lines = str.split(/(?:\r\n?|\n)/);
    for (let i = 0, ii = lines.length; i < ii; ++i) {
      const line = lines[i];
      p.append(document.createTextNode(line));
      if (i < ii - 1) {
        p.append(document.createElement("br"));
      }
    }
    return p;
  }
  _toggle() {
    if (this.pinned) {
      this._hide(true);
    } else {
      this._show(true);
    }
  }
  _show(pin = false) {
    if (pin) {
      this.pinned = true;
    }
    if (this.hideElement.hidden) {
      this.hideElement.hidden = false;
      this.container.style.zIndex = parseInt(this.container.style.zIndex) + 1000;
    }
  }
  _hide(unpin = true) {
    if (unpin) {
      this.pinned = false;
    }
    if (!this.hideElement.hidden && !this.pinned) {
      this.hideElement.hidden = true;
      this.container.style.zIndex = parseInt(this.container.style.zIndex) - 1000;
    }
  }
}
class FreeTextAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
    this.textContent = parameters.data.textContent;
  }
  render() {
    this.container.className = "freeTextAnnotation";
    if (this.textContent) {
      const content = document.createElement("div");
      content.className = "annotationTextContent";
      content.setAttribute("role", "comment");
      for (const line of this.textContent) {
        const lineSpan = document.createElement("span");
        lineSpan.textContent = line;
        content.append(lineSpan);
      }
      this.container.append(content);
    }
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    return this.container;
  }
}
class LineAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
  }
  render() {
    this.container.className = "lineAnnotation";
    const data = this.data;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const svg = this.svgFactory.create(width, height, true);
    const line = this.svgFactory.createElement("svg:line");
    line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
    line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
    line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
    line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
    line.setAttribute("stroke-width", data.borderStyle.width || 1);
    line.setAttribute("stroke", "transparent");
    line.setAttribute("fill", "transparent");
    svg.append(line);
    this.container.append(svg);
    this._createPopup(line, data);
    return this.container;
  }
}
class SquareAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
  }
  render() {
    this.container.className = "squareAnnotation";
    const data = this.data;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const svg = this.svgFactory.create(width, height, true);
    const borderWidth = data.borderStyle.width;
    const square = this.svgFactory.createElement("svg:rect");
    square.setAttribute("x", borderWidth / 2);
    square.setAttribute("y", borderWidth / 2);
    square.setAttribute("width", width - borderWidth);
    square.setAttribute("height", height - borderWidth);
    square.setAttribute("stroke-width", borderWidth || 1);
    square.setAttribute("stroke", "transparent");
    square.setAttribute("fill", "transparent");
    svg.append(square);
    this.container.append(svg);
    this._createPopup(square, data);
    return this.container;
  }
}
class CircleAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
  }
  render() {
    this.container.className = "circleAnnotation";
    const data = this.data;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const svg = this.svgFactory.create(width, height, true);
    const borderWidth = data.borderStyle.width;
    const circle = this.svgFactory.createElement("svg:ellipse");
    circle.setAttribute("cx", width / 2);
    circle.setAttribute("cy", height / 2);
    circle.setAttribute("rx", width / 2 - borderWidth / 2);
    circle.setAttribute("ry", height / 2 - borderWidth / 2);
    circle.setAttribute("stroke-width", borderWidth || 1);
    circle.setAttribute("stroke", "transparent");
    circle.setAttribute("fill", "transparent");
    svg.append(circle);
    this.container.append(svg);
    this._createPopup(circle, data);
    return this.container;
  }
}
class PolylineAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
    this.containerClassName = "polylineAnnotation";
    this.svgElementName = "svg:polyline";
  }
  render() {
    this.container.className = this.containerClassName;
    const data = this.data;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const svg = this.svgFactory.create(width, height, true);
    let points = [];
    for (const coordinate of data.vertices) {
      const x = coordinate.x - data.rect[0];
      const y = data.rect[3] - coordinate.y;
      points.push(x + "," + y);
    }
    points = points.join(" ");
    const polyline = this.svgFactory.createElement(this.svgElementName);
    polyline.setAttribute("points", points);
    polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
    polyline.setAttribute("stroke", "transparent");
    polyline.setAttribute("fill", "transparent");
    svg.append(polyline);
    this.container.append(svg);
    this._createPopup(polyline, data);
    return this.container;
  }
}
class PolygonAnnotationElement extends PolylineAnnotationElement {
  constructor(parameters) {
    super(parameters);
    this.containerClassName = "polygonAnnotation";
    this.svgElementName = "svg:polygon";
  }
}
class CaretAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
  }
  render() {
    this.container.className = "caretAnnotation";
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    return this.container;
  }
}
class InkAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
    this.containerClassName = "inkAnnotation";
    this.svgElementName = "svg:polyline";
  }
  render() {
    this.container.className = this.containerClassName;
    const data = this.data;
    const {
      width,
      height
    } = getRectDims(data.rect);
    const svg = this.svgFactory.create(width, height, true);
    for (const inkList of data.inkLists) {
      let points = [];
      for (const coordinate of inkList) {
        const x = coordinate.x - data.rect[0];
        const y = data.rect[3] - coordinate.y;
        points.push(`${x},${y}`);
      }
      points = points.join(" ");
      const polyline = this.svgFactory.createElement(this.svgElementName);
      polyline.setAttribute("points", points);
      polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
      polyline.setAttribute("stroke", "transparent");
      polyline.setAttribute("fill", "transparent");
      this._createPopup(polyline, data);
      svg.append(polyline);
    }
    this.container.append(svg);
    return this.container;
  }
}
class HighlightAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    if (this.quadrilaterals) {
      return this._renderQuadrilaterals("highlightAnnotation");
    }
    this.container.className = "highlightAnnotation";
    return this.container;
  }
}
class UnderlineAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    if (this.quadrilaterals) {
      return this._renderQuadrilaterals("underlineAnnotation");
    }
    this.container.className = "underlineAnnotation";
    return this.container;
  }
}
class SquigglyAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    if (this.quadrilaterals) {
      return this._renderQuadrilaterals("squigglyAnnotation");
    }
    this.container.className = "squigglyAnnotation";
    return this.container;
  }
}
class StrikeOutAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true,
      createQuadrilaterals: true
    });
  }
  render() {
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    if (this.quadrilaterals) {
      return this._renderQuadrilaterals("strikeoutAnnotation");
    }
    this.container.className = "strikeoutAnnotation";
    return this.container;
  }
}
class StampAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
    super(parameters, {
      isRenderable,
      ignoreBorder: true
    });
  }
  render() {
    this.container.className = "stampAnnotation";
    if (!this.data.hasPopup) {
      this._createPopup(null, this.data);
    }
    return this.container;
  }
}
class FileAttachmentAnnotationElement extends AnnotationElement {
  constructor(parameters) {
    super(parameters, {
      isRenderable: true
    });
    const {
      filename,
      content
    } = this.data.file;
    this.filename = (0, _display_utils.getFilenameFromUrl)(filename, true);
    this.content = content;
    this.linkService.eventBus?.dispatch("fileattachmentannotation", {
      source: this,
      filename,
      content
    });
  }
  render() {
    this.container.className = "fileAttachmentAnnotation";
    let trigger;
    if (this.data.hasAppearance) {
      trigger = document.createElement("div");
    } else {
      trigger = document.createElement("img");
      trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(this.data.name) ? "paperclip" : "pushpin"}.svg`;
    }
    trigger.className = "popupTriggerArea";
    trigger.addEventListener("dblclick", this._download.bind(this));
    if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
      this._createPopup(trigger, this.data);
    }
    this.container.append(trigger);
    return this.container;
  }
  _download() {
    this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
  }
}
class AnnotationLayer {
  static #appendElement(element, id, div, accessibilityManager) {
    const contentElement = element.firstChild || element;
    contentElement.id = `${_display_utils.AnnotationPrefix}${id}`;
    div.append(element);
    accessibilityManager?.moveElementInDOM(div, element, contentElement, false);
  }
  static render(params) {
    const {
      annotations,
      div,
      viewport,
      accessibilityManager
    } = params;
    (0, _display_utils.setLayerDimensions)(div, viewport);
    const elementParams = {
      data: null,
      layer: div,
      page: params.page,
      viewport,
      linkService: params.linkService,
      downloadManager: params.downloadManager,
      imageResourcesPath: params.imageResourcesPath || "",
      renderForms: params.renderForms !== false,
      svgFactory: new _display_utils.DOMSVGFactory(),
      annotationStorage: params.annotationStorage || new _annotation_storage.AnnotationStorage(),
      enableScripting: params.enableScripting === true,
      hasJSActions: params.hasJSActions,
      fieldObjects: params.fieldObjects
    };
    let zIndex = 0;
    for (const data of annotations) {
      if (data.annotationType !== _util.AnnotationType.POPUP) {
        const {
          width,
          height
        } = getRectDims(data.rect);
        if (width <= 0 || height <= 0) {
          continue;
        }
      }
      elementParams.data = data;
      const element = AnnotationElementFactory.create(elementParams);
      if (!element.isRenderable) {
        continue;
      }
      const rendered = element.render();
      if (data.hidden) {
        rendered.style.visibility = "hidden";
      }
      if (Array.isArray(rendered)) {
        for (const renderedElement of rendered) {
          renderedElement.style.zIndex = zIndex++;
          AnnotationLayer.#appendElement(renderedElement, data.id, div, accessibilityManager);
        }
      } else {
        rendered.style.zIndex = zIndex++;
        if (element instanceof PopupAnnotationElement) {
          div.prepend(rendered);
        } else {
          AnnotationLayer.#appendElement(rendered, data.id, div, accessibilityManager);
        }
      }
    }
    this.#setAnnotationCanvasMap(div, params.annotationCanvasMap);
  }
  static update(params) {
    const {
      annotationCanvasMap,
      div,
      viewport
    } = params;
    (0, _display_utils.setLayerDimensions)(div, {
      rotation: viewport.rotation
    });
    this.#setAnnotationCanvasMap(div, annotationCanvasMap);
    div.hidden = false;
  }
  static #setAnnotationCanvasMap(div, annotationCanvasMap) {
    if (!annotationCanvasMap) {
      return;
    }
    for (const [id, canvas] of annotationCanvasMap) {
      const element = div.querySelector(`[data-annotation-id="${id}"]`);
      if (!element) {
        continue;
      }
      const {
        firstChild
      } = element;
      if (!firstChild) {
        element.append(canvas);
      } else if (firstChild.nodeName === "CANVAS") {
        firstChild.replaceWith(canvas);
      } else {
        firstChild.before(canvas);
      }
    }
    annotationCanvasMap.clear();
  }
}
exports.AnnotationLayer = AnnotationLayer;

/***/ }),
/* 33 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ColorConverters = void 0;
function makeColorComp(n) {
  return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
}
class ColorConverters {
  static CMYK_G([c, y, m, k]) {
    return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
  }
  static G_CMYK([g]) {
    return ["CMYK", 0, 0, 0, 1 - g];
  }
  static G_RGB([g]) {
    return ["RGB", g, g, g];
  }
  static G_HTML([g]) {
    const G = makeColorComp(g);
    return `#${G}${G}${G}`;
  }
  static RGB_G([r, g, b]) {
    return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
  }
  static RGB_HTML([r, g, b]) {
    const R = makeColorComp(r);
    const G = makeColorComp(g);
    const B = makeColorComp(b);
    return `#${R}${G}${B}`;
  }
  static T_HTML() {
    return "#00000000";
  }
  static CMYK_RGB([c, y, m, k]) {
    return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
  }
  static CMYK_HTML(components) {
    const rgb = this.CMYK_RGB(components).slice(1);
    return this.RGB_HTML(rgb);
  }
  static RGB_CMYK([r, g, b]) {
    const c = 1 - r;
    const m = 1 - g;
    const y = 1 - b;
    const k = Math.min(c, m, y);
    return ["CMYK", c, m, y, k];
  }
}
exports.ColorConverters = ColorConverters;

/***/ }),
/* 34 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XfaLayer = void 0;
var _xfa_text = __w_pdfjs_require__(19);
class XfaLayer {
  static setupStorage(html, id, element, storage, intent) {
    const storedData = storage.getValue(id, {
      value: null
    });
    switch (element.name) {
      case "textarea":
        if (storedData.value !== null) {
          html.textContent = storedData.value;
        }
        if (intent === "print") {
          break;
        }
        html.addEventListener("input", event => {
          storage.setValue(id, {
            value: event.target.value
          });
        });
        break;
      case "input":
        if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
          if (storedData.value === element.attributes.xfaOn) {
            html.setAttribute("checked", true);
          } else if (storedData.value === element.attributes.xfaOff) {
            html.removeAttribute("checked");
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("change", event => {
            storage.setValue(id, {
              value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
            });
          });
        } else {
          if (storedData.value !== null) {
            html.setAttribute("value", storedData.value);
          }
          if (intent === "print") {
            break;
          }
          html.addEventListener("input", event => {
            storage.setValue(id, {
              value: event.target.value
            });
          });
        }
        break;
      case "select":
        if (storedData.value !== null) {
          for (const option of element.children) {
            if (option.attributes.value === storedData.value) {
              option.attributes.selected = true;
            }
          }
        }
        html.addEventListener("input", event => {
          const options = event.target.options;
          const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
          storage.setValue(id, {
            value
          });
        });
        break;
    }
  }
  static setAttributes({
    html,
    element,
    storage = null,
    intent,
    linkService
  }) {
    const {
      attributes
    } = element;
    const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
    if (attributes.type === "radio") {
      attributes.name = `${attributes.name}-${intent}`;
    }
    for (const [key, value] of Object.entries(attributes)) {
      if (value === null || value === undefined) {
        continue;
      }
      switch (key) {
        case "class":
          if (value.length) {
            html.setAttribute(key, value.join(" "));
          }
          break;
        case "dataId":
          break;
        case "id":
          html.setAttribute("data-element-id", value);
          break;
        case "style":
          Object.assign(html.style, value);
          break;
        case "textContent":
          html.textContent = value;
          break;
        default:
          if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") {
            html.setAttribute(key, value);
          }
      }
    }
    if (isHTMLAnchorElement) {
      linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
    }
    if (storage && attributes.dataId) {
      this.setupStorage(html, attributes.dataId, element, storage);
    }
  }
  static render(parameters) {
    const storage = parameters.annotationStorage;
    const linkService = parameters.linkService;
    const root = parameters.xfaHtml;
    const intent = parameters.intent || "display";
    const rootHtml = document.createElement(root.name);
    if (root.attributes) {
      this.setAttributes({
        html: rootHtml,
        element: root,
        intent,
        linkService
      });
    }
    const stack = [[root, -1, rootHtml]];
    const rootDiv = parameters.div;
    rootDiv.append(rootHtml);
    if (parameters.viewport) {
      const transform = `matrix(${parameters.viewport.transform.join(",")})`;
      rootDiv.style.transform = transform;
    }
    if (intent !== "richText") {
      rootDiv.setAttribute("class", "xfaLayer xfaFont");
    }
    const textDivs = [];
    while (stack.length > 0) {
      const [parent, i, html] = stack.at(-1);
      if (i + 1 === parent.children.length) {
        stack.pop();
        continue;
      }
      const child = parent.children[++stack.at(-1)[1]];
      if (child === null) {
        continue;
      }
      const {
        name
      } = child;
      if (name === "#text") {
        const node = document.createTextNode(child.value);
        textDivs.push(node);
        html.append(node);
        continue;
      }
      let childHtml;
      if (child?.attributes?.xmlns) {
        childHtml = document.createElementNS(child.attributes.xmlns, name);
      } else {
        childHtml = document.createElement(name);
      }
      html.append(childHtml);
      if (child.attributes) {
        this.setAttributes({
          html: childHtml,
          element: child,
          storage,
          intent,
          linkService
        });
      }
      if (child.children && child.children.length > 0) {
        stack.push([child, -1, childHtml]);
      } else if (child.value) {
        const node = document.createTextNode(child.value);
        if (_xfa_text.XfaText.shouldBuildText(name)) {
          textDivs.push(node);
        }
        childHtml.append(node);
      }
    }
    for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
      el.setAttribute("readOnly", true);
    }
    return {
      textDivs
    };
  }
  static update(parameters) {
    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
    parameters.div.style.transform = transform;
    parameters.div.hidden = false;
  }
}
exports.XfaLayer = XfaLayer;

/***/ }),
/* 35 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.SVGGraphics = void 0;
var _display_utils = __w_pdfjs_require__(6);
var _util = __w_pdfjs_require__(1);
var _is_node = __w_pdfjs_require__(10);
let SVGGraphics = class {
  constructor() {
    (0, _util.unreachable)("Not implemented: SVGGraphics");
  }
};
exports.SVGGraphics = SVGGraphics;
{
  const SVG_DEFAULTS = {
    fontStyle: "normal",
    fontWeight: "normal",
    fillColor: "#000000"
  };
  const XML_NS = "http://www.w3.org/XML/1998/namespace";
  const XLINK_NS = "http://www.w3.org/1999/xlink";
  const LINE_CAP_STYLES = ["butt", "round", "square"];
  const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
  const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
    if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
      return URL.createObjectURL(new Blob([data], {
        type: contentType
      }));
    }
    const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    let buffer = `data:${contentType};base64,`;
    for (let i = 0, ii = data.length; i < ii; i += 3) {
      const b1 = data[i] & 0xff;
      const b2 = data[i + 1] & 0xff;
      const b3 = data[i + 2] & 0xff;
      const d1 = b1 >> 2,
        d2 = (b1 & 3) << 4 | b2 >> 4;
      const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
      const d4 = i + 2 < ii ? b3 & 0x3f : 64;
      buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
    }
    return buffer;
  };
  const convertImgDataToPng = function () {
    const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
    const CHUNK_WRAPPER_SIZE = 12;
    const crcTable = new Int32Array(256);
    for (let i = 0; i < 256; i++) {
      let c = i;
      for (let h = 0; h < 8; h++) {
        if (c & 1) {
          c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
        } else {
          c = c >> 1 & 0x7fffffff;
        }
      }
      crcTable[i] = c;
    }
    function crc32(data, start, end) {
      let crc = -1;
      for (let i = start; i < end; i++) {
        const a = (crc ^ data[i]) & 0xff;
        const b = crcTable[a];
        crc = crc >>> 8 ^ b;
      }
      return crc ^ -1;
    }
    function writePngChunk(type, body, data, offset) {
      let p = offset;
      const len = body.length;
      data[p] = len >> 24 & 0xff;
      data[p + 1] = len >> 16 & 0xff;
      data[p + 2] = len >> 8 & 0xff;
      data[p + 3] = len & 0xff;
      p += 4;
      data[p] = type.charCodeAt(0) & 0xff;
      data[p + 1] = type.charCodeAt(1) & 0xff;
      data[p + 2] = type.charCodeAt(2) & 0xff;
      data[p + 3] = type.charCodeAt(3) & 0xff;
      p += 4;
      data.set(body, p);
      p += body.length;
      const crc = crc32(data, offset + 4, p);
      data[p] = crc >> 24 & 0xff;
      data[p + 1] = crc >> 16 & 0xff;
      data[p + 2] = crc >> 8 & 0xff;
      data[p + 3] = crc & 0xff;
    }
    function adler32(data, start, end) {
      let a = 1;
      let b = 0;
      for (let i = start; i < end; ++i) {
        a = (a + (data[i] & 0xff)) % 65521;
        b = (b + a) % 65521;
      }
      return b << 16 | a;
    }
    function deflateSync(literals) {
      if (!_is_node.isNodeJS) {
        return deflateSyncUncompressed(literals);
      }
      try {
        let input;
        if (parseInt(process.versions.node) >= 8) {
          input = literals;
        } else {
          input = Buffer.from(literals);
        }
        const output = require("zlib").deflateSync(input, {
          level: 9
        });
        return output instanceof Uint8Array ? output : new Uint8Array(output);
      } catch (e) {
        (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
      }
      return deflateSyncUncompressed(literals);
    }
    function deflateSyncUncompressed(literals) {
      let len = literals.length;
      const maxBlockLength = 0xffff;
      const deflateBlocks = Math.ceil(len / maxBlockLength);
      const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
      let pi = 0;
      idat[pi++] = 0x78;
      idat[pi++] = 0x9c;
      let pos = 0;
      while (len > maxBlockLength) {
        idat[pi++] = 0x00;
        idat[pi++] = 0xff;
        idat[pi++] = 0xff;
        idat[pi++] = 0x00;
        idat[pi++] = 0x00;
        idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
        pi += maxBlockLength;
        pos += maxBlockLength;
        len -= maxBlockLength;
      }
      idat[pi++] = 0x01;
      idat[pi++] = len & 0xff;
      idat[pi++] = len >> 8 & 0xff;
      idat[pi++] = ~len & 0xffff & 0xff;
      idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
      idat.set(literals.subarray(pos), pi);
      pi += literals.length - pos;
      const adler = adler32(literals, 0, literals.length);
      idat[pi++] = adler >> 24 & 0xff;
      idat[pi++] = adler >> 16 & 0xff;
      idat[pi++] = adler >> 8 & 0xff;
      idat[pi++] = adler & 0xff;
      return idat;
    }
    function encode(imgData, kind, forceDataSchema, isMask) {
      const width = imgData.width;
      const height = imgData.height;
      let bitDepth, colorType, lineSize;
      const bytes = imgData.data;
      switch (kind) {
        case _util.ImageKind.GRAYSCALE_1BPP:
          colorType = 0;
          bitDepth = 1;
          lineSize = width + 7 >> 3;
          break;
        case _util.ImageKind.RGB_24BPP:
          colorType = 2;
          bitDepth = 8;
          lineSize = width * 3;
          break;
        case _util.ImageKind.RGBA_32BPP:
          colorType = 6;
          bitDepth = 8;
          lineSize = width * 4;
          break;
        default:
          throw new Error("invalid format");
      }
      const literals = new Uint8Array((1 + lineSize) * height);
      let offsetLiterals = 0,
        offsetBytes = 0;
      for (let y = 0; y < height; ++y) {
        literals[offsetLiterals++] = 0;
        literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
        offsetBytes += lineSize;
        offsetLiterals += lineSize;
      }
      if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
        offsetLiterals = 0;
        for (let y = 0; y < height; y++) {
          offsetLiterals++;
          for (let i = 0; i < lineSize; i++) {
            literals[offsetLiterals++] ^= 0xff;
          }
        }
      }
      const ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
      const idat = deflateSync(literals);
      const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
      const data = new Uint8Array(pngLength);
      let offset = 0;
      data.set(PNG_HEADER, offset);
      offset += PNG_HEADER.length;
      writePngChunk("IHDR", ihdr, data, offset);
      offset += CHUNK_WRAPPER_SIZE + ihdr.length;
      writePngChunk("IDATA", idat, data, offset);
      offset += CHUNK_WRAPPER_SIZE + idat.length;
      writePngChunk("IEND", new Uint8Array(0), data, offset);
      return createObjectURL(data, "image/png", forceDataSchema);
    }
    return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
      const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
      return encode(imgData, kind, forceDataSchema, isMask);
    };
  }();
  class SVGExtraState {
    constructor() {
      this.fontSizeScale = 1;
      this.fontWeight = SVG_DEFAULTS.fontWeight;
      this.fontSize = 0;
      this.textMatrix = _util.IDENTITY_MATRIX;
      this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
      this.leading = 0;
      this.textRenderingMode = _util.TextRenderingMode.FILL;
      this.textMatrixScale = 1;
      this.x = 0;
      this.y = 0;
      this.lineX = 0;
      this.lineY = 0;
      this.charSpacing = 0;
      this.wordSpacing = 0;
      this.textHScale = 1;
      this.textRise = 0;
      this.fillColor = SVG_DEFAULTS.fillColor;
      this.strokeColor = "#000000";
      this.fillAlpha = 1;
      this.strokeAlpha = 1;
      this.lineWidth = 1;
      this.lineJoin = "";
      this.lineCap = "";
      this.miterLimit = 0;
      this.dashArray = [];
      this.dashPhase = 0;
      this.dependencies = [];
      this.activeClipUrl = null;
      this.clipGroup = null;
      this.maskId = "";
    }
    clone() {
      return Object.create(this);
    }
    setCurrentPoint(x, y) {
      this.x = x;
      this.y = y;
    }
  }
  function opListToTree(opList) {
    let opTree = [];
    const tmp = [];
    for (const opListElement of opList) {
      if (opListElement.fn === "save") {
        opTree.push({
          fnId: 92,
          fn: "group",
          items: []
        });
        tmp.push(opTree);
        opTree = opTree.at(-1).items;
        continue;
      }
      if (opListElement.fn === "restore") {
        opTree = tmp.pop();
      } else {
        opTree.push(opListElement);
      }
    }
    return opTree;
  }
  function pf(value) {
    if (Number.isInteger(value)) {
      return value.toString();
    }
    const s = value.toFixed(10);
    let i = s.length - 1;
    if (s[i] !== "0") {
      return s;
    }
    do {
      i--;
    } while (s[i] === "0");
    return s.substring(0, s[i] === "." ? i : i + 1);
  }
  function pm(m) {
    if (m[4] === 0 && m[5] === 0) {
      if (m[1] === 0 && m[2] === 0) {
        if (m[0] === 1 && m[3] === 1) {
          return "";
        }
        return `scale(${pf(m[0])} ${pf(m[3])})`;
      }
      if (m[0] === m[3] && m[1] === -m[2]) {
        const a = Math.acos(m[0]) * 180 / Math.PI;
        return `rotate(${pf(a)})`;
      }
    } else {
      if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
        return `translate(${pf(m[4])} ${pf(m[5])})`;
      }
    }
    return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
  }
  let clipCount = 0;
  let maskCount = 0;
  let shadingCount = 0;
  exports.SVGGraphics = SVGGraphics = class {
    constructor(commonObjs, objs, forceDataSchema = false) {
      (0, _display_utils.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");
      this.svgFactory = new _display_utils.DOMSVGFactory();
      this.current = new SVGExtraState();
      this.transformMatrix = _util.IDENTITY_MATRIX;
      this.transformStack = [];
      this.extraStack = [];
      this.commonObjs = commonObjs;
      this.objs = objs;
      this.pendingClip = null;
      this.pendingEOFill = false;
      this.embedFonts = false;
      this.embeddedFonts = Object.create(null);
      this.cssStyle = null;
      this.forceDataSchema = !!forceDataSchema;
      this._operatorIdMapping = [];
      for (const op in _util.OPS) {
        this._operatorIdMapping[_util.OPS[op]] = op;
      }
    }
    getObject(data, fallback = null) {
      if (typeof data === "string") {
        return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
      }
      return fallback;
    }
    save() {
      this.transformStack.push(this.transformMatrix);
      const old = this.current;
      this.extraStack.push(old);
      this.current = old.clone();
    }
    restore() {
      this.transformMatrix = this.transformStack.pop();
      this.current = this.extraStack.pop();
      this.pendingClip = null;
      this.tgrp = null;
    }
    group(items) {
      this.save();
      this.executeOpTree(items);
      this.restore();
    }
    loadDependencies(operatorList) {
      const fnArray = operatorList.fnArray;
      const argsArray = operatorList.argsArray;
      for (let i = 0, ii = fnArray.length; i < ii; i++) {
        if (fnArray[i] !== _util.OPS.dependency) {
          continue;
        }
        for (const obj of argsArray[i]) {
          const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
          const promise = new Promise(resolve => {
            objsPool.get(obj, resolve);
          });
          this.current.dependencies.push(promise);
        }
      }
      return Promise.all(this.current.dependencies);
    }
    transform(a, b, c, d, e, f) {
      const transformMatrix = [a, b, c, d, e, f];
      this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
      this.tgrp = null;
    }
    getSVG(operatorList, viewport) {
      this.viewport = viewport;
      const svgElement = this._initialize(viewport);
      return this.loadDependencies(operatorList).then(() => {
        this.transformMatrix = _util.IDENTITY_MATRIX;
        this.executeOpTree(this.convertOpList(operatorList));
        return svgElement;
      });
    }
    convertOpList(operatorList) {
      const operatorIdMapping = this._operatorIdMapping;
      const argsArray = operatorList.argsArray;
      const fnArray = operatorList.fnArray;
      const opList = [];
      for (let i = 0, ii = fnArray.length; i < ii; i++) {
        const fnId = fnArray[i];
        opList.push({
          fnId,
          fn: operatorIdMapping[fnId],
          args: argsArray[i]
        });
      }
      return opListToTree(opList);
    }
    executeOpTree(opTree) {
      for (const opTreeElement of opTree) {
        const fn = opTreeElement.fn;
        const fnId = opTreeElement.fnId;
        const args = opTreeElement.args;
        switch (fnId | 0) {
          case _util.OPS.beginText:
            this.beginText();
            break;
          case _util.OPS.dependency:
            break;
          case _util.OPS.setLeading:
            this.setLeading(args);
            break;
          case _util.OPS.setLeadingMoveText:
            this.setLeadingMoveText(args[0], args[1]);
            break;
          case _util.OPS.setFont:
            this.setFont(args);
            break;
          case _util.OPS.showText:
            this.showText(args[0]);
            break;
          case _util.OPS.showSpacedText:
            this.showText(args[0]);
            break;
          case _util.OPS.endText:
            this.endText();
            break;
          case _util.OPS.moveText:
            this.moveText(args[0], args[1]);
            break;
          case _util.OPS.setCharSpacing:
            this.setCharSpacing(args[0]);
            break;
          case _util.OPS.setWordSpacing:
            this.setWordSpacing(args[0]);
            break;
          case _util.OPS.setHScale:
            this.setHScale(args[0]);
            break;
          case _util.OPS.setTextMatrix:
            this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
            break;
          case _util.OPS.setTextRise:
            this.setTextRise(args[0]);
            break;
          case _util.OPS.setTextRenderingMode:
            this.setTextRenderingMode(args[0]);
            break;
          case _util.OPS.setLineWidth:
            this.setLineWidth(args[0]);
            break;
          case _util.OPS.setLineJoin:
            this.setLineJoin(args[0]);
            break;
          case _util.OPS.setLineCap:
            this.setLineCap(args[0]);
            break;
          case _util.OPS.setMiterLimit:
            this.setMiterLimit(args[0]);
            break;
          case _util.OPS.setFillRGBColor:
            this.setFillRGBColor(args[0], args[1], args[2]);
            break;
          case _util.OPS.setStrokeRGBColor:
            this.setStrokeRGBColor(args[0], args[1], args[2]);
            break;
          case _util.OPS.setStrokeColorN:
            this.setStrokeColorN(args);
            break;
          case _util.OPS.setFillColorN:
            this.setFillColorN(args);
            break;
          case _util.OPS.shadingFill:
            this.shadingFill(args[0]);
            break;
          case _util.OPS.setDash:
            this.setDash(args[0], args[1]);
            break;
          case _util.OPS.setRenderingIntent:
            this.setRenderingIntent(args[0]);
            break;
          case _util.OPS.setFlatness:
            this.setFlatness(args[0]);
            break;
          case _util.OPS.setGState:
            this.setGState(args[0]);
            break;
          case _util.OPS.fill:
            this.fill();
            break;
          case _util.OPS.eoFill:
            this.eoFill();
            break;
          case _util.OPS.stroke:
            this.stroke();
            break;
          case _util.OPS.fillStroke:
            this.fillStroke();
            break;
          case _util.OPS.eoFillStroke:
            this.eoFillStroke();
            break;
          case _util.OPS.clip:
            this.clip("nonzero");
            break;
          case _util.OPS.eoClip:
            this.clip("evenodd");
            break;
          case _util.OPS.paintSolidColorImageMask:
            this.paintSolidColorImageMask();
            break;
          case _util.OPS.paintImageXObject:
            this.paintImageXObject(args[0]);
            break;
          case _util.OPS.paintInlineImageXObject:
            this.paintInlineImageXObject(args[0]);
            break;
          case _util.OPS.paintImageMaskXObject:
            this.paintImageMaskXObject(args[0]);
            break;
          case _util.OPS.paintFormXObjectBegin:
            this.paintFormXObjectBegin(args[0], args[1]);
            break;
          case _util.OPS.paintFormXObjectEnd:
            this.paintFormXObjectEnd();
            break;
          case _util.OPS.closePath:
            this.closePath();
            break;
          case _util.OPS.closeStroke:
            this.closeStroke();
            break;
          case _util.OPS.closeFillStroke:
            this.closeFillStroke();
            break;
          case _util.OPS.closeEOFillStroke:
            this.closeEOFillStroke();
            break;
          case _util.OPS.nextLine:
            this.nextLine();
            break;
          case _util.OPS.transform:
            this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
            break;
          case _util.OPS.constructPath:
            this.constructPath(args[0], args[1]);
            break;
          case _util.OPS.endPath:
            this.endPath();
            break;
          case 92:
            this.group(opTreeElement.items);
            break;
          default:
            (0, _util.warn)(`Unimplemented operator ${fn}`);
            break;
        }
      }
    }
    setWordSpacing(wordSpacing) {
      this.current.wordSpacing = wordSpacing;
    }
    setCharSpacing(charSpacing) {
      this.current.charSpacing = charSpacing;
    }
    nextLine() {
      this.moveText(0, this.current.leading);
    }
    setTextMatrix(a, b, c, d, e, f) {
      const current = this.current;
      current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
      current.textMatrixScale = Math.hypot(a, b);
      current.x = current.lineX = 0;
      current.y = current.lineY = 0;
      current.xcoords = [];
      current.ycoords = [];
      current.tspan = this.svgFactory.createElement("svg:tspan");
      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
      current.tspan.setAttributeNS(null, "y", pf(-current.y));
      current.txtElement = this.svgFactory.createElement("svg:text");
      current.txtElement.append(current.tspan);
    }
    beginText() {
      const current = this.current;
      current.x = current.lineX = 0;
      current.y = current.lineY = 0;
      current.textMatrix = _util.IDENTITY_MATRIX;
      current.lineMatrix = _util.IDENTITY_MATRIX;
      current.textMatrixScale = 1;
      current.tspan = this.svgFactory.createElement("svg:tspan");
      current.txtElement = this.svgFactory.createElement("svg:text");
      current.txtgrp = this.svgFactory.createElement("svg:g");
      current.xcoords = [];
      current.ycoords = [];
    }
    moveText(x, y) {
      const current = this.current;
      current.x = current.lineX += x;
      current.y = current.lineY += y;
      current.xcoords = [];
      current.ycoords = [];
      current.tspan = this.svgFactory.createElement("svg:tspan");
      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
      current.tspan.setAttributeNS(null, "y", pf(-current.y));
    }
    showText(glyphs) {
      const current = this.current;
      const font = current.font;
      const fontSize = current.fontSize;
      if (fontSize === 0) {
        return;
      }
      const fontSizeScale = current.fontSizeScale;
      const charSpacing = current.charSpacing;
      const wordSpacing = current.wordSpacing;
      const fontDirection = current.fontDirection;
      const textHScale = current.textHScale * fontDirection;
      const vertical = font.vertical;
      const spacingDir = vertical ? 1 : -1;
      const defaultVMetrics = font.defaultVMetrics;
      const widthAdvanceScale = fontSize * current.fontMatrix[0];
      let x = 0;
      for (const glyph of glyphs) {
        if (glyph === null) {
          x += fontDirection * wordSpacing;
          continue;
        } else if (typeof glyph === "number") {
          x += spacingDir * glyph * fontSize / 1000;
          continue;
        }
        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
        const character = glyph.fontChar;
        let scaledX, scaledY;
        let width = glyph.width;
        if (vertical) {
          let vx;
          const vmetric = glyph.vmetric || defaultVMetrics;
          vx = glyph.vmetric ? vmetric[1] : width * 0.5;
          vx = -vx * widthAdvanceScale;
          const vy = vmetric[2] * widthAdvanceScale;
          width = vmetric ? -vmetric[0] : width;
          scaledX = vx / fontSizeScale;
          scaledY = (x + vy) / fontSizeScale;
        } else {
          scaledX = x / fontSizeScale;
          scaledY = 0;
        }
        if (glyph.isInFont || font.missingFile) {
          current.xcoords.push(current.x + scaledX);
          if (vertical) {
            current.ycoords.push(-current.y + scaledY);
          }
          current.tspan.textContent += character;
        } else {}
        let charWidth;
        if (vertical) {
          charWidth = width * widthAdvanceScale - spacing * fontDirection;
        } else {
          charWidth = width * widthAdvanceScale + spacing * fontDirection;
        }
        x += charWidth;
      }
      current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
      if (vertical) {
        current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
      } else {
        current.tspan.setAttributeNS(null, "y", pf(-current.y));
      }
      if (vertical) {
        current.y -= x;
      } else {
        current.x += x * textHScale;
      }
      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
      if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
        current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
      }
      if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
        current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
      }
      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        if (current.fillColor !== SVG_DEFAULTS.fillColor) {
          current.tspan.setAttributeNS(null, "fill", current.fillColor);
        }
        if (current.fillAlpha < 1) {
          current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
        }
      } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
        current.tspan.setAttributeNS(null, "fill", "transparent");
      } else {
        current.tspan.setAttributeNS(null, "fill", "none");
      }
      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
        const lineWidthScale = 1 / (current.textMatrixScale || 1);
        this._setStrokeAttributes(current.tspan, lineWidthScale);
      }
      let textMatrix = current.textMatrix;
      if (current.textRise !== 0) {
        textMatrix = textMatrix.slice();
        textMatrix[5] += current.textRise;
      }
      current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
      current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
      current.txtElement.append(current.tspan);
      current.txtgrp.append(current.txtElement);
      this._ensureTransformGroup().append(current.txtElement);
    }
    setLeadingMoveText(x, y) {
      this.setLeading(-y);
      this.moveText(x, y);
    }
    addFontStyle(fontObj) {
      if (!fontObj.data) {
        throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
      }
      if (!this.cssStyle) {
        this.cssStyle = this.svgFactory.createElement("svg:style");
        this.cssStyle.setAttributeNS(null, "type", "text/css");
        this.defs.append(this.cssStyle);
      }
      const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
      this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
    }
    setFont(details) {
      const current = this.current;
      const fontObj = this.commonObjs.get(details[0]);
      let size = details[1];
      current.font = fontObj;
      if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
        this.addFontStyle(fontObj);
        this.embeddedFonts[fontObj.loadedName] = fontObj;
      }
      current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
      let bold = "normal";
      if (fontObj.black) {
        bold = "900";
      } else if (fontObj.bold) {
        bold = "bold";
      }
      const italic = fontObj.italic ? "italic" : "normal";
      if (size < 0) {
        size = -size;
        current.fontDirection = -1;
      } else {
        current.fontDirection = 1;
      }
      current.fontSize = size;
      current.fontFamily = fontObj.loadedName;
      current.fontWeight = bold;
      current.fontStyle = italic;
      current.tspan = this.svgFactory.createElement("svg:tspan");
      current.tspan.setAttributeNS(null, "y", pf(-current.y));
      current.xcoords = [];
      current.ycoords = [];
    }
    endText() {
      const current = this.current;
      if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
        current.element = current.txtElement;
        this.clip("nonzero");
        this.endPath();
      }
    }
    setLineWidth(width) {
      if (width > 0) {
        this.current.lineWidth = width;
      }
    }
    setLineCap(style) {
      this.current.lineCap = LINE_CAP_STYLES[style];
    }
    setLineJoin(style) {
      this.current.lineJoin = LINE_JOIN_STYLES[style];
    }
    setMiterLimit(limit) {
      this.current.miterLimit = limit;
    }
    setStrokeAlpha(strokeAlpha) {
      this.current.strokeAlpha = strokeAlpha;
    }
    setStrokeRGBColor(r, g, b) {
      this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
    }
    setFillAlpha(fillAlpha) {
      this.current.fillAlpha = fillAlpha;
    }
    setFillRGBColor(r, g, b) {
      this.current.fillColor = _util.Util.makeHexColor(r, g, b);
      this.current.tspan = this.svgFactory.createElement("svg:tspan");
      this.current.xcoords = [];
      this.current.ycoords = [];
    }
    setStrokeColorN(args) {
      this.current.strokeColor = this._makeColorN_Pattern(args);
    }
    setFillColorN(args) {
      this.current.fillColor = this._makeColorN_Pattern(args);
    }
    shadingFill(args) {
      const width = this.viewport.width;
      const height = this.viewport.height;
      const inv = _util.Util.inverseTransform(this.transformMatrix);
      const bl = _util.Util.applyTransform([0, 0], inv);
      const br = _util.Util.applyTransform([0, height], inv);
      const ul = _util.Util.applyTransform([width, 0], inv);
      const ur = _util.Util.applyTransform([width, height], inv);
      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
      const rect = this.svgFactory.createElement("svg:rect");
      rect.setAttributeNS(null, "x", x0);
      rect.setAttributeNS(null, "y", y0);
      rect.setAttributeNS(null, "width", x1 - x0);
      rect.setAttributeNS(null, "height", y1 - y0);
      rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
      if (this.current.fillAlpha < 1) {
        rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
      }
      this._ensureTransformGroup().append(rect);
    }
    _makeColorN_Pattern(args) {
      if (args[0] === "TilingPattern") {
        return this._makeTilingPattern(args);
      }
      return this._makeShadingPattern(args);
    }
    _makeTilingPattern(args) {
      const color = args[1];
      const operatorList = args[2];
      const matrix = args[3] || _util.IDENTITY_MATRIX;
      const [x0, y0, x1, y1] = args[4];
      const xstep = args[5];
      const ystep = args[6];
      const paintType = args[7];
      const tilingId = `shading${shadingCount++}`;
      const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
      const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
      const txstep = xstep * xscale;
      const tystep = ystep * yscale;
      const tiling = this.svgFactory.createElement("svg:pattern");
      tiling.setAttributeNS(null, "id", tilingId);
      tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
      tiling.setAttributeNS(null, "width", txstep);
      tiling.setAttributeNS(null, "height", tystep);
      tiling.setAttributeNS(null, "x", `${tx0}`);
      tiling.setAttributeNS(null, "y", `${ty0}`);
      const svg = this.svg;
      const transformMatrix = this.transformMatrix;
      const fillColor = this.current.fillColor;
      const strokeColor = this.current.strokeColor;
      const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
      this.svg = bbox;
      this.transformMatrix = matrix;
      if (paintType === 2) {
        const cssColor = _util.Util.makeHexColor(...color);
        this.current.fillColor = cssColor;
        this.current.strokeColor = cssColor;
      }
      this.executeOpTree(this.convertOpList(operatorList));
      this.svg = svg;
      this.transformMatrix = transformMatrix;
      this.current.fillColor = fillColor;
      this.current.strokeColor = strokeColor;
      tiling.append(bbox.childNodes[0]);
      this.defs.append(tiling);
      return `url(#${tilingId})`;
    }
    _makeShadingPattern(args) {
      if (typeof args === "string") {
        args = this.objs.get(args);
      }
      switch (args[0]) {
        case "RadialAxial":
          const shadingId = `shading${shadingCount++}`;
          const colorStops = args[3];
          let gradient;
          switch (args[1]) {
            case "axial":
              const point0 = args[4];
              const point1 = args[5];
              gradient = this.svgFactory.createElement("svg:linearGradient");
              gradient.setAttributeNS(null, "id", shadingId);
              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
              gradient.setAttributeNS(null, "x1", point0[0]);
              gradient.setAttributeNS(null, "y1", point0[1]);
              gradient.setAttributeNS(null, "x2", point1[0]);
              gradient.setAttributeNS(null, "y2", point1[1]);
              break;
            case "radial":
              const focalPoint = args[4];
              const circlePoint = args[5];
              const focalRadius = args[6];
              const circleRadius = args[7];
              gradient = this.svgFactory.createElement("svg:radialGradient");
              gradient.setAttributeNS(null, "id", shadingId);
              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
              gradient.setAttributeNS(null, "cx", circlePoint[0]);
              gradient.setAttributeNS(null, "cy", circlePoint[1]);
              gradient.setAttributeNS(null, "r", circleRadius);
              gradient.setAttributeNS(null, "fx", focalPoint[0]);
              gradient.setAttributeNS(null, "fy", focalPoint[1]);
              gradient.setAttributeNS(null, "fr", focalRadius);
              break;
            default:
              throw new Error(`Unknown RadialAxial type: ${args[1]}`);
          }
          for (const colorStop of colorStops) {
            const stop = this.svgFactory.createElement("svg:stop");
            stop.setAttributeNS(null, "offset", colorStop[0]);
            stop.setAttributeNS(null, "stop-color", colorStop[1]);
            gradient.append(stop);
          }
          this.defs.append(gradient);
          return `url(#${shadingId})`;
        case "Mesh":
          (0, _util.warn)("Unimplemented pattern Mesh");
          return null;
        case "Dummy":
          return "hotpink";
        default:
          throw new Error(`Unknown IR type: ${args[0]}`);
      }
    }
    setDash(dashArray, dashPhase) {
      this.current.dashArray = dashArray;
      this.current.dashPhase = dashPhase;
    }
    constructPath(ops, args) {
      const current = this.current;
      let x = current.x,
        y = current.y;
      let d = [];
      let j = 0;
      for (const op of ops) {
        switch (op | 0) {
          case _util.OPS.rectangle:
            x = args[j++];
            y = args[j++];
            const width = args[j++];
            const height = args[j++];
            const xw = x + width;
            const yh = y + height;
            d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
            break;
          case _util.OPS.moveTo:
            x = args[j++];
            y = args[j++];
            d.push("M", pf(x), pf(y));
            break;
          case _util.OPS.lineTo:
            x = args[j++];
            y = args[j++];
            d.push("L", pf(x), pf(y));
            break;
          case _util.OPS.curveTo:
            x = args[j + 4];
            y = args[j + 5];
            d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
            j += 6;
            break;
          case _util.OPS.curveTo2:
            d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
            x = args[j + 2];
            y = args[j + 3];
            j += 4;
            break;
          case _util.OPS.curveTo3:
            x = args[j + 2];
            y = args[j + 3];
            d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
            j += 4;
            break;
          case _util.OPS.closePath:
            d.push("Z");
            break;
        }
      }
      d = d.join(" ");
      if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
        d = current.path.getAttributeNS(null, "d") + d;
      } else {
        current.path = this.svgFactory.createElement("svg:path");
        this._ensureTransformGroup().append(current.path);
      }
      current.path.setAttributeNS(null, "d", d);
      current.path.setAttributeNS(null, "fill", "none");
      current.element = current.path;
      current.setCurrentPoint(x, y);
    }
    endPath() {
      const current = this.current;
      current.path = null;
      if (!this.pendingClip) {
        return;
      }
      if (!current.element) {
        this.pendingClip = null;
        return;
      }
      const clipId = `clippath${clipCount++}`;
      const clipPath = this.svgFactory.createElement("svg:clipPath");
      clipPath.setAttributeNS(null, "id", clipId);
      clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
      const clipElement = current.element.cloneNode(true);
      if (this.pendingClip === "evenodd") {
        clipElement.setAttributeNS(null, "clip-rule", "evenodd");
      } else {
        clipElement.setAttributeNS(null, "clip-rule", "nonzero");
      }
      this.pendingClip = null;
      clipPath.append(clipElement);
      this.defs.append(clipPath);
      if (current.activeClipUrl) {
        current.clipGroup = null;
        for (const prev of this.extraStack) {
          prev.clipGroup = null;
        }
        clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
      }
      current.activeClipUrl = `url(#${clipId})`;
      this.tgrp = null;
    }
    clip(type) {
      this.pendingClip = type;
    }
    closePath() {
      const current = this.current;
      if (current.path) {
        const d = `${current.path.getAttributeNS(null, "d")}Z`;
        current.path.setAttributeNS(null, "d", d);
      }
    }
    setLeading(leading) {
      this.current.leading = -leading;
    }
    setTextRise(textRise) {
      this.current.textRise = textRise;
    }
    setTextRenderingMode(textRenderingMode) {
      this.current.textRenderingMode = textRenderingMode;
    }
    setHScale(scale) {
      this.current.textHScale = scale / 100;
    }
    setRenderingIntent(intent) {}
    setFlatness(flatness) {}
    setGState(states) {
      for (const [key, value] of states) {
        switch (key) {
          case "LW":
            this.setLineWidth(value);
            break;
          case "LC":
            this.setLineCap(value);
            break;
          case "LJ":
            this.setLineJoin(value);
            break;
          case "ML":
            this.setMiterLimit(value);
            break;
          case "D":
            this.setDash(value[0], value[1]);
            break;
          case "RI":
            this.setRenderingIntent(value);
            break;
          case "FL":
            this.setFlatness(value);
            break;
          case "Font":
            this.setFont(value);
            break;
          case "CA":
            this.setStrokeAlpha(value);
            break;
          case "ca":
            this.setFillAlpha(value);
            break;
          default:
            (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
            break;
        }
      }
    }
    fill() {
      const current = this.current;
      if (current.element) {
        current.element.setAttributeNS(null, "fill", current.fillColor);
        current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
        this.endPath();
      }
    }
    stroke() {
      const current = this.current;
      if (current.element) {
        this._setStrokeAttributes(current.element);
        current.element.setAttributeNS(null, "fill", "none");
        this.endPath();
      }
    }
    _setStrokeAttributes(element, lineWidthScale = 1) {
      const current = this.current;
      let dashArray = current.dashArray;
      if (lineWidthScale !== 1 && dashArray.length > 0) {
        dashArray = dashArray.map(function (value) {
          return lineWidthScale * value;
        });
      }
      element.setAttributeNS(null, "stroke", current.strokeColor);
      element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
      element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
      element.setAttributeNS(null, "stroke-linecap", current.lineCap);
      element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
      element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
      element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
      element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
    }
    eoFill() {
      this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
      this.fill();
    }
    fillStroke() {
      this.stroke();
      this.fill();
    }
    eoFillStroke() {
      this.current.element?.setAttributeNS(null, "fill-rule", "evenodd");
      this.fillStroke();
    }
    closeStroke() {
      this.closePath();
      this.stroke();
    }
    closeFillStroke() {
      this.closePath();
      this.fillStroke();
    }
    closeEOFillStroke() {
      this.closePath();
      this.eoFillStroke();
    }
    paintSolidColorImageMask() {
      const rect = this.svgFactory.createElement("svg:rect");
      rect.setAttributeNS(null, "x", "0");
      rect.setAttributeNS(null, "y", "0");
      rect.setAttributeNS(null, "width", "1px");
      rect.setAttributeNS(null, "height", "1px");
      rect.setAttributeNS(null, "fill", this.current.fillColor);
      this._ensureTransformGroup().append(rect);
    }
    paintImageXObject(objId) {
      const imgData = this.getObject(objId);
      if (!imgData) {
        (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
        return;
      }
      this.paintInlineImageXObject(imgData);
    }
    paintInlineImageXObject(imgData, mask) {
      const width = imgData.width;
      const height = imgData.height;
      const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
      const cliprect = this.svgFactory.createElement("svg:rect");
      cliprect.setAttributeNS(null, "x", "0");
      cliprect.setAttributeNS(null, "y", "0");
      cliprect.setAttributeNS(null, "width", pf(width));
      cliprect.setAttributeNS(null, "height", pf(height));
      this.current.element = cliprect;
      this.clip("nonzero");
      const imgEl = this.svgFactory.createElement("svg:image");
      imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
      imgEl.setAttributeNS(null, "x", "0");
      imgEl.setAttributeNS(null, "y", pf(-height));
      imgEl.setAttributeNS(null, "width", pf(width) + "px");
      imgEl.setAttributeNS(null, "height", pf(height) + "px");
      imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
      if (mask) {
        mask.append(imgEl);
      } else {
        this._ensureTransformGroup().append(imgEl);
      }
    }
    paintImageMaskXObject(img) {
      const imgData = this.getObject(img.data, img);
      if (imgData.bitmap) {
        (0, _util.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, " + "ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");
        return;
      }
      const current = this.current;
      const width = imgData.width;
      const height = imgData.height;
      const fillColor = current.fillColor;
      current.maskId = `mask${maskCount++}`;
      const mask = this.svgFactory.createElement("svg:mask");
      mask.setAttributeNS(null, "id", current.maskId);
      const rect = this.svgFactory.createElement("svg:rect");
      rect.setAttributeNS(null, "x", "0");
      rect.setAttributeNS(null, "y", "0");
      rect.setAttributeNS(null, "width", pf(width));
      rect.setAttributeNS(null, "height", pf(height));
      rect.setAttributeNS(null, "fill", fillColor);
      rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
      this.defs.append(mask);
      this._ensureTransformGroup().append(rect);
      this.paintInlineImageXObject(imgData, mask);
    }
    paintFormXObjectBegin(matrix, bbox) {
      if (Array.isArray(matrix) && matrix.length === 6) {
        this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
      }
      if (bbox) {
        const width = bbox[2] - bbox[0];
        const height = bbox[3] - bbox[1];
        const cliprect = this.svgFactory.createElement("svg:rect");
        cliprect.setAttributeNS(null, "x", bbox[0]);
        cliprect.setAttributeNS(null, "y", bbox[1]);
        cliprect.setAttributeNS(null, "width", pf(width));
        cliprect.setAttributeNS(null, "height", pf(height));
        this.current.element = cliprect;
        this.clip("nonzero");
        this.endPath();
      }
    }
    paintFormXObjectEnd() {}
    _initialize(viewport) {
      const svg = this.svgFactory.create(viewport.width, viewport.height);
      const definitions = this.svgFactory.createElement("svg:defs");
      svg.append(definitions);
      this.defs = definitions;
      const rootGroup = this.svgFactory.createElement("svg:g");
      rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
      svg.append(rootGroup);
      this.svg = rootGroup;
      return svg;
    }
    _ensureClipGroup() {
      if (!this.current.clipGroup) {
        const clipGroup = this.svgFactory.createElement("svg:g");
        clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
        this.svg.append(clipGroup);
        this.current.clipGroup = clipGroup;
      }
      return this.current.clipGroup;
    }
    _ensureTransformGroup() {
      if (!this.tgrp) {
        this.tgrp = this.svgFactory.createElement("svg:g");
        this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
        if (this.current.activeClipUrl) {
          this._ensureClipGroup().append(this.tgrp);
        } else {
          this.svg.append(this.tgrp);
        }
      }
      return this.tgrp;
    }
  };
}

/***/ })
/******/ 	]);
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __w_pdfjs_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
var exports = __webpack_exports__;


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
Object.defineProperty(exports, "AbortException", ({
  enumerable: true,
  get: function () {
    return _util.AbortException;
  }
}));
Object.defineProperty(exports, "AnnotationEditorLayer", ({
  enumerable: true,
  get: function () {
    return _annotation_editor_layer.AnnotationEditorLayer;
  }
}));
Object.defineProperty(exports, "AnnotationEditorParamsType", ({
  enumerable: true,
  get: function () {
    return _util.AnnotationEditorParamsType;
  }
}));
Object.defineProperty(exports, "AnnotationEditorType", ({
  enumerable: true,
  get: function () {
    return _util.AnnotationEditorType;
  }
}));
Object.defineProperty(exports, "AnnotationEditorUIManager", ({
  enumerable: true,
  get: function () {
    return _tools.AnnotationEditorUIManager;
  }
}));
Object.defineProperty(exports, "AnnotationLayer", ({
  enumerable: true,
  get: function () {
    return _annotation_layer.AnnotationLayer;
  }
}));
Object.defineProperty(exports, "AnnotationMode", ({
  enumerable: true,
  get: function () {
    return _util.AnnotationMode;
  }
}));
Object.defineProperty(exports, "CMapCompressionType", ({
  enumerable: true,
  get: function () {
    return _util.CMapCompressionType;
  }
}));
Object.defineProperty(exports, "GlobalWorkerOptions", ({
  enumerable: true,
  get: function () {
    return _worker_options.GlobalWorkerOptions;
  }
}));
Object.defineProperty(exports, "InvalidPDFException", ({
  enumerable: true,
  get: function () {
    return _util.InvalidPDFException;
  }
}));
Object.defineProperty(exports, "MissingPDFException", ({
  enumerable: true,
  get: function () {
    return _util.MissingPDFException;
  }
}));
Object.defineProperty(exports, "OPS", ({
  enumerable: true,
  get: function () {
    return _util.OPS;
  }
}));
Object.defineProperty(exports, "PDFDataRangeTransport", ({
  enumerable: true,
  get: function () {
    return _api.PDFDataRangeTransport;
  }
}));
Object.defineProperty(exports, "PDFDateString", ({
  enumerable: true,
  get: function () {
    return _display_utils.PDFDateString;
  }
}));
Object.defineProperty(exports, "PDFWorker", ({
  enumerable: true,
  get: function () {
    return _api.PDFWorker;
  }
}));
Object.defineProperty(exports, "PasswordResponses", ({
  enumerable: true,
  get: function () {
    return _util.PasswordResponses;
  }
}));
Object.defineProperty(exports, "PermissionFlag", ({
  enumerable: true,
  get: function () {
    return _util.PermissionFlag;
  }
}));
Object.defineProperty(exports, "PixelsPerInch", ({
  enumerable: true,
  get: function () {
    return _display_utils.PixelsPerInch;
  }
}));
Object.defineProperty(exports, "RenderingCancelledException", ({
  enumerable: true,
  get: function () {
    return _display_utils.RenderingCancelledException;
  }
}));
Object.defineProperty(exports, "SVGGraphics", ({
  enumerable: true,
  get: function () {
    return _svg.SVGGraphics;
  }
}));
Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
  enumerable: true,
  get: function () {
    return _util.UNSUPPORTED_FEATURES;
  }
}));
Object.defineProperty(exports, "UnexpectedResponseException", ({
  enumerable: true,
  get: function () {
    return _util.UnexpectedResponseException;
  }
}));
Object.defineProperty(exports, "Util", ({
  enumerable: true,
  get: function () {
    return _util.Util;
  }
}));
Object.defineProperty(exports, "VerbosityLevel", ({
  enumerable: true,
  get: function () {
    return _util.VerbosityLevel;
  }
}));
Object.defineProperty(exports, "XfaLayer", ({
  enumerable: true,
  get: function () {
    return _xfa_layer.XfaLayer;
  }
}));
Object.defineProperty(exports, "build", ({
  enumerable: true,
  get: function () {
    return _api.build;
  }
}));
Object.defineProperty(exports, "createPromiseCapability", ({
  enumerable: true,
  get: function () {
    return _util.createPromiseCapability;
  }
}));
Object.defineProperty(exports, "createValidAbsoluteUrl", ({
  enumerable: true,
  get: function () {
    return _util.createValidAbsoluteUrl;
  }
}));
Object.defineProperty(exports, "getDocument", ({
  enumerable: true,
  get: function () {
    return _api.getDocument;
  }
}));
Object.defineProperty(exports, "getFilenameFromUrl", ({
  enumerable: true,
  get: function () {
    return _display_utils.getFilenameFromUrl;
  }
}));
Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
  enumerable: true,
  get: function () {
    return _display_utils.getPdfFilenameFromUrl;
  }
}));
Object.defineProperty(exports, "getXfaPageViewport", ({
  enumerable: true,
  get: function () {
    return _display_utils.getXfaPageViewport;
  }
}));
Object.defineProperty(exports, "isDataScheme", ({
  enumerable: true,
  get: function () {
    return _display_utils.isDataScheme;
  }
}));
Object.defineProperty(exports, "isPdfFile", ({
  enumerable: true,
  get: function () {
    return _display_utils.isPdfFile;
  }
}));
Object.defineProperty(exports, "loadScript", ({
  enumerable: true,
  get: function () {
    return _display_utils.loadScript;
  }
}));
Object.defineProperty(exports, "renderTextLayer", ({
  enumerable: true,
  get: function () {
    return _text_layer.renderTextLayer;
  }
}));
Object.defineProperty(exports, "setLayerDimensions", ({
  enumerable: true,
  get: function () {
    return _display_utils.setLayerDimensions;
  }
}));
Object.defineProperty(exports, "shadow", ({
  enumerable: true,
  get: function () {
    return _util.shadow;
  }
}));
Object.defineProperty(exports, "updateTextLayer", ({
  enumerable: true,
  get: function () {
    return _text_layer.updateTextLayer;
  }
}));
Object.defineProperty(exports, "version", ({
  enumerable: true,
  get: function () {
    return _api.version;
  }
}));
var _util = __w_pdfjs_require__(1);
var _api = __w_pdfjs_require__(2);
var _display_utils = __w_pdfjs_require__(6);
var _text_layer = __w_pdfjs_require__(26);
var _annotation_editor_layer = __w_pdfjs_require__(27);
var _tools = __w_pdfjs_require__(5);
var _annotation_layer = __w_pdfjs_require__(32);
var _worker_options = __w_pdfjs_require__(14);
var _svg = __w_pdfjs_require__(35);
var _xfa_layer = __w_pdfjs_require__(34);
const pdfjsVersion = '3.4.50';
const pdfjsBuild = '00560ed83';
})();

/******/ 	return __webpack_exports__;
/******/ })()
;
});

/**
 * @licstart The following is the entire license notice for the
 * JavaScript code in this page
 *
 * Copyright 2023 Mozilla Foundation
 *
 * 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.
 *
 * @licend The above is the entire license notice for the
 * JavaScript code in this page
 */

(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("pdfjs-dist/build/pdf.worker", [], factory);
	else if(typeof exports === 'object')
		exports["pdfjs-dist/build/pdf.worker"] = factory();
	else
		root["pdfjs-dist/build/pdf.worker"] = root.pdfjsWorker = factory();
})(globalThis, () => {
return /******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ([
/* 0 */,
/* 1 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.WorkerTask = exports.WorkerMessageHandler = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _core_utils = __w_pdfjs_require__(4);
var _pdf_manager = __w_pdfjs_require__(6);
var _cleanup_helper = __w_pdfjs_require__(69);
var _writer = __w_pdfjs_require__(63);
var _is_node = __w_pdfjs_require__(100);
var _message_handler = __w_pdfjs_require__(101);
var _worker_stream = __w_pdfjs_require__(102);
class WorkerTask {
  constructor(name) {
    this.name = name;
    this.terminated = false;
    this._capability = (0, _util.createPromiseCapability)();
  }
  get finished() {
    return this._capability.promise;
  }
  finish() {
    this._capability.resolve();
  }
  terminate() {
    this.terminated = true;
  }
  ensureNotTerminated() {
    if (this.terminated) {
      throw new Error("Worker task was terminated");
    }
  }
}
exports.WorkerTask = WorkerTask;
class WorkerMessageHandler {
  static setup(handler, port) {
    let testMessageProcessed = false;
    handler.on("test", function (data) {
      if (testMessageProcessed) {
        return;
      }
      testMessageProcessed = true;
      handler.send("test", data instanceof Uint8Array);
    });
    handler.on("configure", function (data) {
      (0, _util.setVerbosityLevel)(data.verbosity);
    });
    handler.on("GetDocRequest", function (data) {
      return WorkerMessageHandler.createDocumentHandler(data, port);
    });
  }
  static createDocumentHandler(docParams, port) {
    let pdfManager;
    let terminated = false;
    let cancelXHRs = null;
    const WorkerTasks = [];
    const verbosity = (0, _util.getVerbosityLevel)();
    const {
      docId,
      apiVersion
    } = docParams;
    const workerVersion = '3.4.50';
    if (apiVersion !== workerVersion) {
      throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`);
    }
    const enumerableProperties = [];
    for (const property in []) {
      enumerableProperties.push(property);
    }
    if (enumerableProperties.length) {
      throw new Error("The `Array.prototype` contains unexpected enumerable properties: " + enumerableProperties.join(", ") + "; thus breaking e.g. `for...in` iteration of `Array`s.");
    }
    if (typeof ReadableStream === "undefined") {
      const partialMsg = "The browser/environment lacks native support for critical " + "functionality used by the PDF.js library (e.g. `ReadableStream`); ";
      if (_is_node.isNodeJS) {
        throw new Error(partialMsg + "please use a `legacy`-build instead.");
      }
      throw new Error(partialMsg + "please update to a supported browser.");
    }
    const workerHandlerName = docId + "_worker";
    let handler = new _message_handler.MessageHandler(workerHandlerName, docId, port);
    function ensureNotTerminated() {
      if (terminated) {
        throw new Error("Worker was terminated");
      }
    }
    function startWorkerTask(task) {
      WorkerTasks.push(task);
    }
    function finishWorkerTask(task) {
      task.finish();
      const i = WorkerTasks.indexOf(task);
      WorkerTasks.splice(i, 1);
    }
    async function loadDocument(recoveryMode) {
      await pdfManager.ensureDoc("checkHeader");
      await pdfManager.ensureDoc("parseStartXRef");
      await pdfManager.ensureDoc("parse", [recoveryMode]);
      await pdfManager.ensureDoc("checkFirstPage", [recoveryMode]);
      await pdfManager.ensureDoc("checkLastPage", [recoveryMode]);
      const isPureXfa = await pdfManager.ensureDoc("isPureXfa");
      if (isPureXfa) {
        const task = new WorkerTask("loadXfaFonts");
        startWorkerTask(task);
        await Promise.all([pdfManager.loadXfaFonts(handler, task).catch(reason => {}).then(() => finishWorkerTask(task)), pdfManager.loadXfaImages()]);
      }
      const [numPages, fingerprints] = await Promise.all([pdfManager.ensureDoc("numPages"), pdfManager.ensureDoc("fingerprints")]);
      const htmlForXfa = isPureXfa ? await pdfManager.ensureDoc("htmlForXfa") : null;
      return {
        numPages,
        fingerprints,
        htmlForXfa
      };
    }
    function getPdfManager({
      data,
      password,
      disableAutoFetch,
      rangeChunkSize,
      length,
      docBaseUrl,
      enableXfa,
      evaluatorOptions
    }) {
      const pdfManagerCapability = (0, _util.createPromiseCapability)();
      let newPdfManager;
      if (data) {
        try {
          newPdfManager = new _pdf_manager.LocalPdfManager(docId, data, password, handler, evaluatorOptions, enableXfa, docBaseUrl);
          pdfManagerCapability.resolve(newPdfManager);
        } catch (ex) {
          pdfManagerCapability.reject(ex);
        }
        return pdfManagerCapability.promise;
      }
      let pdfStream,
        cachedChunks = [];
      try {
        pdfStream = new _worker_stream.PDFWorkerStream(handler);
      } catch (ex) {
        pdfManagerCapability.reject(ex);
        return pdfManagerCapability.promise;
      }
      const fullRequest = pdfStream.getFullReader();
      fullRequest.headersReady.then(function () {
        if (!fullRequest.isRangeSupported) {
          return;
        }
        disableAutoFetch = disableAutoFetch || fullRequest.isStreamingSupported;
        newPdfManager = new _pdf_manager.NetworkPdfManager(docId, pdfStream, {
          msgHandler: handler,
          password,
          length: fullRequest.contentLength,
          disableAutoFetch,
          rangeChunkSize
        }, evaluatorOptions, enableXfa, docBaseUrl);
        for (const chunk of cachedChunks) {
          newPdfManager.sendProgressiveData(chunk);
        }
        cachedChunks = [];
        pdfManagerCapability.resolve(newPdfManager);
        cancelXHRs = null;
      }).catch(function (reason) {
        pdfManagerCapability.reject(reason);
        cancelXHRs = null;
      });
      let loaded = 0;
      const flushChunks = function () {
        const pdfFile = (0, _util.arraysToBytes)(cachedChunks);
        if (length && pdfFile.length !== length) {
          (0, _util.warn)("reported HTTP length is different from actual");
        }
        try {
          newPdfManager = new _pdf_manager.LocalPdfManager(docId, pdfFile, password, handler, evaluatorOptions, enableXfa, docBaseUrl);
          pdfManagerCapability.resolve(newPdfManager);
        } catch (ex) {
          pdfManagerCapability.reject(ex);
        }
        cachedChunks = [];
      };
      new Promise(function (resolve, reject) {
        const readChunk = function ({
          value,
          done
        }) {
          try {
            ensureNotTerminated();
            if (done) {
              if (!newPdfManager) {
                flushChunks();
              }
              cancelXHRs = null;
              return;
            }
            loaded += (0, _util.arrayByteLength)(value);
            if (!fullRequest.isStreamingSupported) {
              handler.send("DocProgress", {
                loaded,
                total: Math.max(loaded, fullRequest.contentLength || 0)
              });
            }
            if (newPdfManager) {
              newPdfManager.sendProgressiveData(value);
            } else {
              cachedChunks.push(value);
            }
            fullRequest.read().then(readChunk, reject);
          } catch (e) {
            reject(e);
          }
        };
        fullRequest.read().then(readChunk, reject);
      }).catch(function (e) {
        pdfManagerCapability.reject(e);
        cancelXHRs = null;
      });
      cancelXHRs = function (reason) {
        pdfStream.cancelAllRequests(reason);
      };
      return pdfManagerCapability.promise;
    }
    function setupDoc(data) {
      function onSuccess(doc) {
        ensureNotTerminated();
        handler.send("GetDoc", {
          pdfInfo: doc
        });
      }
      function onFailure(ex) {
        ensureNotTerminated();
        if (ex instanceof _util.PasswordException) {
          const task = new WorkerTask(`PasswordException: response ${ex.code}`);
          startWorkerTask(task);
          handler.sendWithPromise("PasswordRequest", ex).then(function ({
            password
          }) {
            finishWorkerTask(task);
            pdfManager.updatePassword(password);
            pdfManagerReady();
          }).catch(function () {
            finishWorkerTask(task);
            handler.send("DocException", ex);
          });
        } else if (ex instanceof _util.InvalidPDFException || ex instanceof _util.MissingPDFException || ex instanceof _util.UnexpectedResponseException || ex instanceof _util.UnknownErrorException) {
          handler.send("DocException", ex);
        } else {
          handler.send("DocException", new _util.UnknownErrorException(ex.message, ex.toString()));
        }
      }
      function pdfManagerReady() {
        ensureNotTerminated();
        loadDocument(false).then(onSuccess, function (reason) {
          ensureNotTerminated();
          if (!(reason instanceof _core_utils.XRefParseException)) {
            onFailure(reason);
            return;
          }
          pdfManager.requestLoadedStream().then(function () {
            ensureNotTerminated();
            loadDocument(true).then(onSuccess, onFailure);
          });
        });
      }
      ensureNotTerminated();
      getPdfManager(data).then(function (newPdfManager) {
        if (terminated) {
          newPdfManager.terminate(new _util.AbortException("Worker was terminated."));
          throw new Error("Worker was terminated");
        }
        pdfManager = newPdfManager;
        pdfManager.requestLoadedStream(true).then(stream => {
          handler.send("DataLoaded", {
            length: stream.bytes.byteLength
          });
        });
      }).then(pdfManagerReady, onFailure);
    }
    handler.on("GetPage", function (data) {
      return pdfManager.getPage(data.pageIndex).then(function (page) {
        return Promise.all([pdfManager.ensure(page, "rotate"), pdfManager.ensure(page, "ref"), pdfManager.ensure(page, "userUnit"), pdfManager.ensure(page, "view")]).then(function ([rotate, ref, userUnit, view]) {
          return {
            rotate,
            ref,
            userUnit,
            view
          };
        });
      });
    });
    handler.on("GetPageIndex", function (data) {
      const pageRef = _primitives.Ref.get(data.num, data.gen);
      return pdfManager.ensureCatalog("getPageIndex", [pageRef]);
    });
    handler.on("GetDestinations", function (data) {
      return pdfManager.ensureCatalog("destinations");
    });
    handler.on("GetDestination", function (data) {
      return pdfManager.ensureCatalog("getDestination", [data.id]);
    });
    handler.on("GetPageLabels", function (data) {
      return pdfManager.ensureCatalog("pageLabels");
    });
    handler.on("GetPageLayout", function (data) {
      return pdfManager.ensureCatalog("pageLayout");
    });
    handler.on("GetPageMode", function (data) {
      return pdfManager.ensureCatalog("pageMode");
    });
    handler.on("GetViewerPreferences", function (data) {
      return pdfManager.ensureCatalog("viewerPreferences");
    });
    handler.on("GetOpenAction", function (data) {
      return pdfManager.ensureCatalog("openAction");
    });
    handler.on("GetAttachments", function (data) {
      return pdfManager.ensureCatalog("attachments");
    });
    handler.on("GetJavaScript", function (data) {
      return pdfManager.ensureCatalog("javaScript");
    });
    handler.on("GetDocJSActions", function (data) {
      return pdfManager.ensureCatalog("jsActions");
    });
    handler.on("GetPageJSActions", function ({
      pageIndex
    }) {
      return pdfManager.getPage(pageIndex).then(function (page) {
        return pdfManager.ensure(page, "jsActions");
      });
    });
    handler.on("GetOutline", function (data) {
      return pdfManager.ensureCatalog("documentOutline");
    });
    handler.on("GetOptionalContentConfig", function (data) {
      return pdfManager.ensureCatalog("optionalContentConfig");
    });
    handler.on("GetPermissions", function (data) {
      return pdfManager.ensureCatalog("permissions");
    });
    handler.on("GetMetadata", function (data) {
      return Promise.all([pdfManager.ensureDoc("documentInfo"), pdfManager.ensureCatalog("metadata")]);
    });
    handler.on("GetMarkInfo", function (data) {
      return pdfManager.ensureCatalog("markInfo");
    });
    handler.on("GetData", function (data) {
      return pdfManager.requestLoadedStream().then(function (stream) {
        return stream.bytes;
      });
    });
    handler.on("GetAnnotations", function ({
      pageIndex,
      intent
    }) {
      return pdfManager.getPage(pageIndex).then(function (page) {
        const task = new WorkerTask(`GetAnnotations: page ${pageIndex}`);
        startWorkerTask(task);
        return page.getAnnotationsData(handler, task, intent).then(data => {
          finishWorkerTask(task);
          return data;
        }, reason => {
          finishWorkerTask(task);
        });
      });
    });
    handler.on("GetFieldObjects", function (data) {
      return pdfManager.ensureDoc("fieldObjects");
    });
    handler.on("HasJSActions", function (data) {
      return pdfManager.ensureDoc("hasJSActions");
    });
    handler.on("GetCalculationOrderIds", function (data) {
      return pdfManager.ensureDoc("calculationOrderIds");
    });
    handler.on("SaveDocument", function ({
      isPureXfa,
      numPages,
      annotationStorage,
      filename
    }) {
      const promises = [pdfManager.requestLoadedStream(), pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("acroFormRef"), pdfManager.ensureDoc("xref"), pdfManager.ensureDoc("startXRef")];
      const newAnnotationsByPage = !isPureXfa ? (0, _core_utils.getNewAnnotationsMap)(annotationStorage) : null;
      if (newAnnotationsByPage) {
        for (const [pageIndex, annotations] of newAnnotationsByPage) {
          promises.push(pdfManager.getPage(pageIndex).then(page => {
            const task = new WorkerTask(`Save (editor): page ${pageIndex}`);
            return page.saveNewAnnotations(handler, task, annotations).finally(function () {
              finishWorkerTask(task);
            });
          }));
        }
      }
      if (isPureXfa) {
        promises.push(pdfManager.serializeXfaData(annotationStorage));
      } else {
        for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
          promises.push(pdfManager.getPage(pageIndex).then(function (page) {
            const task = new WorkerTask(`Save: page ${pageIndex}`);
            return page.save(handler, task, annotationStorage).finally(function () {
              finishWorkerTask(task);
            });
          }));
        }
      }
      return Promise.all(promises).then(function ([stream, acroForm, acroFormRef, xref, startXRef, ...refs]) {
        let newRefs = [];
        let xfaData = null;
        if (isPureXfa) {
          xfaData = refs[0];
          if (!xfaData) {
            return stream.bytes;
          }
        } else {
          newRefs = refs.flat(2);
          if (newRefs.length === 0) {
            return stream.bytes;
          }
        }
        const needAppearances = acroFormRef && acroForm instanceof _primitives.Dict && newRefs.some(ref => ref.needAppearances);
        const xfa = acroForm instanceof _primitives.Dict && acroForm.get("XFA") || null;
        let xfaDatasetsRef = null;
        let hasXfaDatasetsEntry = false;
        if (Array.isArray(xfa)) {
          for (let i = 0, ii = xfa.length; i < ii; i += 2) {
            if (xfa[i] === "datasets") {
              xfaDatasetsRef = xfa[i + 1];
              hasXfaDatasetsEntry = true;
            }
          }
          if (xfaDatasetsRef === null) {
            xfaDatasetsRef = xref.getNewTemporaryRef();
          }
        } else if (xfa) {
          (0, _util.warn)("Unsupported XFA type.");
        }
        let newXrefInfo = Object.create(null);
        if (xref.trailer) {
          const infoObj = Object.create(null);
          const xrefInfo = xref.trailer.get("Info") || null;
          if (xrefInfo instanceof _primitives.Dict) {
            xrefInfo.forEach((key, value) => {
              if (typeof value === "string") {
                infoObj[key] = (0, _util.stringToPDFString)(value);
              }
            });
          }
          newXrefInfo = {
            rootRef: xref.trailer.getRaw("Root") || null,
            encryptRef: xref.trailer.getRaw("Encrypt") || null,
            newRef: xref.getNewTemporaryRef(),
            infoRef: xref.trailer.getRaw("Info") || null,
            info: infoObj,
            fileIds: xref.trailer.get("ID") || null,
            startXRef,
            filename
          };
        }
        try {
          return (0, _writer.incrementalUpdate)({
            originalData: stream.bytes,
            xrefInfo: newXrefInfo,
            newRefs,
            xref,
            hasXfa: !!xfa,
            xfaDatasetsRef,
            hasXfaDatasetsEntry,
            needAppearances,
            acroFormRef,
            acroForm,
            xfaData
          });
        } finally {
          xref.resetNewTemporaryRef();
        }
      });
    });
    handler.on("GetOperatorList", function (data, sink) {
      const pageIndex = data.pageIndex;
      pdfManager.getPage(pageIndex).then(function (page) {
        const task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
        startWorkerTask(task);
        const start = verbosity >= _util.VerbosityLevel.INFOS ? Date.now() : 0;
        page.getOperatorList({
          handler,
          sink,
          task,
          intent: data.intent,
          cacheKey: data.cacheKey,
          annotationStorage: data.annotationStorage
        }).then(function (operatorListInfo) {
          finishWorkerTask(task);
          if (start) {
            (0, _util.info)(`page=${pageIndex + 1} - getOperatorList: time=` + `${Date.now() - start}ms, len=${operatorListInfo.length}`);
          }
          sink.close();
        }, function (reason) {
          finishWorkerTask(task);
          if (task.terminated) {
            return;
          }
          sink.error(reason);
        });
      });
    });
    handler.on("GetTextContent", function (data, sink) {
      const pageIndex = data.pageIndex;
      pdfManager.getPage(pageIndex).then(function (page) {
        const task = new WorkerTask("GetTextContent: page " + pageIndex);
        startWorkerTask(task);
        const start = verbosity >= _util.VerbosityLevel.INFOS ? Date.now() : 0;
        page.extractTextContent({
          handler,
          task,
          sink,
          includeMarkedContent: data.includeMarkedContent,
          combineTextItems: data.combineTextItems
        }).then(function () {
          finishWorkerTask(task);
          if (start) {
            (0, _util.info)(`page=${pageIndex + 1} - getTextContent: time=` + `${Date.now() - start}ms`);
          }
          sink.close();
        }, function (reason) {
          finishWorkerTask(task);
          if (task.terminated) {
            return;
          }
          sink.error(reason);
        });
      });
    });
    handler.on("GetStructTree", function (data) {
      return pdfManager.getPage(data.pageIndex).then(function (page) {
        return pdfManager.ensure(page, "getStructTree");
      });
    });
    handler.on("FontFallback", function (data) {
      return pdfManager.fontFallback(data.id, handler);
    });
    handler.on("Cleanup", function (data) {
      return pdfManager.cleanup(true);
    });
    handler.on("Terminate", function (data) {
      terminated = true;
      const waitOn = [];
      if (pdfManager) {
        pdfManager.terminate(new _util.AbortException("Worker was terminated."));
        const cleanupPromise = pdfManager.cleanup();
        waitOn.push(cleanupPromise);
        pdfManager = null;
      } else {
        (0, _cleanup_helper.clearGlobalCaches)();
      }
      if (cancelXHRs) {
        cancelXHRs(new _util.AbortException("Worker was terminated."));
      }
      for (const task of WorkerTasks) {
        waitOn.push(task.finished);
        task.terminate();
      }
      return Promise.all(waitOn).then(function () {
        handler.destroy();
        handler = null;
      });
    });
    handler.on("Ready", function (data) {
      setupDoc(docParams);
      docParams = null;
    });
    return workerHandlerName;
  }
  static initializeFromPort(port) {
    const handler = new _message_handler.MessageHandler("worker", "main", port);
    WorkerMessageHandler.setup(handler, port);
    handler.send("ready", null);
  }
}
exports.WorkerMessageHandler = WorkerMessageHandler;
function isMessagePort(maybePort) {
  return typeof maybePort.postMessage === "function" && "onmessage" in maybePort;
}
if (typeof window === "undefined" && !_is_node.isNodeJS && typeof self !== "undefined" && isMessagePort(self)) {
  WorkerMessageHandler.initializeFromPort(self);
}

/***/ }),
/* 2 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.LINE_FACTOR = exports.LINE_DESCENT_FACTOR = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.BASELINE_FACTOR = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationEditorType = exports.AnnotationEditorPrefix = exports.AnnotationEditorParamsType = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
exports.arrayByteLength = arrayByteLength;
exports.arraysToBytes = arraysToBytes;
exports.assert = assert;
exports.bytesToString = bytesToString;
exports.createPromiseCapability = createPromiseCapability;
exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
exports.getModificationDate = getModificationDate;
exports.getVerbosityLevel = getVerbosityLevel;
exports.info = info;
exports.isArrayBuffer = isArrayBuffer;
exports.isArrayEqual = isArrayEqual;
exports.objectFromMap = objectFromMap;
exports.objectSize = objectSize;
exports.setVerbosityLevel = setVerbosityLevel;
exports.shadow = shadow;
exports.string32 = string32;
exports.stringToBytes = stringToBytes;
exports.stringToPDFString = stringToPDFString;
exports.stringToUTF8String = stringToUTF8String;
exports.unreachable = unreachable;
exports.utf8StringToString = utf8StringToString;
exports.warn = warn;
;
const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
const LINE_FACTOR = 1.35;
exports.LINE_FACTOR = LINE_FACTOR;
const LINE_DESCENT_FACTOR = 0.35;
exports.LINE_DESCENT_FACTOR = LINE_DESCENT_FACTOR;
const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
exports.BASELINE_FACTOR = BASELINE_FACTOR;
const RenderingIntentFlag = {
  ANY: 0x01,
  DISPLAY: 0x02,
  PRINT: 0x04,
  SAVE: 0x08,
  ANNOTATIONS_FORMS: 0x10,
  ANNOTATIONS_STORAGE: 0x20,
  ANNOTATIONS_DISABLE: 0x40,
  OPLIST: 0x100
};
exports.RenderingIntentFlag = RenderingIntentFlag;
const AnnotationMode = {
  DISABLE: 0,
  ENABLE: 1,
  ENABLE_FORMS: 2,
  ENABLE_STORAGE: 3
};
exports.AnnotationMode = AnnotationMode;
const AnnotationEditorPrefix = "pdfjs_internal_editor_";
exports.AnnotationEditorPrefix = AnnotationEditorPrefix;
const AnnotationEditorType = {
  DISABLE: -1,
  NONE: 0,
  FREETEXT: 3,
  INK: 15
};
exports.AnnotationEditorType = AnnotationEditorType;
const AnnotationEditorParamsType = {
  FREETEXT_SIZE: 1,
  FREETEXT_COLOR: 2,
  FREETEXT_OPACITY: 3,
  INK_COLOR: 11,
  INK_THICKNESS: 12,
  INK_OPACITY: 13
};
exports.AnnotationEditorParamsType = AnnotationEditorParamsType;
const PermissionFlag = {
  PRINT: 0x04,
  MODIFY_CONTENTS: 0x08,
  COPY: 0x10,
  MODIFY_ANNOTATIONS: 0x20,
  FILL_INTERACTIVE_FORMS: 0x100,
  COPY_FOR_ACCESSIBILITY: 0x200,
  ASSEMBLE: 0x400,
  PRINT_HIGH_QUALITY: 0x800
};
exports.PermissionFlag = PermissionFlag;
const TextRenderingMode = {
  FILL: 0,
  STROKE: 1,
  FILL_STROKE: 2,
  INVISIBLE: 3,
  FILL_ADD_TO_PATH: 4,
  STROKE_ADD_TO_PATH: 5,
  FILL_STROKE_ADD_TO_PATH: 6,
  ADD_TO_PATH: 7,
  FILL_STROKE_MASK: 3,
  ADD_TO_PATH_FLAG: 4
};
exports.TextRenderingMode = TextRenderingMode;
const ImageKind = {
  GRAYSCALE_1BPP: 1,
  RGB_24BPP: 2,
  RGBA_32BPP: 3
};
exports.ImageKind = ImageKind;
const AnnotationType = {
  TEXT: 1,
  LINK: 2,
  FREETEXT: 3,
  LINE: 4,
  SQUARE: 5,
  CIRCLE: 6,
  POLYGON: 7,
  POLYLINE: 8,
  HIGHLIGHT: 9,
  UNDERLINE: 10,
  SQUIGGLY: 11,
  STRIKEOUT: 12,
  STAMP: 13,
  CARET: 14,
  INK: 15,
  POPUP: 16,
  FILEATTACHMENT: 17,
  SOUND: 18,
  MOVIE: 19,
  WIDGET: 20,
  SCREEN: 21,
  PRINTERMARK: 22,
  TRAPNET: 23,
  WATERMARK: 24,
  THREED: 25,
  REDACT: 26
};
exports.AnnotationType = AnnotationType;
const AnnotationStateModelType = {
  MARKED: "Marked",
  REVIEW: "Review"
};
exports.AnnotationStateModelType = AnnotationStateModelType;
const AnnotationMarkedState = {
  MARKED: "Marked",
  UNMARKED: "Unmarked"
};
exports.AnnotationMarkedState = AnnotationMarkedState;
const AnnotationReviewState = {
  ACCEPTED: "Accepted",
  REJECTED: "Rejected",
  CANCELLED: "Cancelled",
  COMPLETED: "Completed",
  NONE: "None"
};
exports.AnnotationReviewState = AnnotationReviewState;
const AnnotationReplyType = {
  GROUP: "Group",
  REPLY: "R"
};
exports.AnnotationReplyType = AnnotationReplyType;
const AnnotationFlag = {
  INVISIBLE: 0x01,
  HIDDEN: 0x02,
  PRINT: 0x04,
  NOZOOM: 0x08,
  NOROTATE: 0x10,
  NOVIEW: 0x20,
  READONLY: 0x40,
  LOCKED: 0x80,
  TOGGLENOVIEW: 0x100,
  LOCKEDCONTENTS: 0x200
};
exports.AnnotationFlag = AnnotationFlag;
const AnnotationFieldFlag = {
  READONLY: 0x0000001,
  REQUIRED: 0x0000002,
  NOEXPORT: 0x0000004,
  MULTILINE: 0x0001000,
  PASSWORD: 0x0002000,
  NOTOGGLETOOFF: 0x0004000,
  RADIO: 0x0008000,
  PUSHBUTTON: 0x0010000,
  COMBO: 0x0020000,
  EDIT: 0x0040000,
  SORT: 0x0080000,
  FILESELECT: 0x0100000,
  MULTISELECT: 0x0200000,
  DONOTSPELLCHECK: 0x0400000,
  DONOTSCROLL: 0x0800000,
  COMB: 0x1000000,
  RICHTEXT: 0x2000000,
  RADIOSINUNISON: 0x2000000,
  COMMITONSELCHANGE: 0x4000000
};
exports.AnnotationFieldFlag = AnnotationFieldFlag;
const AnnotationBorderStyleType = {
  SOLID: 1,
  DASHED: 2,
  BEVELED: 3,
  INSET: 4,
  UNDERLINE: 5
};
exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
const AnnotationActionEventType = {
  E: "Mouse Enter",
  X: "Mouse Exit",
  D: "Mouse Down",
  U: "Mouse Up",
  Fo: "Focus",
  Bl: "Blur",
  PO: "PageOpen",
  PC: "PageClose",
  PV: "PageVisible",
  PI: "PageInvisible",
  K: "Keystroke",
  F: "Format",
  V: "Validate",
  C: "Calculate"
};
exports.AnnotationActionEventType = AnnotationActionEventType;
const DocumentActionEventType = {
  WC: "WillClose",
  WS: "WillSave",
  DS: "DidSave",
  WP: "WillPrint",
  DP: "DidPrint"
};
exports.DocumentActionEventType = DocumentActionEventType;
const PageActionEventType = {
  O: "PageOpen",
  C: "PageClose"
};
exports.PageActionEventType = PageActionEventType;
const VerbosityLevel = {
  ERRORS: 0,
  WARNINGS: 1,
  INFOS: 5
};
exports.VerbosityLevel = VerbosityLevel;
const CMapCompressionType = {
  NONE: 0,
  BINARY: 1
};
exports.CMapCompressionType = CMapCompressionType;
const OPS = {
  dependency: 1,
  setLineWidth: 2,
  setLineCap: 3,
  setLineJoin: 4,
  setMiterLimit: 5,
  setDash: 6,
  setRenderingIntent: 7,
  setFlatness: 8,
  setGState: 9,
  save: 10,
  restore: 11,
  transform: 12,
  moveTo: 13,
  lineTo: 14,
  curveTo: 15,
  curveTo2: 16,
  curveTo3: 17,
  closePath: 18,
  rectangle: 19,
  stroke: 20,
  closeStroke: 21,
  fill: 22,
  eoFill: 23,
  fillStroke: 24,
  eoFillStroke: 25,
  closeFillStroke: 26,
  closeEOFillStroke: 27,
  endPath: 28,
  clip: 29,
  eoClip: 30,
  beginText: 31,
  endText: 32,
  setCharSpacing: 33,
  setWordSpacing: 34,
  setHScale: 35,
  setLeading: 36,
  setFont: 37,
  setTextRenderingMode: 38,
  setTextRise: 39,
  moveText: 40,
  setLeadingMoveText: 41,
  setTextMatrix: 42,
  nextLine: 43,
  showText: 44,
  showSpacedText: 45,
  nextLineShowText: 46,
  nextLineSetSpacingShowText: 47,
  setCharWidth: 48,
  setCharWidthAndBounds: 49,
  setStrokeColorSpace: 50,
  setFillColorSpace: 51,
  setStrokeColor: 52,
  setStrokeColorN: 53,
  setFillColor: 54,
  setFillColorN: 55,
  setStrokeGray: 56,
  setFillGray: 57,
  setStrokeRGBColor: 58,
  setFillRGBColor: 59,
  setStrokeCMYKColor: 60,
  setFillCMYKColor: 61,
  shadingFill: 62,
  beginInlineImage: 63,
  beginImageData: 64,
  endInlineImage: 65,
  paintXObject: 66,
  markPoint: 67,
  markPointProps: 68,
  beginMarkedContent: 69,
  beginMarkedContentProps: 70,
  endMarkedContent: 71,
  beginCompat: 72,
  endCompat: 73,
  paintFormXObjectBegin: 74,
  paintFormXObjectEnd: 75,
  beginGroup: 76,
  endGroup: 77,
  beginAnnotation: 80,
  endAnnotation: 81,
  paintImageMaskXObject: 83,
  paintImageMaskXObjectGroup: 84,
  paintImageXObject: 85,
  paintInlineImageXObject: 86,
  paintInlineImageXObjectGroup: 87,
  paintImageXObjectRepeat: 88,
  paintImageMaskXObjectRepeat: 89,
  paintSolidColorImageMask: 90,
  constructPath: 91
};
exports.OPS = OPS;
const UNSUPPORTED_FEATURES = {
  forms: "forms",
  javaScript: "javaScript",
  signatures: "signatures",
  smask: "smask",
  shadingPattern: "shadingPattern",
  errorTilingPattern: "errorTilingPattern",
  errorExtGState: "errorExtGState",
  errorXObject: "errorXObject",
  errorFontLoadType3: "errorFontLoadType3",
  errorFontState: "errorFontState",
  errorFontMissing: "errorFontMissing",
  errorFontTranslate: "errorFontTranslate",
  errorColorSpace: "errorColorSpace",
  errorOperatorList: "errorOperatorList",
  errorFontToUnicode: "errorFontToUnicode",
  errorFontLoadNative: "errorFontLoadNative",
  errorFontBuildPath: "errorFontBuildPath",
  errorFontGetPath: "errorFontGetPath",
  errorMarkedContent: "errorMarkedContent",
  errorContentSubStream: "errorContentSubStream"
};
exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
const PasswordResponses = {
  NEED_PASSWORD: 1,
  INCORRECT_PASSWORD: 2
};
exports.PasswordResponses = PasswordResponses;
let verbosity = VerbosityLevel.WARNINGS;
function setVerbosityLevel(level) {
  if (Number.isInteger(level)) {
    verbosity = level;
  }
}
function getVerbosityLevel() {
  return verbosity;
}
function info(msg) {
  if (verbosity >= VerbosityLevel.INFOS) {
    console.log(`Info: ${msg}`);
  }
}
function warn(msg) {
  if (verbosity >= VerbosityLevel.WARNINGS) {
    console.log(`Warning: ${msg}`);
  }
}
function unreachable(msg) {
  throw new Error(msg);
}
function assert(cond, msg) {
  if (!cond) {
    unreachable(msg);
  }
}
function _isValidProtocol(url) {
  if (!url) {
    return false;
  }
  switch (url.protocol) {
    case "http:":
    case "https:":
    case "ftp:":
    case "mailto:":
    case "tel:":
      return true;
    default:
      return false;
  }
}
function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
  if (!url) {
    return null;
  }
  try {
    if (options && typeof url === "string") {
      if (options.addDefaultProtocol && url.startsWith("www.")) {
        const dots = url.match(/\./g);
        if (dots && dots.length >= 2) {
          url = `http://${url}`;
        }
      }
      if (options.tryConvertEncoding) {
        try {
          url = stringToUTF8String(url);
        } catch (ex) {}
      }
    }
    const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
    if (_isValidProtocol(absoluteUrl)) {
      return absoluteUrl;
    }
  } catch (ex) {}
  return null;
}
function shadow(obj, prop, value, nonSerializable = false) {
  Object.defineProperty(obj, prop, {
    value,
    enumerable: !nonSerializable,
    configurable: true,
    writable: false
  });
  return value;
}
const BaseException = function BaseExceptionClosure() {
  function BaseException(message, name) {
    if (this.constructor === BaseException) {
      unreachable("Cannot initialize BaseException.");
    }
    this.message = message;
    this.name = name;
  }
  BaseException.prototype = new Error();
  BaseException.constructor = BaseException;
  return BaseException;
}();
exports.BaseException = BaseException;
class PasswordException extends BaseException {
  constructor(msg, code) {
    super(msg, "PasswordException");
    this.code = code;
  }
}
exports.PasswordException = PasswordException;
class UnknownErrorException extends BaseException {
  constructor(msg, details) {
    super(msg, "UnknownErrorException");
    this.details = details;
  }
}
exports.UnknownErrorException = UnknownErrorException;
class InvalidPDFException extends BaseException {
  constructor(msg) {
    super(msg, "InvalidPDFException");
  }
}
exports.InvalidPDFException = InvalidPDFException;
class MissingPDFException extends BaseException {
  constructor(msg) {
    super(msg, "MissingPDFException");
  }
}
exports.MissingPDFException = MissingPDFException;
class UnexpectedResponseException extends BaseException {
  constructor(msg, status) {
    super(msg, "UnexpectedResponseException");
    this.status = status;
  }
}
exports.UnexpectedResponseException = UnexpectedResponseException;
class FormatError extends BaseException {
  constructor(msg) {
    super(msg, "FormatError");
  }
}
exports.FormatError = FormatError;
class AbortException extends BaseException {
  constructor(msg) {
    super(msg, "AbortException");
  }
}
exports.AbortException = AbortException;
function bytesToString(bytes) {
  if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
    unreachable("Invalid argument for bytesToString");
  }
  const length = bytes.length;
  const MAX_ARGUMENT_COUNT = 8192;
  if (length < MAX_ARGUMENT_COUNT) {
    return String.fromCharCode.apply(null, bytes);
  }
  const strBuf = [];
  for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
    const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
    const chunk = bytes.subarray(i, chunkEnd);
    strBuf.push(String.fromCharCode.apply(null, chunk));
  }
  return strBuf.join("");
}
function stringToBytes(str) {
  if (typeof str !== "string") {
    unreachable("Invalid argument for stringToBytes");
  }
  const length = str.length;
  const bytes = new Uint8Array(length);
  for (let i = 0; i < length; ++i) {
    bytes[i] = str.charCodeAt(i) & 0xff;
  }
  return bytes;
}
function arrayByteLength(arr) {
  if (arr.length !== undefined) {
    return arr.length;
  }
  if (arr.byteLength !== undefined) {
    return arr.byteLength;
  }
  unreachable("Invalid argument for arrayByteLength");
}
function arraysToBytes(arr) {
  const length = arr.length;
  if (length === 1 && arr[0] instanceof Uint8Array) {
    return arr[0];
  }
  let resultLength = 0;
  for (let i = 0; i < length; i++) {
    resultLength += arrayByteLength(arr[i]);
  }
  let pos = 0;
  const data = new Uint8Array(resultLength);
  for (let i = 0; i < length; i++) {
    let item = arr[i];
    if (!(item instanceof Uint8Array)) {
      if (typeof item === "string") {
        item = stringToBytes(item);
      } else {
        item = new Uint8Array(item);
      }
    }
    const itemLength = item.byteLength;
    data.set(item, pos);
    pos += itemLength;
  }
  return data;
}
function string32(value) {
  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
}
function objectSize(obj) {
  return Object.keys(obj).length;
}
function objectFromMap(map) {
  const obj = Object.create(null);
  for (const [key, value] of map) {
    obj[key] = value;
  }
  return obj;
}
function isLittleEndian() {
  const buffer8 = new Uint8Array(4);
  buffer8[0] = 1;
  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
  return view32[0] === 1;
}
function isEvalSupported() {
  try {
    new Function("");
    return true;
  } catch (e) {
    return false;
  }
}
class FeatureTest {
  static get isLittleEndian() {
    return shadow(this, "isLittleEndian", isLittleEndian());
  }
  static get isEvalSupported() {
    return shadow(this, "isEvalSupported", isEvalSupported());
  }
  static get isOffscreenCanvasSupported() {
    return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
  }
  static get platform() {
    if (typeof navigator === "undefined") {
      return shadow(this, "platform", {
        isWin: false,
        isMac: false
      });
    }
    return shadow(this, "platform", {
      isWin: navigator.platform.includes("Win"),
      isMac: navigator.platform.includes("Mac")
    });
  }
}
exports.FeatureTest = FeatureTest;
const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
class Util {
  static makeHexColor(r, g, b) {
    return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
  }
  static scaleMinMax(transform, minMax) {
    let temp;
    if (transform[0]) {
      if (transform[0] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[1];
        minMax[1] = temp;
      }
      minMax[0] *= transform[0];
      minMax[1] *= transform[0];
      if (transform[3] < 0) {
        temp = minMax[2];
        minMax[2] = minMax[3];
        minMax[3] = temp;
      }
      minMax[2] *= transform[3];
      minMax[3] *= transform[3];
    } else {
      temp = minMax[0];
      minMax[0] = minMax[2];
      minMax[2] = temp;
      temp = minMax[1];
      minMax[1] = minMax[3];
      minMax[3] = temp;
      if (transform[1] < 0) {
        temp = minMax[2];
        minMax[2] = minMax[3];
        minMax[3] = temp;
      }
      minMax[2] *= transform[1];
      minMax[3] *= transform[1];
      if (transform[2] < 0) {
        temp = minMax[0];
        minMax[0] = minMax[1];
        minMax[1] = temp;
      }
      minMax[0] *= transform[2];
      minMax[1] *= transform[2];
    }
    minMax[0] += transform[4];
    minMax[1] += transform[4];
    minMax[2] += transform[5];
    minMax[3] += transform[5];
  }
  static transform(m1, m2) {
    return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
  }
  static applyTransform(p, m) {
    const xt = p[0] * m[0] + p[1] * m[2] + m[4];
    const yt = p[0] * m[1] + p[1] * m[3] + m[5];
    return [xt, yt];
  }
  static applyInverseTransform(p, m) {
    const d = m[0] * m[3] - m[1] * m[2];
    const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
    const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
    return [xt, yt];
  }
  static getAxialAlignedBoundingBox(r, m) {
    const p1 = Util.applyTransform(r, m);
    const p2 = Util.applyTransform(r.slice(2, 4), m);
    const p3 = Util.applyTransform([r[0], r[3]], m);
    const p4 = Util.applyTransform([r[2], r[1]], m);
    return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
  }
  static inverseTransform(m) {
    const d = m[0] * m[3] - m[1] * m[2];
    return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  }
  static singularValueDecompose2dScale(m) {
    const transpose = [m[0], m[2], m[1], m[3]];
    const a = m[0] * transpose[0] + m[1] * transpose[2];
    const b = m[0] * transpose[1] + m[1] * transpose[3];
    const c = m[2] * transpose[0] + m[3] * transpose[2];
    const d = m[2] * transpose[1] + m[3] * transpose[3];
    const first = (a + d) / 2;
    const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
    const sx = first + second || 1;
    const sy = first - second || 1;
    return [Math.sqrt(sx), Math.sqrt(sy)];
  }
  static normalizeRect(rect) {
    const r = rect.slice(0);
    if (rect[0] > rect[2]) {
      r[0] = rect[2];
      r[2] = rect[0];
    }
    if (rect[1] > rect[3]) {
      r[1] = rect[3];
      r[3] = rect[1];
    }
    return r;
  }
  static intersect(rect1, rect2) {
    const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
    const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
    if (xLow > xHigh) {
      return null;
    }
    const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
    const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
    if (yLow > yHigh) {
      return null;
    }
    return [xLow, yLow, xHigh, yHigh];
  }
  static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
    const tvalues = [],
      bounds = [[], []];
    let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
    for (let i = 0; i < 2; ++i) {
      if (i === 0) {
        b = 6 * x0 - 12 * x1 + 6 * x2;
        a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
        c = 3 * x1 - 3 * x0;
      } else {
        b = 6 * y0 - 12 * y1 + 6 * y2;
        a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
        c = 3 * y1 - 3 * y0;
      }
      if (Math.abs(a) < 1e-12) {
        if (Math.abs(b) < 1e-12) {
          continue;
        }
        t = -c / b;
        if (0 < t && t < 1) {
          tvalues.push(t);
        }
        continue;
      }
      b2ac = b * b - 4 * c * a;
      sqrtb2ac = Math.sqrt(b2ac);
      if (b2ac < 0) {
        continue;
      }
      t1 = (-b + sqrtb2ac) / (2 * a);
      if (0 < t1 && t1 < 1) {
        tvalues.push(t1);
      }
      t2 = (-b - sqrtb2ac) / (2 * a);
      if (0 < t2 && t2 < 1) {
        tvalues.push(t2);
      }
    }
    let j = tvalues.length,
      mt;
    const jlen = j;
    while (j--) {
      t = tvalues[j];
      mt = 1 - t;
      bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
      bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
    }
    bounds[0][jlen] = x0;
    bounds[1][jlen] = y0;
    bounds[0][jlen + 1] = x3;
    bounds[1][jlen + 1] = y3;
    bounds[0].length = bounds[1].length = jlen + 2;
    return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
  }
}
exports.Util = Util;
const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
function stringToPDFString(str) {
  if (str[0] >= "\xEF") {
    let encoding;
    if (str[0] === "\xFE" && str[1] === "\xFF") {
      encoding = "utf-16be";
    } else if (str[0] === "\xFF" && str[1] === "\xFE") {
      encoding = "utf-16le";
    } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
      encoding = "utf-8";
    }
    if (encoding) {
      try {
        const decoder = new TextDecoder(encoding, {
          fatal: true
        });
        const buffer = stringToBytes(str);
        return decoder.decode(buffer);
      } catch (ex) {
        warn(`stringToPDFString: "${ex}".`);
      }
    }
  }
  const strBuf = [];
  for (let i = 0, ii = str.length; i < ii; i++) {
    const code = PDFStringTranslateTable[str.charCodeAt(i)];
    strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  }
  return strBuf.join("");
}
function stringToUTF8String(str) {
  return decodeURIComponent(escape(str));
}
function utf8StringToString(str) {
  return unescape(encodeURIComponent(str));
}
function isArrayBuffer(v) {
  return typeof v === "object" && v !== null && v.byteLength !== undefined;
}
function isArrayEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0, ii = arr1.length; i < ii; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}
function getModificationDate(date = new Date()) {
  const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
  return buffer.join("");
}
function createPromiseCapability() {
  const capability = Object.create(null);
  let isSettled = false;
  Object.defineProperty(capability, "settled", {
    get() {
      return isSettled;
    }
  });
  capability.promise = new Promise(function (resolve, reject) {
    capability.resolve = function (data) {
      isSettled = true;
      resolve(data);
    };
    capability.reject = function (reason) {
      isSettled = true;
      reject(reason);
    };
  });
  return capability;
}

/***/ }),
/* 3 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.RefSetCache = exports.RefSet = exports.Ref = exports.Name = exports.EOF = exports.Dict = exports.Cmd = exports.CIRCULAR_REF = void 0;
exports.clearPrimitiveCaches = clearPrimitiveCaches;
exports.isCmd = isCmd;
exports.isDict = isDict;
exports.isName = isName;
exports.isRefsEqual = isRefsEqual;
var _util = __w_pdfjs_require__(2);
const CIRCULAR_REF = Symbol("CIRCULAR_REF");
exports.CIRCULAR_REF = CIRCULAR_REF;
const EOF = Symbol("EOF");
exports.EOF = EOF;
const Name = function NameClosure() {
  let nameCache = Object.create(null);
  class Name {
    constructor(name) {
      this.name = name;
    }
    static get(name) {
      return nameCache[name] || (nameCache[name] = new Name(name));
    }
    static _clearCache() {
      nameCache = Object.create(null);
    }
  }
  return Name;
}();
exports.Name = Name;
const Cmd = function CmdClosure() {
  let cmdCache = Object.create(null);
  class Cmd {
    constructor(cmd) {
      this.cmd = cmd;
    }
    static get(cmd) {
      return cmdCache[cmd] || (cmdCache[cmd] = new Cmd(cmd));
    }
    static _clearCache() {
      cmdCache = Object.create(null);
    }
  }
  return Cmd;
}();
exports.Cmd = Cmd;
const nonSerializable = function nonSerializableClosure() {
  return nonSerializable;
};
class Dict {
  constructor(xref = null) {
    this._map = Object.create(null);
    this.xref = xref;
    this.objId = null;
    this.suppressEncryption = false;
    this.__nonSerializable__ = nonSerializable;
  }
  assignXref(newXref) {
    this.xref = newXref;
  }
  get size() {
    return Object.keys(this._map).length;
  }
  get(key1, key2, key3) {
    let value = this._map[key1];
    if (value === undefined && key2 !== undefined) {
      value = this._map[key2];
      if (value === undefined && key3 !== undefined) {
        value = this._map[key3];
      }
    }
    if (value instanceof Ref && this.xref) {
      return this.xref.fetch(value, this.suppressEncryption);
    }
    return value;
  }
  async getAsync(key1, key2, key3) {
    let value = this._map[key1];
    if (value === undefined && key2 !== undefined) {
      value = this._map[key2];
      if (value === undefined && key3 !== undefined) {
        value = this._map[key3];
      }
    }
    if (value instanceof Ref && this.xref) {
      return this.xref.fetchAsync(value, this.suppressEncryption);
    }
    return value;
  }
  getArray(key1, key2, key3) {
    let value = this._map[key1];
    if (value === undefined && key2 !== undefined) {
      value = this._map[key2];
      if (value === undefined && key3 !== undefined) {
        value = this._map[key3];
      }
    }
    if (value instanceof Ref && this.xref) {
      value = this.xref.fetch(value, this.suppressEncryption);
    }
    if (Array.isArray(value)) {
      value = value.slice();
      for (let i = 0, ii = value.length; i < ii; i++) {
        if (value[i] instanceof Ref && this.xref) {
          value[i] = this.xref.fetch(value[i], this.suppressEncryption);
        }
      }
    }
    return value;
  }
  getRaw(key) {
    return this._map[key];
  }
  getKeys() {
    return Object.keys(this._map);
  }
  getRawValues() {
    return Object.values(this._map);
  }
  set(key, value) {
    this._map[key] = value;
  }
  has(key) {
    return this._map[key] !== undefined;
  }
  forEach(callback) {
    for (const key in this._map) {
      callback(key, this.get(key));
    }
  }
  static get empty() {
    const emptyDict = new Dict(null);
    emptyDict.set = (key, value) => {
      (0, _util.unreachable)("Should not call `set` on the empty dictionary.");
    };
    return (0, _util.shadow)(this, "empty", emptyDict);
  }
  static merge({
    xref,
    dictArray,
    mergeSubDicts = false
  }) {
    const mergedDict = new Dict(xref),
      properties = new Map();
    for (const dict of dictArray) {
      if (!(dict instanceof Dict)) {
        continue;
      }
      for (const [key, value] of Object.entries(dict._map)) {
        let property = properties.get(key);
        if (property === undefined) {
          property = [];
          properties.set(key, property);
        } else if (!mergeSubDicts || !(value instanceof Dict)) {
          continue;
        }
        property.push(value);
      }
    }
    for (const [name, values] of properties) {
      if (values.length === 1 || !(values[0] instanceof Dict)) {
        mergedDict._map[name] = values[0];
        continue;
      }
      const subDict = new Dict(xref);
      for (const dict of values) {
        for (const [key, value] of Object.entries(dict._map)) {
          if (subDict._map[key] === undefined) {
            subDict._map[key] = value;
          }
        }
      }
      if (subDict.size > 0) {
        mergedDict._map[name] = subDict;
      }
    }
    properties.clear();
    return mergedDict.size > 0 ? mergedDict : Dict.empty;
  }
}
exports.Dict = Dict;
const Ref = function RefClosure() {
  let refCache = Object.create(null);
  class Ref {
    constructor(num, gen) {
      this.num = num;
      this.gen = gen;
    }
    toString() {
      if (this.gen === 0) {
        return `${this.num}R`;
      }
      return `${this.num}R${this.gen}`;
    }
    static get(num, gen) {
      const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
      return refCache[key] || (refCache[key] = new Ref(num, gen));
    }
    static _clearCache() {
      refCache = Object.create(null);
    }
  }
  return Ref;
}();
exports.Ref = Ref;
class RefSet {
  constructor(parent = null) {
    this._set = new Set(parent && parent._set);
  }
  has(ref) {
    return this._set.has(ref.toString());
  }
  put(ref) {
    this._set.add(ref.toString());
  }
  remove(ref) {
    this._set.delete(ref.toString());
  }
  [Symbol.iterator]() {
    return this._set.values();
  }
  clear() {
    this._set.clear();
  }
}
exports.RefSet = RefSet;
class RefSetCache {
  constructor() {
    this._map = new Map();
  }
  get size() {
    return this._map.size;
  }
  get(ref) {
    return this._map.get(ref.toString());
  }
  has(ref) {
    return this._map.has(ref.toString());
  }
  put(ref, obj) {
    this._map.set(ref.toString(), obj);
  }
  putAlias(ref, aliasRef) {
    this._map.set(ref.toString(), this.get(aliasRef));
  }
  [Symbol.iterator]() {
    return this._map.values();
  }
  clear() {
    this._map.clear();
  }
}
exports.RefSetCache = RefSetCache;
function isName(v, name) {
  return v instanceof Name && (name === undefined || v.name === name);
}
function isCmd(v, cmd) {
  return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
}
function isDict(v, type) {
  return v instanceof Dict && (type === undefined || isName(v.get("Type"), type));
}
function isRefsEqual(v1, v2) {
  return v1.num === v2.num && v1.gen === v2.gen;
}
function clearPrimitiveCaches() {
  Cmd._clearCache();
  Name._clearCache();
  Ref._clearCache();
}

/***/ }),
/* 4 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.PDF_VERSION_REGEXP = exports.MissingDataException = void 0;
exports.collectActions = collectActions;
exports.encodeToXmlString = encodeToXmlString;
exports.escapePDFName = escapePDFName;
exports.escapeString = escapeString;
exports.getArrayLookupTableFactory = getArrayLookupTableFactory;
exports.getInheritableProperty = getInheritableProperty;
exports.getLookupTableFactory = getLookupTableFactory;
exports.getNewAnnotationsMap = getNewAnnotationsMap;
exports.getRotationMatrix = getRotationMatrix;
exports.isAscii = isAscii;
exports.isWhiteSpace = isWhiteSpace;
exports.log2 = log2;
exports.numberToString = numberToString;
exports.parseXFAPath = parseXFAPath;
exports.readInt8 = readInt8;
exports.readUint16 = readUint16;
exports.readUint32 = readUint32;
exports.recoverJsURL = recoverJsURL;
exports.stringToUTF16HexString = stringToUTF16HexString;
exports.stringToUTF16String = stringToUTF16String;
exports.toRomanNumerals = toRomanNumerals;
exports.validateCSSFont = validateCSSFont;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _base_stream = __w_pdfjs_require__(5);
const PDF_VERSION_REGEXP = /^[1-9]\.\d$/;
exports.PDF_VERSION_REGEXP = PDF_VERSION_REGEXP;
function getLookupTableFactory(initializer) {
  let lookup;
  return function () {
    if (initializer) {
      lookup = Object.create(null);
      initializer(lookup);
      initializer = null;
    }
    return lookup;
  };
}
function getArrayLookupTableFactory(initializer) {
  let lookup;
  return function () {
    if (initializer) {
      let arr = initializer();
      initializer = null;
      lookup = Object.create(null);
      for (let i = 0, ii = arr.length; i < ii; i += 2) {
        lookup[arr[i]] = arr[i + 1];
      }
      arr = null;
    }
    return lookup;
  };
}
class MissingDataException extends _util.BaseException {
  constructor(begin, end) {
    super(`Missing data [${begin}, ${end})`, "MissingDataException");
    this.begin = begin;
    this.end = end;
  }
}
exports.MissingDataException = MissingDataException;
class ParserEOFException extends _util.BaseException {
  constructor(msg) {
    super(msg, "ParserEOFException");
  }
}
exports.ParserEOFException = ParserEOFException;
class XRefEntryException extends _util.BaseException {
  constructor(msg) {
    super(msg, "XRefEntryException");
  }
}
exports.XRefEntryException = XRefEntryException;
class XRefParseException extends _util.BaseException {
  constructor(msg) {
    super(msg, "XRefParseException");
  }
}
exports.XRefParseException = XRefParseException;
function getInheritableProperty({
  dict,
  key,
  getArray = false,
  stopWhenFound = true
}) {
  let values;
  const visited = new _primitives.RefSet();
  while (dict instanceof _primitives.Dict && !(dict.objId && visited.has(dict.objId))) {
    if (dict.objId) {
      visited.put(dict.objId);
    }
    const value = getArray ? dict.getArray(key) : dict.get(key);
    if (value !== undefined) {
      if (stopWhenFound) {
        return value;
      }
      if (!values) {
        values = [];
      }
      values.push(value);
    }
    dict = dict.get("Parent");
  }
  return values;
}
const ROMAN_NUMBER_MAP = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
function toRomanNumerals(number, lowerCase = false) {
  (0, _util.assert)(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
  const romanBuf = [];
  let pos;
  while (number >= 1000) {
    number -= 1000;
    romanBuf.push("M");
  }
  pos = number / 100 | 0;
  number %= 100;
  romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  pos = number / 10 | 0;
  number %= 10;
  romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  const romanStr = romanBuf.join("");
  return lowerCase ? romanStr.toLowerCase() : romanStr;
}
function log2(x) {
  if (x <= 0) {
    return 0;
  }
  return Math.ceil(Math.log2(x));
}
function readInt8(data, offset) {
  return data[offset] << 24 >> 24;
}
function readUint16(data, offset) {
  return data[offset] << 8 | data[offset + 1];
}
function readUint32(data, offset) {
  return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
}
function isWhiteSpace(ch) {
  return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
}
function parseXFAPath(path) {
  const positionPattern = /(.+)\[(\d+)\]$/;
  return path.split(".").map(component => {
    const m = component.match(positionPattern);
    if (m) {
      return {
        name: m[1],
        pos: parseInt(m[2], 10)
      };
    }
    return {
      name: component,
      pos: 0
    };
  });
}
function escapePDFName(str) {
  const buffer = [];
  let start = 0;
  for (let i = 0, ii = str.length; i < ii; i++) {
    const char = str.charCodeAt(i);
    if (char < 0x21 || char > 0x7e || char === 0x23 || char === 0x28 || char === 0x29 || char === 0x3c || char === 0x3e || char === 0x5b || char === 0x5d || char === 0x7b || char === 0x7d || char === 0x2f || char === 0x25) {
      if (start < i) {
        buffer.push(str.substring(start, i));
      }
      buffer.push(`#${char.toString(16)}`);
      start = i + 1;
    }
  }
  if (buffer.length === 0) {
    return str;
  }
  if (start < str.length) {
    buffer.push(str.substring(start, str.length));
  }
  return buffer.join("");
}
function escapeString(str) {
  return str.replace(/([()\\\n\r])/g, match => {
    if (match === "\n") {
      return "\\n";
    } else if (match === "\r") {
      return "\\r";
    }
    return `\\${match}`;
  });
}
function _collectJS(entry, xref, list, parents) {
  if (!entry) {
    return;
  }
  let parent = null;
  if (entry instanceof _primitives.Ref) {
    if (parents.has(entry)) {
      return;
    }
    parent = entry;
    parents.put(parent);
    entry = xref.fetch(entry);
  }
  if (Array.isArray(entry)) {
    for (const element of entry) {
      _collectJS(element, xref, list, parents);
    }
  } else if (entry instanceof _primitives.Dict) {
    if ((0, _primitives.isName)(entry.get("S"), "JavaScript")) {
      const js = entry.get("JS");
      let code;
      if (js instanceof _base_stream.BaseStream) {
        code = js.getString();
      } else if (typeof js === "string") {
        code = js;
      }
      code = code && (0, _util.stringToPDFString)(code).replace(/\u0000/g, "");
      if (code) {
        list.push(code);
      }
    }
    _collectJS(entry.getRaw("Next"), xref, list, parents);
  }
  if (parent) {
    parents.remove(parent);
  }
}
function collectActions(xref, dict, eventType) {
  const actions = Object.create(null);
  const additionalActionsDicts = getInheritableProperty({
    dict,
    key: "AA",
    stopWhenFound: false
  });
  if (additionalActionsDicts) {
    for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
      const additionalActions = additionalActionsDicts[i];
      if (!(additionalActions instanceof _primitives.Dict)) {
        continue;
      }
      for (const key of additionalActions.getKeys()) {
        const action = eventType[key];
        if (!action) {
          continue;
        }
        const actionDict = additionalActions.getRaw(key);
        const parents = new _primitives.RefSet();
        const list = [];
        _collectJS(actionDict, xref, list, parents);
        if (list.length > 0) {
          actions[action] = list;
        }
      }
    }
  }
  if (dict.has("A")) {
    const actionDict = dict.get("A");
    const parents = new _primitives.RefSet();
    const list = [];
    _collectJS(actionDict, xref, list, parents);
    if (list.length > 0) {
      actions.Action = list;
    }
  }
  return (0, _util.objectSize)(actions) > 0 ? actions : null;
}
const XMLEntities = {
  0x3c: "&lt;",
  0x3e: "&gt;",
  0x26: "&amp;",
  0x22: "&quot;",
  0x27: "&apos;"
};
function encodeToXmlString(str) {
  const buffer = [];
  let start = 0;
  for (let i = 0, ii = str.length; i < ii; i++) {
    const char = str.codePointAt(i);
    if (0x20 <= char && char <= 0x7e) {
      const entity = XMLEntities[char];
      if (entity) {
        if (start < i) {
          buffer.push(str.substring(start, i));
        }
        buffer.push(entity);
        start = i + 1;
      }
    } else {
      if (start < i) {
        buffer.push(str.substring(start, i));
      }
      buffer.push(`&#x${char.toString(16).toUpperCase()};`);
      if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
        i++;
      }
      start = i + 1;
    }
  }
  if (buffer.length === 0) {
    return str;
  }
  if (start < str.length) {
    buffer.push(str.substring(start, str.length));
  }
  return buffer.join("");
}
function validateCSSFont(cssFontInfo) {
  const DEFAULT_CSS_FONT_OBLIQUE = "14";
  const DEFAULT_CSS_FONT_WEIGHT = "400";
  const CSS_FONT_WEIGHT_VALUES = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900", "1000", "normal", "bold", "bolder", "lighter"]);
  const {
    fontFamily,
    fontWeight,
    italicAngle
  } = cssFontInfo;
  if (/^".*"$/.test(fontFamily)) {
    if (/[^\\]"/.test(fontFamily.slice(1, fontFamily.length - 1))) {
      (0, _util.warn)(`XFA - FontFamily contains some unescaped ": ${fontFamily}.`);
      return false;
    }
  } else if (/^'.*'$/.test(fontFamily)) {
    if (/[^\\]'/.test(fontFamily.slice(1, fontFamily.length - 1))) {
      (0, _util.warn)(`XFA - FontFamily contains some unescaped ': ${fontFamily}.`);
      return false;
    }
  } else {
    for (const ident of fontFamily.split(/[ \t]+/)) {
      if (/^(\d|(-(\d|-)))/.test(ident) || !/^[\w-\\]+$/.test(ident)) {
        (0, _util.warn)(`XFA - FontFamily contains some invalid <custom-ident>: ${fontFamily}.`);
        return false;
      }
    }
  }
  const weight = fontWeight ? fontWeight.toString() : "";
  cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
  const angle = parseFloat(italicAngle);
  cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
  return true;
}
function recoverJsURL(str) {
  const URL_OPEN_METHODS = ["app.launchURL", "window.open", "xfa.host.gotoURL"];
  const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
  const jsUrl = regex.exec(str);
  if (jsUrl && jsUrl[2]) {
    const url = jsUrl[2];
    let newWindow = false;
    if (jsUrl[3] === "true" && jsUrl[1] === "app.launchURL") {
      newWindow = true;
    }
    return {
      url,
      newWindow
    };
  }
  return null;
}
function numberToString(value) {
  if (Number.isInteger(value)) {
    return value.toString();
  }
  const roundedValue = Math.round(value * 100);
  if (roundedValue % 100 === 0) {
    return (roundedValue / 100).toString();
  }
  if (roundedValue % 10 === 0) {
    return value.toFixed(1);
  }
  return value.toFixed(2);
}
function getNewAnnotationsMap(annotationStorage) {
  if (!annotationStorage) {
    return null;
  }
  const newAnnotationsByPage = new Map();
  for (const [key, value] of annotationStorage) {
    if (!key.startsWith(_util.AnnotationEditorPrefix)) {
      continue;
    }
    let annotations = newAnnotationsByPage.get(value.pageIndex);
    if (!annotations) {
      annotations = [];
      newAnnotationsByPage.set(value.pageIndex, annotations);
    }
    annotations.push(value);
  }
  return newAnnotationsByPage.size > 0 ? newAnnotationsByPage : null;
}
function isAscii(str) {
  return /^[\x00-\x7F]*$/.test(str);
}
function stringToUTF16HexString(str) {
  const buf = [];
  for (let i = 0, ii = str.length; i < ii; i++) {
    const char = str.charCodeAt(i);
    buf.push((char >> 8 & 0xff).toString(16).padStart(2, "0"), (char & 0xff).toString(16).padStart(2, "0"));
  }
  return buf.join("");
}
function stringToUTF16String(str, bigEndian = false) {
  const buf = [];
  if (bigEndian) {
    buf.push("\xFE\xFF");
  }
  for (let i = 0, ii = str.length; i < ii; i++) {
    const char = str.charCodeAt(i);
    buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
  }
  return buf.join("");
}
function getRotationMatrix(rotation, width, height) {
  switch (rotation) {
    case 90:
      return [0, 1, -1, 0, width, 0];
    case 180:
      return [-1, 0, 0, -1, width, height];
    case 270:
      return [0, -1, 1, 0, 0, height];
    default:
      throw new Error("Invalid rotation");
  }
}

/***/ }),
/* 5 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.BaseStream = void 0;
var _util = __w_pdfjs_require__(2);
class BaseStream {
  constructor() {
    if (this.constructor === BaseStream) {
      (0, _util.unreachable)("Cannot initialize BaseStream.");
    }
  }
  get length() {
    (0, _util.unreachable)("Abstract getter `length` accessed");
  }
  get isEmpty() {
    (0, _util.unreachable)("Abstract getter `isEmpty` accessed");
  }
  get isDataLoaded() {
    return (0, _util.shadow)(this, "isDataLoaded", true);
  }
  getByte() {
    (0, _util.unreachable)("Abstract method `getByte` called");
  }
  getBytes(length) {
    (0, _util.unreachable)("Abstract method `getBytes` called");
  }
  peekByte() {
    const peekedByte = this.getByte();
    if (peekedByte !== -1) {
      this.pos--;
    }
    return peekedByte;
  }
  peekBytes(length) {
    const bytes = this.getBytes(length);
    this.pos -= bytes.length;
    return bytes;
  }
  getUint16() {
    const b0 = this.getByte();
    const b1 = this.getByte();
    if (b0 === -1 || b1 === -1) {
      return -1;
    }
    return (b0 << 8) + b1;
  }
  getInt32() {
    const b0 = this.getByte();
    const b1 = this.getByte();
    const b2 = this.getByte();
    const b3 = this.getByte();
    return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  }
  getByteRange(begin, end) {
    (0, _util.unreachable)("Abstract method `getByteRange` called");
  }
  getString(length) {
    return (0, _util.bytesToString)(this.getBytes(length));
  }
  skip(n) {
    this.pos += n || 1;
  }
  reset() {
    (0, _util.unreachable)("Abstract method `reset` called");
  }
  moveStart() {
    (0, _util.unreachable)("Abstract method `moveStart` called");
  }
  makeSubStream(start, length, dict = null) {
    (0, _util.unreachable)("Abstract method `makeSubStream` called");
  }
  getBaseStreams() {
    return null;
  }
}
exports.BaseStream = BaseStream;

/***/ }),
/* 6 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.NetworkPdfManager = exports.LocalPdfManager = void 0;
var _util = __w_pdfjs_require__(2);
var _chunked_stream = __w_pdfjs_require__(7);
var _core_utils = __w_pdfjs_require__(4);
var _document = __w_pdfjs_require__(9);
var _stream = __w_pdfjs_require__(8);
function parseDocBaseUrl(url) {
  if (url) {
    const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url);
    if (absoluteUrl) {
      return absoluteUrl.href;
    }
    (0, _util.warn)(`Invalid absolute docBaseUrl: "${url}".`);
  }
  return null;
}
class BasePdfManager {
  constructor() {
    if (this.constructor === BasePdfManager) {
      (0, _util.unreachable)("Cannot initialize BasePdfManager.");
    }
  }
  get docId() {
    return this._docId;
  }
  get password() {
    return this._password;
  }
  get docBaseUrl() {
    const catalog = this.pdfDocument.catalog;
    return (0, _util.shadow)(this, "docBaseUrl", catalog.baseUrl || this._docBaseUrl);
  }
  ensureDoc(prop, args) {
    return this.ensure(this.pdfDocument, prop, args);
  }
  ensureXRef(prop, args) {
    return this.ensure(this.pdfDocument.xref, prop, args);
  }
  ensureCatalog(prop, args) {
    return this.ensure(this.pdfDocument.catalog, prop, args);
  }
  getPage(pageIndex) {
    return this.pdfDocument.getPage(pageIndex);
  }
  fontFallback(id, handler) {
    return this.pdfDocument.fontFallback(id, handler);
  }
  loadXfaFonts(handler, task) {
    return this.pdfDocument.loadXfaFonts(handler, task);
  }
  loadXfaImages() {
    return this.pdfDocument.loadXfaImages();
  }
  serializeXfaData(annotationStorage) {
    return this.pdfDocument.serializeXfaData(annotationStorage);
  }
  cleanup(manuallyTriggered = false) {
    return this.pdfDocument.cleanup(manuallyTriggered);
  }
  async ensure(obj, prop, args) {
    (0, _util.unreachable)("Abstract method `ensure` called");
  }
  requestRange(begin, end) {
    (0, _util.unreachable)("Abstract method `requestRange` called");
  }
  requestLoadedStream(noFetch = false) {
    (0, _util.unreachable)("Abstract method `requestLoadedStream` called");
  }
  sendProgressiveData(chunk) {
    (0, _util.unreachable)("Abstract method `sendProgressiveData` called");
  }
  updatePassword(password) {
    this._password = password;
  }
  terminate(reason) {
    (0, _util.unreachable)("Abstract method `terminate` called");
  }
}
class LocalPdfManager extends BasePdfManager {
  constructor(docId, data, password, msgHandler, evaluatorOptions, enableXfa, docBaseUrl) {
    super();
    this._docId = docId;
    this._password = password;
    this._docBaseUrl = parseDocBaseUrl(docBaseUrl);
    this.msgHandler = msgHandler;
    this.evaluatorOptions = evaluatorOptions;
    this.enableXfa = enableXfa;
    const stream = new _stream.Stream(data);
    this.pdfDocument = new _document.PDFDocument(this, stream);
    this._loadedStreamPromise = Promise.resolve(stream);
  }
  async ensure(obj, prop, args) {
    const value = obj[prop];
    if (typeof value === "function") {
      return value.apply(obj, args);
    }
    return value;
  }
  requestRange(begin, end) {
    return Promise.resolve();
  }
  requestLoadedStream(noFetch = false) {
    return this._loadedStreamPromise;
  }
  terminate(reason) {}
}
exports.LocalPdfManager = LocalPdfManager;
class NetworkPdfManager extends BasePdfManager {
  constructor(docId, pdfNetworkStream, args, evaluatorOptions, enableXfa, docBaseUrl) {
    super();
    this._docId = docId;
    this._password = args.password;
    this._docBaseUrl = parseDocBaseUrl(docBaseUrl);
    this.msgHandler = args.msgHandler;
    this.evaluatorOptions = evaluatorOptions;
    this.enableXfa = enableXfa;
    this.streamManager = new _chunked_stream.ChunkedStreamManager(pdfNetworkStream, {
      msgHandler: args.msgHandler,
      length: args.length,
      disableAutoFetch: args.disableAutoFetch,
      rangeChunkSize: args.rangeChunkSize
    });
    this.pdfDocument = new _document.PDFDocument(this, this.streamManager.getStream());
  }
  async ensure(obj, prop, args) {
    try {
      const value = obj[prop];
      if (typeof value === "function") {
        return value.apply(obj, args);
      }
      return value;
    } catch (ex) {
      if (!(ex instanceof _core_utils.MissingDataException)) {
        throw ex;
      }
      await this.requestRange(ex.begin, ex.end);
      return this.ensure(obj, prop, args);
    }
  }
  requestRange(begin, end) {
    return this.streamManager.requestRange(begin, end);
  }
  requestLoadedStream(noFetch = false) {
    return this.streamManager.requestAllChunks(noFetch);
  }
  sendProgressiveData(chunk) {
    this.streamManager.onReceiveData({
      chunk
    });
  }
  terminate(reason) {
    this.streamManager.abort(reason);
  }
}
exports.NetworkPdfManager = NetworkPdfManager;

/***/ }),
/* 7 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ChunkedStreamManager = exports.ChunkedStream = void 0;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _stream = __w_pdfjs_require__(8);
class ChunkedStream extends _stream.Stream {
  constructor(length, chunkSize, manager) {
    super(new Uint8Array(length), 0, length, null);
    this.chunkSize = chunkSize;
    this._loadedChunks = new Set();
    this.numChunks = Math.ceil(length / chunkSize);
    this.manager = manager;
    this.progressiveDataLength = 0;
    this.lastSuccessfulEnsureByteChunk = -1;
  }
  getMissingChunks() {
    const chunks = [];
    for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
      if (!this._loadedChunks.has(chunk)) {
        chunks.push(chunk);
      }
    }
    return chunks;
  }
  get numChunksLoaded() {
    return this._loadedChunks.size;
  }
  get isDataLoaded() {
    return this.numChunksLoaded === this.numChunks;
  }
  onReceiveData(begin, chunk) {
    const chunkSize = this.chunkSize;
    if (begin % chunkSize !== 0) {
      throw new Error(`Bad begin offset: ${begin}`);
    }
    const end = begin + chunk.byteLength;
    if (end % chunkSize !== 0 && end !== this.bytes.length) {
      throw new Error(`Bad end offset: ${end}`);
    }
    this.bytes.set(new Uint8Array(chunk), begin);
    const beginChunk = Math.floor(begin / chunkSize);
    const endChunk = Math.floor((end - 1) / chunkSize) + 1;
    for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
      this._loadedChunks.add(curChunk);
    }
  }
  onReceiveProgressiveData(data) {
    let position = this.progressiveDataLength;
    const beginChunk = Math.floor(position / this.chunkSize);
    this.bytes.set(new Uint8Array(data), position);
    position += data.byteLength;
    this.progressiveDataLength = position;
    const endChunk = position >= this.end ? this.numChunks : Math.floor(position / this.chunkSize);
    for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
      this._loadedChunks.add(curChunk);
    }
  }
  ensureByte(pos) {
    if (pos < this.progressiveDataLength) {
      return;
    }
    const chunk = Math.floor(pos / this.chunkSize);
    if (chunk > this.numChunks) {
      return;
    }
    if (chunk === this.lastSuccessfulEnsureByteChunk) {
      return;
    }
    if (!this._loadedChunks.has(chunk)) {
      throw new _core_utils.MissingDataException(pos, pos + 1);
    }
    this.lastSuccessfulEnsureByteChunk = chunk;
  }
  ensureRange(begin, end) {
    if (begin >= end) {
      return;
    }
    if (end <= this.progressiveDataLength) {
      return;
    }
    const beginChunk = Math.floor(begin / this.chunkSize);
    if (beginChunk > this.numChunks) {
      return;
    }
    const endChunk = Math.min(Math.floor((end - 1) / this.chunkSize) + 1, this.numChunks);
    for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
      if (!this._loadedChunks.has(chunk)) {
        throw new _core_utils.MissingDataException(begin, end);
      }
    }
  }
  nextEmptyChunk(beginChunk) {
    const numChunks = this.numChunks;
    for (let i = 0; i < numChunks; ++i) {
      const chunk = (beginChunk + i) % numChunks;
      if (!this._loadedChunks.has(chunk)) {
        return chunk;
      }
    }
    return null;
  }
  hasChunk(chunk) {
    return this._loadedChunks.has(chunk);
  }
  getByte() {
    const pos = this.pos;
    if (pos >= this.end) {
      return -1;
    }
    if (pos >= this.progressiveDataLength) {
      this.ensureByte(pos);
    }
    return this.bytes[this.pos++];
  }
  getBytes(length) {
    const bytes = this.bytes;
    const pos = this.pos;
    const strEnd = this.end;
    if (!length) {
      if (strEnd > this.progressiveDataLength) {
        this.ensureRange(pos, strEnd);
      }
      return bytes.subarray(pos, strEnd);
    }
    let end = pos + length;
    if (end > strEnd) {
      end = strEnd;
    }
    if (end > this.progressiveDataLength) {
      this.ensureRange(pos, end);
    }
    this.pos = end;
    return bytes.subarray(pos, end);
  }
  getByteRange(begin, end) {
    if (begin < 0) {
      begin = 0;
    }
    if (end > this.end) {
      end = this.end;
    }
    if (end > this.progressiveDataLength) {
      this.ensureRange(begin, end);
    }
    return this.bytes.subarray(begin, end);
  }
  makeSubStream(start, length, dict = null) {
    if (length) {
      if (start + length > this.progressiveDataLength) {
        this.ensureRange(start, start + length);
      }
    } else {
      if (start >= this.progressiveDataLength) {
        this.ensureByte(start);
      }
    }
    function ChunkedStreamSubstream() {}
    ChunkedStreamSubstream.prototype = Object.create(this);
    ChunkedStreamSubstream.prototype.getMissingChunks = function () {
      const chunkSize = this.chunkSize;
      const beginChunk = Math.floor(this.start / chunkSize);
      const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
      const missingChunks = [];
      for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
        if (!this._loadedChunks.has(chunk)) {
          missingChunks.push(chunk);
        }
      }
      return missingChunks;
    };
    Object.defineProperty(ChunkedStreamSubstream.prototype, "isDataLoaded", {
      get() {
        if (this.numChunksLoaded === this.numChunks) {
          return true;
        }
        return this.getMissingChunks().length === 0;
      },
      configurable: true
    });
    const subStream = new ChunkedStreamSubstream();
    subStream.pos = subStream.start = start;
    subStream.end = start + length || this.end;
    subStream.dict = dict;
    return subStream;
  }
  getBaseStreams() {
    return [this];
  }
}
exports.ChunkedStream = ChunkedStream;
class ChunkedStreamManager {
  constructor(pdfNetworkStream, args) {
    this.length = args.length;
    this.chunkSize = args.rangeChunkSize;
    this.stream = new ChunkedStream(this.length, this.chunkSize, this);
    this.pdfNetworkStream = pdfNetworkStream;
    this.disableAutoFetch = args.disableAutoFetch;
    this.msgHandler = args.msgHandler;
    this.currRequestId = 0;
    this._chunksNeededByRequest = new Map();
    this._requestsByChunk = new Map();
    this._promisesByRequest = new Map();
    this.progressiveDataLength = 0;
    this.aborted = false;
    this._loadedStreamCapability = (0, _util.createPromiseCapability)();
  }
  sendRequest(begin, end) {
    const rangeReader = this.pdfNetworkStream.getRangeReader(begin, end);
    if (!rangeReader.isStreamingSupported) {
      rangeReader.onProgress = this.onProgress.bind(this);
    }
    let chunks = [],
      loaded = 0;
    return new Promise((resolve, reject) => {
      const readChunk = chunk => {
        try {
          if (!chunk.done) {
            const data = chunk.value;
            chunks.push(data);
            loaded += (0, _util.arrayByteLength)(data);
            if (rangeReader.isStreamingSupported) {
              this.onProgress({
                loaded
              });
            }
            rangeReader.read().then(readChunk, reject);
            return;
          }
          const chunkData = (0, _util.arraysToBytes)(chunks);
          chunks = null;
          resolve(chunkData);
        } catch (e) {
          reject(e);
        }
      };
      rangeReader.read().then(readChunk, reject);
    }).then(data => {
      if (this.aborted) {
        return;
      }
      this.onReceiveData({
        chunk: data,
        begin
      });
    });
  }
  requestAllChunks(noFetch = false) {
    if (!noFetch) {
      const missingChunks = this.stream.getMissingChunks();
      this._requestChunks(missingChunks);
    }
    return this._loadedStreamCapability.promise;
  }
  _requestChunks(chunks) {
    const requestId = this.currRequestId++;
    const chunksNeeded = new Set();
    this._chunksNeededByRequest.set(requestId, chunksNeeded);
    for (const chunk of chunks) {
      if (!this.stream.hasChunk(chunk)) {
        chunksNeeded.add(chunk);
      }
    }
    if (chunksNeeded.size === 0) {
      return Promise.resolve();
    }
    const capability = (0, _util.createPromiseCapability)();
    this._promisesByRequest.set(requestId, capability);
    const chunksToRequest = [];
    for (const chunk of chunksNeeded) {
      let requestIds = this._requestsByChunk.get(chunk);
      if (!requestIds) {
        requestIds = [];
        this._requestsByChunk.set(chunk, requestIds);
        chunksToRequest.push(chunk);
      }
      requestIds.push(requestId);
    }
    if (chunksToRequest.length > 0) {
      const groupedChunksToRequest = this.groupChunks(chunksToRequest);
      for (const groupedChunk of groupedChunksToRequest) {
        const begin = groupedChunk.beginChunk * this.chunkSize;
        const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
        this.sendRequest(begin, end).catch(capability.reject);
      }
    }
    return capability.promise.catch(reason => {
      if (this.aborted) {
        return;
      }
      throw reason;
    });
  }
  getStream() {
    return this.stream;
  }
  requestRange(begin, end) {
    end = Math.min(end, this.length);
    const beginChunk = this.getBeginChunk(begin);
    const endChunk = this.getEndChunk(end);
    const chunks = [];
    for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
      chunks.push(chunk);
    }
    return this._requestChunks(chunks);
  }
  requestRanges(ranges = []) {
    const chunksToRequest = [];
    for (const range of ranges) {
      const beginChunk = this.getBeginChunk(range.begin);
      const endChunk = this.getEndChunk(range.end);
      for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
        if (!chunksToRequest.includes(chunk)) {
          chunksToRequest.push(chunk);
        }
      }
    }
    chunksToRequest.sort(function (a, b) {
      return a - b;
    });
    return this._requestChunks(chunksToRequest);
  }
  groupChunks(chunks) {
    const groupedChunks = [];
    let beginChunk = -1;
    let prevChunk = -1;
    for (let i = 0, ii = chunks.length; i < ii; ++i) {
      const chunk = chunks[i];
      if (beginChunk < 0) {
        beginChunk = chunk;
      }
      if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
        groupedChunks.push({
          beginChunk,
          endChunk: prevChunk + 1
        });
        beginChunk = chunk;
      }
      if (i + 1 === chunks.length) {
        groupedChunks.push({
          beginChunk,
          endChunk: chunk + 1
        });
      }
      prevChunk = chunk;
    }
    return groupedChunks;
  }
  onProgress(args) {
    this.msgHandler.send("DocProgress", {
      loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded,
      total: this.length
    });
  }
  onReceiveData(args) {
    const chunk = args.chunk;
    const isProgressive = args.begin === undefined;
    const begin = isProgressive ? this.progressiveDataLength : args.begin;
    const end = begin + chunk.byteLength;
    const beginChunk = Math.floor(begin / this.chunkSize);
    const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : Math.ceil(end / this.chunkSize);
    if (isProgressive) {
      this.stream.onReceiveProgressiveData(chunk);
      this.progressiveDataLength = end;
    } else {
      this.stream.onReceiveData(begin, chunk);
    }
    if (this.stream.isDataLoaded) {
      this._loadedStreamCapability.resolve(this.stream);
    }
    const loadedRequests = [];
    for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
      const requestIds = this._requestsByChunk.get(curChunk);
      if (!requestIds) {
        continue;
      }
      this._requestsByChunk.delete(curChunk);
      for (const requestId of requestIds) {
        const chunksNeeded = this._chunksNeededByRequest.get(requestId);
        if (chunksNeeded.has(curChunk)) {
          chunksNeeded.delete(curChunk);
        }
        if (chunksNeeded.size > 0) {
          continue;
        }
        loadedRequests.push(requestId);
      }
    }
    if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
      let nextEmptyChunk;
      if (this.stream.numChunksLoaded === 1) {
        const lastChunk = this.stream.numChunks - 1;
        if (!this.stream.hasChunk(lastChunk)) {
          nextEmptyChunk = lastChunk;
        }
      } else {
        nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
      }
      if (Number.isInteger(nextEmptyChunk)) {
        this._requestChunks([nextEmptyChunk]);
      }
    }
    for (const requestId of loadedRequests) {
      const capability = this._promisesByRequest.get(requestId);
      this._promisesByRequest.delete(requestId);
      capability.resolve();
    }
    this.msgHandler.send("DocProgress", {
      loaded: this.stream.numChunksLoaded * this.chunkSize,
      total: this.length
    });
  }
  onError(err) {
    this._loadedStreamCapability.reject(err);
  }
  getBeginChunk(begin) {
    return Math.floor(begin / this.chunkSize);
  }
  getEndChunk(end) {
    return Math.floor((end - 1) / this.chunkSize) + 1;
  }
  abort(reason) {
    this.aborted = true;
    if (this.pdfNetworkStream) {
      this.pdfNetworkStream.cancelAllRequests(reason);
    }
    for (const capability of this._promisesByRequest.values()) {
      capability.reject(reason);
    }
  }
}
exports.ChunkedStreamManager = ChunkedStreamManager;

/***/ }),
/* 8 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.StringStream = exports.Stream = exports.NullStream = void 0;
var _base_stream = __w_pdfjs_require__(5);
var _util = __w_pdfjs_require__(2);
class Stream extends _base_stream.BaseStream {
  constructor(arrayBuffer, start, length, dict) {
    super();
    this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer : new Uint8Array(arrayBuffer);
    this.start = start || 0;
    this.pos = this.start;
    this.end = start + length || this.bytes.length;
    this.dict = dict;
  }
  get length() {
    return this.end - this.start;
  }
  get isEmpty() {
    return this.length === 0;
  }
  getByte() {
    if (this.pos >= this.end) {
      return -1;
    }
    return this.bytes[this.pos++];
  }
  getBytes(length) {
    const bytes = this.bytes;
    const pos = this.pos;
    const strEnd = this.end;
    if (!length) {
      return bytes.subarray(pos, strEnd);
    }
    let end = pos + length;
    if (end > strEnd) {
      end = strEnd;
    }
    this.pos = end;
    return bytes.subarray(pos, end);
  }
  getByteRange(begin, end) {
    if (begin < 0) {
      begin = 0;
    }
    if (end > this.end) {
      end = this.end;
    }
    return this.bytes.subarray(begin, end);
  }
  reset() {
    this.pos = this.start;
  }
  moveStart() {
    this.start = this.pos;
  }
  makeSubStream(start, length, dict = null) {
    return new Stream(this.bytes.buffer, start, length, dict);
  }
}
exports.Stream = Stream;
class StringStream extends Stream {
  constructor(str) {
    super((0, _util.stringToBytes)(str));
  }
}
exports.StringStream = StringStream;
class NullStream extends Stream {
  constructor() {
    super(new Uint8Array(0));
  }
}
exports.NullStream = NullStream;

/***/ }),
/* 9 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Page = exports.PDFDocument = void 0;
var _annotation = __w_pdfjs_require__(10);
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _primitives = __w_pdfjs_require__(3);
var _xfa_fonts = __w_pdfjs_require__(49);
var _base_stream = __w_pdfjs_require__(5);
var _crypto = __w_pdfjs_require__(65);
var _catalog = __w_pdfjs_require__(67);
var _cleanup_helper = __w_pdfjs_require__(69);
var _dataset_reader = __w_pdfjs_require__(98);
var _parser = __w_pdfjs_require__(15);
var _stream = __w_pdfjs_require__(8);
var _object_loader = __w_pdfjs_require__(73);
var _operator_list = __w_pdfjs_require__(60);
var _evaluator = __w_pdfjs_require__(13);
var _decode_stream = __w_pdfjs_require__(17);
var _struct_tree = __w_pdfjs_require__(72);
var _writer = __w_pdfjs_require__(63);
var _factory = __w_pdfjs_require__(74);
var _xref = __w_pdfjs_require__(99);
const DEFAULT_USER_UNIT = 1.0;
const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
class Page {
  constructor({
    pdfManager,
    xref,
    pageIndex,
    pageDict,
    ref,
    globalIdFactory,
    fontCache,
    builtInCMapCache,
    standardFontDataCache,
    globalImageCache,
    nonBlendModesSet,
    xfaFactory
  }) {
    this.pdfManager = pdfManager;
    this.pageIndex = pageIndex;
    this.pageDict = pageDict;
    this.xref = xref;
    this.ref = ref;
    this.fontCache = fontCache;
    this.builtInCMapCache = builtInCMapCache;
    this.standardFontDataCache = standardFontDataCache;
    this.globalImageCache = globalImageCache;
    this.nonBlendModesSet = nonBlendModesSet;
    this.evaluatorOptions = pdfManager.evaluatorOptions;
    this.resourcesPromise = null;
    this.xfaFactory = xfaFactory;
    const idCounters = {
      obj: 0
    };
    this._localIdFactory = class extends globalIdFactory {
      static createObjId() {
        return `p${pageIndex}_${++idCounters.obj}`;
      }
      static getPageObjId() {
        return `page${ref.toString()}`;
      }
    };
  }
  _getInheritableProperty(key, getArray = false) {
    const value = (0, _core_utils.getInheritableProperty)({
      dict: this.pageDict,
      key,
      getArray,
      stopWhenFound: false
    });
    if (!Array.isArray(value)) {
      return value;
    }
    if (value.length === 1 || !(value[0] instanceof _primitives.Dict)) {
      return value[0];
    }
    return _primitives.Dict.merge({
      xref: this.xref,
      dictArray: value
    });
  }
  get content() {
    return this.pageDict.getArray("Contents");
  }
  get resources() {
    const resources = this._getInheritableProperty("Resources");
    return (0, _util.shadow)(this, "resources", resources instanceof _primitives.Dict ? resources : _primitives.Dict.empty);
  }
  _getBoundingBox(name) {
    if (this.xfaData) {
      return this.xfaData.bbox;
    }
    let box = this._getInheritableProperty(name, true);
    if (Array.isArray(box) && box.length === 4) {
      box = _util.Util.normalizeRect(box);
      if (box[2] - box[0] > 0 && box[3] - box[1] > 0) {
        return box;
      }
      (0, _util.warn)(`Empty, or invalid, /${name} entry.`);
    }
    return null;
  }
  get mediaBox() {
    return (0, _util.shadow)(this, "mediaBox", this._getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
  }
  get cropBox() {
    return (0, _util.shadow)(this, "cropBox", this._getBoundingBox("CropBox") || this.mediaBox);
  }
  get userUnit() {
    let obj = this.pageDict.get("UserUnit");
    if (typeof obj !== "number" || obj <= 0) {
      obj = DEFAULT_USER_UNIT;
    }
    return (0, _util.shadow)(this, "userUnit", obj);
  }
  get view() {
    const {
      cropBox,
      mediaBox
    } = this;
    if (cropBox !== mediaBox && !(0, _util.isArrayEqual)(cropBox, mediaBox)) {
      const box = _util.Util.intersect(cropBox, mediaBox);
      if (box && box[2] - box[0] > 0 && box[3] - box[1] > 0) {
        return (0, _util.shadow)(this, "view", box);
      }
      (0, _util.warn)("Empty /CropBox and /MediaBox intersection.");
    }
    return (0, _util.shadow)(this, "view", mediaBox);
  }
  get rotate() {
    let rotate = this._getInheritableProperty("Rotate") || 0;
    if (rotate % 90 !== 0) {
      rotate = 0;
    } else if (rotate >= 360) {
      rotate %= 360;
    } else if (rotate < 0) {
      rotate = (rotate % 360 + 360) % 360;
    }
    return (0, _util.shadow)(this, "rotate", rotate);
  }
  _onSubStreamError(handler, reason, objId) {
    if (this.evaluatorOptions.ignoreErrors) {
      handler.send("UnsupportedFeature", {
        featureId: _util.UNSUPPORTED_FEATURES.errorContentSubStream
      });
      (0, _util.warn)(`getContentStream - ignoring sub-stream (${objId}): "${reason}".`);
      return;
    }
    throw reason;
  }
  getContentStream(handler) {
    return this.pdfManager.ensure(this, "content").then(content => {
      if (content instanceof _base_stream.BaseStream) {
        return content;
      }
      if (Array.isArray(content)) {
        return new _decode_stream.StreamsSequenceStream(content, this._onSubStreamError.bind(this, handler));
      }
      return new _stream.NullStream();
    });
  }
  get xfaData() {
    return (0, _util.shadow)(this, "xfaData", this.xfaFactory ? {
      bbox: this.xfaFactory.getBoundingBox(this.pageIndex)
    } : null);
  }
  async saveNewAnnotations(handler, task, annotations) {
    if (this.xfaFactory) {
      throw new Error("XFA: Cannot save new annotations.");
    }
    const partialEvaluator = new _evaluator.PartialEvaluator({
      xref: this.xref,
      handler,
      pageIndex: this.pageIndex,
      idFactory: this._localIdFactory,
      fontCache: this.fontCache,
      builtInCMapCache: this.builtInCMapCache,
      standardFontDataCache: this.standardFontDataCache,
      globalImageCache: this.globalImageCache,
      options: this.evaluatorOptions
    });
    const pageDict = this.pageDict;
    const annotationsArray = this.annotations.slice();
    const newData = await _annotation.AnnotationFactory.saveNewAnnotations(partialEvaluator, task, annotations);
    for (const {
      ref
    } of newData.annotations) {
      annotationsArray.push(ref);
    }
    const savedDict = pageDict.get("Annots");
    pageDict.set("Annots", annotationsArray);
    const buffer = [];
    let transform = null;
    if (this.xref.encrypt) {
      transform = this.xref.encrypt.createCipherTransform(this.ref.num, this.ref.gen);
    }
    (0, _writer.writeObject)(this.ref, pageDict, buffer, transform);
    if (savedDict) {
      pageDict.set("Annots", savedDict);
    }
    const objects = newData.dependencies;
    objects.push({
      ref: this.ref,
      data: buffer.join("")
    }, ...newData.annotations);
    return objects;
  }
  save(handler, task, annotationStorage) {
    const partialEvaluator = new _evaluator.PartialEvaluator({
      xref: this.xref,
      handler,
      pageIndex: this.pageIndex,
      idFactory: this._localIdFactory,
      fontCache: this.fontCache,
      builtInCMapCache: this.builtInCMapCache,
      standardFontDataCache: this.standardFontDataCache,
      globalImageCache: this.globalImageCache,
      options: this.evaluatorOptions
    });
    return this._parsedAnnotations.then(function (annotations) {
      const newRefsPromises = [];
      for (const annotation of annotations) {
        if (!annotation.mustBePrinted(annotationStorage)) {
          continue;
        }
        newRefsPromises.push(annotation.save(partialEvaluator, task, annotationStorage).catch(function (reason) {
          (0, _util.warn)("save - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
          return null;
        }));
      }
      return Promise.all(newRefsPromises).then(function (newRefs) {
        return newRefs.filter(newRef => !!newRef);
      });
    });
  }
  loadResources(keys) {
    if (!this.resourcesPromise) {
      this.resourcesPromise = this.pdfManager.ensure(this, "resources");
    }
    return this.resourcesPromise.then(() => {
      const objectLoader = new _object_loader.ObjectLoader(this.resources, keys, this.xref);
      return objectLoader.load();
    });
  }
  getOperatorList({
    handler,
    sink,
    task,
    intent,
    cacheKey,
    annotationStorage = null
  }) {
    const contentStreamPromise = this.getContentStream(handler);
    const resourcesPromise = this.loadResources(["ColorSpace", "ExtGState", "Font", "Pattern", "Properties", "Shading", "XObject"]);
    const partialEvaluator = new _evaluator.PartialEvaluator({
      xref: this.xref,
      handler,
      pageIndex: this.pageIndex,
      idFactory: this._localIdFactory,
      fontCache: this.fontCache,
      builtInCMapCache: this.builtInCMapCache,
      standardFontDataCache: this.standardFontDataCache,
      globalImageCache: this.globalImageCache,
      options: this.evaluatorOptions
    });
    const newAnnotationsByPage = !this.xfaFactory ? (0, _core_utils.getNewAnnotationsMap)(annotationStorage) : null;
    let newAnnotationsPromise = Promise.resolve(null);
    if (newAnnotationsByPage) {
      const newAnnotations = newAnnotationsByPage.get(this.pageIndex);
      if (newAnnotations) {
        newAnnotationsPromise = _annotation.AnnotationFactory.printNewAnnotations(partialEvaluator, task, newAnnotations);
      }
    }
    const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
    const pageListPromise = dataPromises.then(([contentStream]) => {
      const opList = new _operator_list.OperatorList(intent, sink);
      handler.send("StartRenderPage", {
        transparency: partialEvaluator.hasBlendModes(this.resources, this.nonBlendModesSet),
        pageIndex: this.pageIndex,
        cacheKey
      });
      return partialEvaluator.getOperatorList({
        stream: contentStream,
        task,
        resources: this.resources,
        operatorList: opList
      }).then(function () {
        return opList;
      });
    });
    return Promise.all([pageListPromise, this._parsedAnnotations, newAnnotationsPromise]).then(function ([pageOpList, annotations, newAnnotations]) {
      if (newAnnotations) {
        annotations = annotations.concat(newAnnotations);
      }
      if (annotations.length === 0 || intent & _util.RenderingIntentFlag.ANNOTATIONS_DISABLE) {
        pageOpList.flush(true);
        return {
          length: pageOpList.totalLength
        };
      }
      const renderForms = !!(intent & _util.RenderingIntentFlag.ANNOTATIONS_FORMS),
        intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
        intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
        intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
      const opListPromises = [];
      for (const annotation of annotations) {
        if (intentAny || intentDisplay && annotation.mustBeViewed(annotationStorage) || intentPrint && annotation.mustBePrinted(annotationStorage)) {
          opListPromises.push(annotation.getOperatorList(partialEvaluator, task, intent, renderForms, annotationStorage).catch(function (reason) {
            (0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
            return {
              opList: null,
              separateForm: false,
              separateCanvas: false
            };
          }));
        }
      }
      return Promise.all(opListPromises).then(function (opLists) {
        let form = false,
          canvas = false;
        for (const {
          opList,
          separateForm,
          separateCanvas
        } of opLists) {
          pageOpList.addOpList(opList);
          if (separateForm) {
            form = separateForm;
          }
          if (separateCanvas) {
            canvas = separateCanvas;
          }
        }
        pageOpList.flush(true, {
          form,
          canvas
        });
        return {
          length: pageOpList.totalLength
        };
      });
    });
  }
  extractTextContent({
    handler,
    task,
    includeMarkedContent,
    sink,
    combineTextItems
  }) {
    const contentStreamPromise = this.getContentStream(handler);
    const resourcesPromise = this.loadResources(["ExtGState", "Font", "Properties", "XObject"]);
    const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
    return dataPromises.then(([contentStream]) => {
      const partialEvaluator = new _evaluator.PartialEvaluator({
        xref: this.xref,
        handler,
        pageIndex: this.pageIndex,
        idFactory: this._localIdFactory,
        fontCache: this.fontCache,
        builtInCMapCache: this.builtInCMapCache,
        standardFontDataCache: this.standardFontDataCache,
        globalImageCache: this.globalImageCache,
        options: this.evaluatorOptions
      });
      return partialEvaluator.getTextContent({
        stream: contentStream,
        task,
        resources: this.resources,
        includeMarkedContent,
        combineTextItems,
        sink,
        viewBox: this.view
      });
    });
  }
  async getStructTree() {
    const structTreeRoot = await this.pdfManager.ensureCatalog("structTreeRoot");
    if (!structTreeRoot) {
      return null;
    }
    const structTree = await this.pdfManager.ensure(this, "_parseStructTree", [structTreeRoot]);
    return structTree.serializable;
  }
  _parseStructTree(structTreeRoot) {
    const tree = new _struct_tree.StructTreePage(structTreeRoot, this.pageDict);
    tree.parse();
    return tree;
  }
  async getAnnotationsData(handler, task, intent) {
    const annotations = await this._parsedAnnotations;
    if (annotations.length === 0) {
      return [];
    }
    const textContentPromises = [];
    const annotationsData = [];
    let partialEvaluator;
    const intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
      intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
      intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
    for (const annotation of annotations) {
      const isVisible = intentAny || intentDisplay && annotation.viewable;
      if (isVisible || intentPrint && annotation.printable) {
        annotationsData.push(annotation.data);
      }
      if (annotation.hasTextContent && isVisible) {
        if (!partialEvaluator) {
          partialEvaluator = new _evaluator.PartialEvaluator({
            xref: this.xref,
            handler,
            pageIndex: this.pageIndex,
            idFactory: this._localIdFactory,
            fontCache: this.fontCache,
            builtInCMapCache: this.builtInCMapCache,
            standardFontDataCache: this.standardFontDataCache,
            globalImageCache: this.globalImageCache,
            options: this.evaluatorOptions
          });
        }
        textContentPromises.push(annotation.extractTextContent(partialEvaluator, task, this.view).catch(function (reason) {
          (0, _util.warn)(`getAnnotationsData - ignoring textContent during "${task.name}" task: "${reason}".`);
        }));
      }
    }
    await Promise.all(textContentPromises);
    return annotationsData;
  }
  get annotations() {
    const annots = this._getInheritableProperty("Annots");
    return (0, _util.shadow)(this, "annotations", Array.isArray(annots) ? annots : []);
  }
  get _parsedAnnotations() {
    const parsedAnnotations = this.pdfManager.ensure(this, "annotations").then(() => {
      const annotationPromises = [];
      for (const annotationRef of this.annotations) {
        annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory, false).catch(function (reason) {
          (0, _util.warn)(`_parsedAnnotations: "${reason}".`);
          return null;
        }));
      }
      return Promise.all(annotationPromises).then(function (annotations) {
        if (annotations.length === 0) {
          return annotations;
        }
        const sortedAnnotations = [];
        let popupAnnotations;
        for (const annotation of annotations) {
          if (!annotation) {
            continue;
          }
          if (annotation instanceof _annotation.PopupAnnotation) {
            if (!popupAnnotations) {
              popupAnnotations = [];
            }
            popupAnnotations.push(annotation);
            continue;
          }
          sortedAnnotations.push(annotation);
        }
        if (popupAnnotations) {
          sortedAnnotations.push(...popupAnnotations);
        }
        return sortedAnnotations;
      });
    });
    return (0, _util.shadow)(this, "_parsedAnnotations", parsedAnnotations);
  }
  get jsActions() {
    const actions = (0, _core_utils.collectActions)(this.xref, this.pageDict, _util.PageActionEventType);
    return (0, _util.shadow)(this, "jsActions", actions);
  }
}
exports.Page = Page;
const PDF_HEADER_SIGNATURE = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
const STARTXREF_SIGNATURE = new Uint8Array([0x73, 0x74, 0x61, 0x72, 0x74, 0x78, 0x72, 0x65, 0x66]);
const ENDOBJ_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x6f, 0x62, 0x6a]);
const FINGERPRINT_FIRST_BYTES = 1024;
const EMPTY_FINGERPRINT = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
function find(stream, signature, limit = 1024, backwards = false) {
  const signatureLength = signature.length;
  const scanBytes = stream.peekBytes(limit);
  const scanLength = scanBytes.length - signatureLength;
  if (scanLength <= 0) {
    return false;
  }
  if (backwards) {
    const signatureEnd = signatureLength - 1;
    let pos = scanBytes.length - 1;
    while (pos >= signatureEnd) {
      let j = 0;
      while (j < signatureLength && scanBytes[pos - j] === signature[signatureEnd - j]) {
        j++;
      }
      if (j >= signatureLength) {
        stream.pos += pos - signatureEnd;
        return true;
      }
      pos--;
    }
  } else {
    let pos = 0;
    while (pos <= scanLength) {
      let j = 0;
      while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
        j++;
      }
      if (j >= signatureLength) {
        stream.pos += pos;
        return true;
      }
      pos++;
    }
  }
  return false;
}
class PDFDocument {
  constructor(pdfManager, stream) {
    if (stream.length <= 0) {
      throw new _util.InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");
    }
    this.pdfManager = pdfManager;
    this.stream = stream;
    this.xref = new _xref.XRef(stream, pdfManager);
    this._pagePromises = new Map();
    this._version = null;
    const idCounters = {
      font: 0
    };
    this._globalIdFactory = class {
      static getDocId() {
        return `g_${pdfManager.docId}`;
      }
      static createFontId() {
        return `f${++idCounters.font}`;
      }
      static createObjId() {
        (0, _util.unreachable)("Abstract method `createObjId` called.");
      }
      static getPageObjId() {
        (0, _util.unreachable)("Abstract method `getPageObjId` called.");
      }
    };
  }
  parse(recoveryMode) {
    this.xref.parse(recoveryMode);
    this.catalog = new _catalog.Catalog(this.pdfManager, this.xref);
  }
  get linearization() {
    let linearization = null;
    try {
      linearization = _parser.Linearization.create(this.stream);
    } catch (err) {
      if (err instanceof _core_utils.MissingDataException) {
        throw err;
      }
      (0, _util.info)(err);
    }
    return (0, _util.shadow)(this, "linearization", linearization);
  }
  get startXRef() {
    const stream = this.stream;
    let startXRef = 0;
    if (this.linearization) {
      stream.reset();
      if (find(stream, ENDOBJ_SIGNATURE)) {
        startXRef = stream.pos + 6 - stream.start;
      }
    } else {
      const step = 1024;
      const startXRefLength = STARTXREF_SIGNATURE.length;
      let found = false,
        pos = stream.end;
      while (!found && pos > 0) {
        pos -= step - startXRefLength;
        if (pos < 0) {
          pos = 0;
        }
        stream.pos = pos;
        found = find(stream, STARTXREF_SIGNATURE, step, true);
      }
      if (found) {
        stream.skip(9);
        let ch;
        do {
          ch = stream.getByte();
        } while ((0, _core_utils.isWhiteSpace)(ch));
        let str = "";
        while (ch >= 0x20 && ch <= 0x39) {
          str += String.fromCharCode(ch);
          ch = stream.getByte();
        }
        startXRef = parseInt(str, 10);
        if (isNaN(startXRef)) {
          startXRef = 0;
        }
      }
    }
    return (0, _util.shadow)(this, "startXRef", startXRef);
  }
  checkHeader() {
    const stream = this.stream;
    stream.reset();
    if (!find(stream, PDF_HEADER_SIGNATURE)) {
      return;
    }
    stream.moveStart();
    stream.skip(PDF_HEADER_SIGNATURE.length);
    let version = "",
      ch;
    while ((ch = stream.getByte()) > 0x20 && version.length < 7) {
      version += String.fromCharCode(ch);
    }
    if (_core_utils.PDF_VERSION_REGEXP.test(version)) {
      this._version = version;
    } else {
      (0, _util.warn)(`Invalid PDF header version: ${version}`);
    }
  }
  parseStartXRef() {
    this.xref.setStartXRef(this.startXRef);
  }
  get numPages() {
    let num = 0;
    if (this.catalog.hasActualNumPages) {
      num = this.catalog.numPages;
    } else if (this.xfaFactory) {
      num = this.xfaFactory.getNumPages();
    } else if (this.linearization) {
      num = this.linearization.numPages;
    } else {
      num = this.catalog.numPages;
    }
    return (0, _util.shadow)(this, "numPages", num);
  }
  _hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
    const RECURSION_LIMIT = 10;
    if (!Array.isArray(fields)) {
      return false;
    }
    return fields.every(field => {
      field = this.xref.fetchIfRef(field);
      if (!(field instanceof _primitives.Dict)) {
        return false;
      }
      if (field.has("Kids")) {
        if (++recursionDepth > RECURSION_LIMIT) {
          (0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
          return false;
        }
        return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
      }
      const isSignature = (0, _primitives.isName)(field.get("FT"), "Sig");
      const rectangle = field.get("Rect");
      const isInvisible = Array.isArray(rectangle) && rectangle.every(value => value === 0);
      return isSignature && isInvisible;
    });
  }
  get _xfaStreams() {
    const acroForm = this.catalog.acroForm;
    if (!acroForm) {
      return null;
    }
    const xfa = acroForm.get("XFA");
    const entries = {
      "xdp:xdp": "",
      template: "",
      datasets: "",
      config: "",
      connectionSet: "",
      localeSet: "",
      stylesheet: "",
      "/xdp:xdp": ""
    };
    if (xfa instanceof _base_stream.BaseStream && !xfa.isEmpty) {
      entries["xdp:xdp"] = xfa;
      return entries;
    }
    if (!Array.isArray(xfa) || xfa.length === 0) {
      return null;
    }
    for (let i = 0, ii = xfa.length; i < ii; i += 2) {
      let name;
      if (i === 0) {
        name = "xdp:xdp";
      } else if (i === ii - 2) {
        name = "/xdp:xdp";
      } else {
        name = xfa[i];
      }
      if (!entries.hasOwnProperty(name)) {
        continue;
      }
      const data = this.xref.fetchIfRef(xfa[i + 1]);
      if (!(data instanceof _base_stream.BaseStream) || data.isEmpty) {
        continue;
      }
      entries[name] = data;
    }
    return entries;
  }
  get xfaDatasets() {
    const streams = this._xfaStreams;
    if (!streams) {
      return (0, _util.shadow)(this, "xfaDatasets", null);
    }
    for (const key of ["datasets", "xdp:xdp"]) {
      const stream = streams[key];
      if (!stream) {
        continue;
      }
      try {
        const str = (0, _util.stringToUTF8String)(stream.getString());
        const data = {
          [key]: str
        };
        return (0, _util.shadow)(this, "xfaDatasets", new _dataset_reader.DatasetReader(data));
      } catch (_) {
        (0, _util.warn)("XFA - Invalid utf-8 string.");
        break;
      }
    }
    return (0, _util.shadow)(this, "xfaDatasets", null);
  }
  get xfaData() {
    const streams = this._xfaStreams;
    if (!streams) {
      return null;
    }
    const data = Object.create(null);
    for (const [key, stream] of Object.entries(streams)) {
      if (!stream) {
        continue;
      }
      try {
        data[key] = (0, _util.stringToUTF8String)(stream.getString());
      } catch (_) {
        (0, _util.warn)("XFA - Invalid utf-8 string.");
        return null;
      }
    }
    return data;
  }
  get xfaFactory() {
    let data;
    if (this.pdfManager.enableXfa && this.catalog.needsRendering && this.formInfo.hasXfa && !this.formInfo.hasAcroForm) {
      data = this.xfaData;
    }
    return (0, _util.shadow)(this, "xfaFactory", data ? new _factory.XFAFactory(data) : null);
  }
  get isPureXfa() {
    return this.xfaFactory ? this.xfaFactory.isValid() : false;
  }
  get htmlForXfa() {
    return this.xfaFactory ? this.xfaFactory.getPages() : null;
  }
  async loadXfaImages() {
    const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
    if (!xfaImagesDict) {
      return;
    }
    const keys = xfaImagesDict.getKeys();
    const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
    await objectLoader.load();
    const xfaImages = new Map();
    for (const key of keys) {
      const stream = xfaImagesDict.get(key);
      if (stream instanceof _base_stream.BaseStream) {
        xfaImages.set(key, stream.getBytes());
      }
    }
    this.xfaFactory.setImages(xfaImages);
  }
  async loadXfaFonts(handler, task) {
    const acroForm = await this.pdfManager.ensureCatalog("acroForm");
    if (!acroForm) {
      return;
    }
    const resources = await acroForm.getAsync("DR");
    if (!(resources instanceof _primitives.Dict)) {
      return;
    }
    const objectLoader = new _object_loader.ObjectLoader(resources, ["Font"], this.xref);
    await objectLoader.load();
    const fontRes = resources.get("Font");
    if (!(fontRes instanceof _primitives.Dict)) {
      return;
    }
    const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
    options.useSystemFonts = false;
    const partialEvaluator = new _evaluator.PartialEvaluator({
      xref: this.xref,
      handler,
      pageIndex: -1,
      idFactory: this._globalIdFactory,
      fontCache: this.catalog.fontCache,
      builtInCMapCache: this.catalog.builtInCMapCache,
      standardFontDataCache: this.catalog.standardFontDataCache,
      options
    });
    const operatorList = new _operator_list.OperatorList();
    const pdfFonts = [];
    const initialState = {
      get font() {
        return pdfFonts.at(-1);
      },
      set font(font) {
        pdfFonts.push(font);
      },
      clone() {
        return this;
      }
    };
    const fonts = new Map();
    fontRes.forEach((fontName, font) => {
      fonts.set(fontName, font);
    });
    const promises = [];
    for (const [fontName, font] of fonts) {
      const descriptor = font.get("FontDescriptor");
      if (!(descriptor instanceof _primitives.Dict)) {
        continue;
      }
      let fontFamily = descriptor.get("FontFamily");
      fontFamily = fontFamily.replace(/[ ]+(\d)/g, "$1");
      const fontWeight = descriptor.get("FontWeight");
      const italicAngle = -descriptor.get("ItalicAngle");
      const cssFontInfo = {
        fontFamily,
        fontWeight,
        italicAngle
      };
      if (!(0, _core_utils.validateCSSFont)(cssFontInfo)) {
        continue;
      }
      promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(fontName), 1], null, operatorList, task, initialState, null, cssFontInfo).catch(function (reason) {
        (0, _util.warn)(`loadXfaFonts: "${reason}".`);
        return null;
      }));
    }
    await Promise.all(promises);
    const missingFonts = this.xfaFactory.setFonts(pdfFonts);
    if (!missingFonts) {
      return;
    }
    options.ignoreErrors = true;
    promises.length = 0;
    pdfFonts.length = 0;
    const reallyMissingFonts = new Set();
    for (const missing of missingFonts) {
      if (!(0, _xfa_fonts.getXfaFontName)(`${missing}-Regular`)) {
        reallyMissingFonts.add(missing);
      }
    }
    if (reallyMissingFonts.size) {
      missingFonts.push("PdfJS-Fallback");
    }
    for (const missing of missingFonts) {
      if (reallyMissingFonts.has(missing)) {
        continue;
      }
      for (const fontInfo of [{
        name: "Regular",
        fontWeight: 400,
        italicAngle: 0
      }, {
        name: "Bold",
        fontWeight: 700,
        italicAngle: 0
      }, {
        name: "Italic",
        fontWeight: 400,
        italicAngle: 12
      }, {
        name: "BoldItalic",
        fontWeight: 700,
        italicAngle: 12
      }]) {
        const name = `${missing}-${fontInfo.name}`;
        const dict = (0, _xfa_fonts.getXfaFontDict)(name);
        promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
          fontFamily: missing,
          fontWeight: fontInfo.fontWeight,
          italicAngle: fontInfo.italicAngle
        }).catch(function (reason) {
          (0, _util.warn)(`loadXfaFonts: "${reason}".`);
          return null;
        }));
      }
    }
    await Promise.all(promises);
    this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
  }
  async serializeXfaData(annotationStorage) {
    return this.xfaFactory ? this.xfaFactory.serializeData(annotationStorage) : null;
  }
  get version() {
    return this.catalog.version || this._version;
  }
  get formInfo() {
    const formInfo = {
      hasFields: false,
      hasAcroForm: false,
      hasXfa: false,
      hasSignatures: false
    };
    const acroForm = this.catalog.acroForm;
    if (!acroForm) {
      return (0, _util.shadow)(this, "formInfo", formInfo);
    }
    try {
      const fields = acroForm.get("Fields");
      const hasFields = Array.isArray(fields) && fields.length > 0;
      formInfo.hasFields = hasFields;
      const xfa = acroForm.get("XFA");
      formInfo.hasXfa = Array.isArray(xfa) && xfa.length > 0 || xfa instanceof _base_stream.BaseStream && !xfa.isEmpty;
      const sigFlags = acroForm.get("SigFlags");
      const hasSignatures = !!(sigFlags & 0x1);
      const hasOnlyDocumentSignatures = hasSignatures && this._hasOnlyDocumentSignatures(fields);
      formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
      formInfo.hasSignatures = hasSignatures;
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`Cannot fetch form information: "${ex}".`);
    }
    return (0, _util.shadow)(this, "formInfo", formInfo);
  }
  get documentInfo() {
    const docInfo = {
      PDFFormatVersion: this.version,
      Language: this.catalog.lang,
      EncryptFilterName: this.xref.encrypt ? this.xref.encrypt.filterName : null,
      IsLinearized: !!this.linearization,
      IsAcroFormPresent: this.formInfo.hasAcroForm,
      IsXFAPresent: this.formInfo.hasXfa,
      IsCollectionPresent: !!this.catalog.collection,
      IsSignaturesPresent: this.formInfo.hasSignatures
    };
    let infoDict;
    try {
      infoDict = this.xref.trailer.get("Info");
    } catch (err) {
      if (err instanceof _core_utils.MissingDataException) {
        throw err;
      }
      (0, _util.info)("The document information dictionary is invalid.");
    }
    if (!(infoDict instanceof _primitives.Dict)) {
      return (0, _util.shadow)(this, "documentInfo", docInfo);
    }
    for (const key of infoDict.getKeys()) {
      const value = infoDict.get(key);
      switch (key) {
        case "Title":
        case "Author":
        case "Subject":
        case "Keywords":
        case "Creator":
        case "Producer":
        case "CreationDate":
        case "ModDate":
          if (typeof value === "string") {
            docInfo[key] = (0, _util.stringToPDFString)(value);
            continue;
          }
          break;
        case "Trapped":
          if (value instanceof _primitives.Name) {
            docInfo[key] = value;
            continue;
          }
          break;
        default:
          let customValue;
          switch (typeof value) {
            case "string":
              customValue = (0, _util.stringToPDFString)(value);
              break;
            case "number":
            case "boolean":
              customValue = value;
              break;
            default:
              if (value instanceof _primitives.Name) {
                customValue = value;
              }
              break;
          }
          if (customValue === undefined) {
            (0, _util.warn)(`Bad value, for custom key "${key}", in Info: ${value}.`);
            continue;
          }
          if (!docInfo.Custom) {
            docInfo.Custom = Object.create(null);
          }
          docInfo.Custom[key] = customValue;
          continue;
      }
      (0, _util.warn)(`Bad value, for key "${key}", in Info: ${value}.`);
    }
    return (0, _util.shadow)(this, "documentInfo", docInfo);
  }
  get fingerprints() {
    function validate(data) {
      return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
    }
    function hexString(hash) {
      const buf = [];
      for (const num of hash) {
        const hex = num.toString(16);
        buf.push(hex.padStart(2, "0"));
      }
      return buf.join("");
    }
    const idArray = this.xref.trailer.get("ID");
    let hashOriginal, hashModified;
    if (Array.isArray(idArray) && validate(idArray[0])) {
      hashOriginal = (0, _util.stringToBytes)(idArray[0]);
      if (idArray[1] !== idArray[0] && validate(idArray[1])) {
        hashModified = (0, _util.stringToBytes)(idArray[1]);
      }
    } else {
      hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
    }
    return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
  }
  async _getLinearizationPage(pageIndex) {
    const {
      catalog,
      linearization,
      xref
    } = this;
    const ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
    try {
      const obj = await xref.fetchAsync(ref);
      if (obj instanceof _primitives.Dict) {
        let type = obj.getRaw("Type");
        if (type instanceof _primitives.Ref) {
          type = await xref.fetchAsync(type);
        }
        if ((0, _primitives.isName)(type, "Page") || !obj.has("Type") && !obj.has("Kids")) {
          if (!catalog.pageKidsCountCache.has(ref)) {
            catalog.pageKidsCountCache.put(ref, 1);
          }
          if (!catalog.pageIndexCache.has(ref)) {
            catalog.pageIndexCache.put(ref, 0);
          }
          return [obj, ref];
        }
      }
      throw new _util.FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.");
    } catch (reason) {
      (0, _util.warn)(`_getLinearizationPage: "${reason.message}".`);
      return catalog.getPageDict(pageIndex);
    }
  }
  getPage(pageIndex) {
    const cachedPromise = this._pagePromises.get(pageIndex);
    if (cachedPromise) {
      return cachedPromise;
    }
    const {
      catalog,
      linearization,
      xfaFactory
    } = this;
    let promise;
    if (xfaFactory) {
      promise = Promise.resolve([_primitives.Dict.empty, null]);
    } else if (linearization && linearization.pageFirst === pageIndex) {
      promise = this._getLinearizationPage(pageIndex);
    } else {
      promise = catalog.getPageDict(pageIndex);
    }
    promise = promise.then(([pageDict, ref]) => {
      return new Page({
        pdfManager: this.pdfManager,
        xref: this.xref,
        pageIndex,
        pageDict,
        ref,
        globalIdFactory: this._globalIdFactory,
        fontCache: catalog.fontCache,
        builtInCMapCache: catalog.builtInCMapCache,
        standardFontDataCache: catalog.standardFontDataCache,
        globalImageCache: catalog.globalImageCache,
        nonBlendModesSet: catalog.nonBlendModesSet,
        xfaFactory
      });
    });
    this._pagePromises.set(pageIndex, promise);
    return promise;
  }
  async checkFirstPage(recoveryMode = false) {
    if (recoveryMode) {
      return;
    }
    try {
      await this.getPage(0);
    } catch (reason) {
      if (reason instanceof _core_utils.XRefEntryException) {
        this._pagePromises.delete(0);
        await this.cleanup();
        throw new _core_utils.XRefParseException();
      }
    }
  }
  async checkLastPage(recoveryMode = false) {
    const {
      catalog,
      pdfManager
    } = this;
    catalog.setActualNumPages();
    let numPages;
    try {
      await Promise.all([pdfManager.ensureDoc("xfaFactory"), pdfManager.ensureDoc("linearization"), pdfManager.ensureCatalog("numPages")]);
      if (this.xfaFactory) {
        return;
      } else if (this.linearization) {
        numPages = this.linearization.numPages;
      } else {
        numPages = catalog.numPages;
      }
      if (!Number.isInteger(numPages)) {
        throw new _util.FormatError("Page count is not an integer.");
      } else if (numPages <= 1) {
        return;
      }
      await this.getPage(numPages - 1);
    } catch (reason) {
      this._pagePromises.delete(numPages - 1);
      await this.cleanup();
      if (reason instanceof _core_utils.XRefEntryException && !recoveryMode) {
        throw new _core_utils.XRefParseException();
      }
      (0, _util.warn)(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);
      let pagesTree;
      try {
        pagesTree = await catalog.getAllPageDicts(recoveryMode);
      } catch (reasonAll) {
        if (reasonAll instanceof _core_utils.XRefEntryException && !recoveryMode) {
          throw new _core_utils.XRefParseException();
        }
        catalog.setActualNumPages(1);
        return;
      }
      for (const [pageIndex, [pageDict, ref]] of pagesTree) {
        let promise;
        if (pageDict instanceof Error) {
          promise = Promise.reject(pageDict);
          promise.catch(() => {});
        } else {
          promise = Promise.resolve(new Page({
            pdfManager,
            xref: this.xref,
            pageIndex,
            pageDict,
            ref,
            globalIdFactory: this._globalIdFactory,
            fontCache: catalog.fontCache,
            builtInCMapCache: catalog.builtInCMapCache,
            standardFontDataCache: catalog.standardFontDataCache,
            globalImageCache: catalog.globalImageCache,
            nonBlendModesSet: catalog.nonBlendModesSet,
            xfaFactory: null
          }));
        }
        this._pagePromises.set(pageIndex, promise);
      }
      catalog.setActualNumPages(pagesTree.size);
    }
  }
  fontFallback(id, handler) {
    return this.catalog.fontFallback(id, handler);
  }
  async cleanup(manuallyTriggered = false) {
    return this.catalog ? this.catalog.cleanup(manuallyTriggered) : (0, _cleanup_helper.clearGlobalCaches)();
  }
  _collectFieldObjects(name, fieldRef, promises) {
    const field = this.xref.fetchIfRef(fieldRef);
    if (field.has("T")) {
      const partName = (0, _util.stringToPDFString)(field.get("T"));
      if (name === "") {
        name = partName;
      } else {
        name = `${name}.${partName}`;
      }
    }
    if (!promises.has(name)) {
      promises.set(name, []);
    }
    promises.get(name).push(_annotation.AnnotationFactory.create(this.xref, fieldRef, this.pdfManager, this._localIdFactory, true).then(annotation => annotation && annotation.getFieldObject()).catch(function (reason) {
      (0, _util.warn)(`_collectFieldObjects: "${reason}".`);
      return null;
    }));
    if (field.has("Kids")) {
      const kids = field.get("Kids");
      for (const kid of kids) {
        this._collectFieldObjects(name, kid, promises);
      }
    }
  }
  get fieldObjects() {
    if (!this.formInfo.hasFields) {
      return (0, _util.shadow)(this, "fieldObjects", Promise.resolve(null));
    }
    const allFields = Object.create(null);
    const fieldPromises = new Map();
    for (const fieldRef of this.catalog.acroForm.get("Fields")) {
      this._collectFieldObjects("", fieldRef, fieldPromises);
    }
    const allPromises = [];
    for (const [name, promises] of fieldPromises) {
      allPromises.push(Promise.all(promises).then(fields => {
        fields = fields.filter(field => !!field);
        if (fields.length > 0) {
          allFields[name] = fields;
        }
      }));
    }
    return (0, _util.shadow)(this, "fieldObjects", Promise.all(allPromises).then(() => allFields));
  }
  get hasJSActions() {
    const promise = this.pdfManager.ensureDoc("_parseHasJSActions");
    return (0, _util.shadow)(this, "hasJSActions", promise);
  }
  async _parseHasJSActions() {
    const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]);
    if (catalogJsActions) {
      return true;
    }
    if (fieldObjects) {
      return Object.values(fieldObjects).some(fieldObject => fieldObject.some(object => object.actions !== null));
    }
    return false;
  }
  get calculationOrderIds() {
    const acroForm = this.catalog.acroForm;
    if (!acroForm || !acroForm.has("CO")) {
      return (0, _util.shadow)(this, "calculationOrderIds", null);
    }
    const calculationOrder = acroForm.get("CO");
    if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) {
      return (0, _util.shadow)(this, "calculationOrderIds", null);
    }
    const ids = [];
    for (const id of calculationOrder) {
      if (id instanceof _primitives.Ref) {
        ids.push(id.toString());
      }
    }
    if (ids.length === 0) {
      return (0, _util.shadow)(this, "calculationOrderIds", null);
    }
    return (0, _util.shadow)(this, "calculationOrderIds", ids);
  }
}
exports.PDFDocument = PDFDocument;

/***/ }),
/* 10 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PopupAnnotation = exports.MarkupAnnotation = exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = void 0;
exports.getQuadPoints = getQuadPoints;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _default_appearance = __w_pdfjs_require__(11);
var _primitives = __w_pdfjs_require__(3);
var _writer = __w_pdfjs_require__(63);
var _base_stream = __w_pdfjs_require__(5);
var _bidi = __w_pdfjs_require__(58);
var _catalog = __w_pdfjs_require__(67);
var _colorspace = __w_pdfjs_require__(12);
var _file_spec = __w_pdfjs_require__(70);
var _object_loader = __w_pdfjs_require__(73);
var _operator_list = __w_pdfjs_require__(60);
var _stream = __w_pdfjs_require__(8);
var _factory = __w_pdfjs_require__(74);
class AnnotationFactory {
  static create(xref, ref, pdfManager, idFactory, collectFields) {
    return Promise.all([pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("baseUrl"), pdfManager.ensureCatalog("attachments"), pdfManager.ensureDoc("xfaDatasets"), collectFields ? this._getPageIndex(xref, ref, pdfManager) : -1]).then(([acroForm, baseUrl, attachments, xfaDatasets, pageIndex]) => pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory, acroForm, attachments, xfaDatasets, collectFields, pageIndex]));
  }
  static _create(xref, ref, pdfManager, idFactory, acroForm, attachments = null, xfaDatasets, collectFields, pageIndex = -1) {
    const dict = xref.fetchIfRef(ref);
    if (!(dict instanceof _primitives.Dict)) {
      return undefined;
    }
    const id = ref instanceof _primitives.Ref ? ref.toString() : `annot_${idFactory.createObjId()}`;
    let subtype = dict.get("Subtype");
    subtype = subtype instanceof _primitives.Name ? subtype.name : null;
    const acroFormDict = acroForm instanceof _primitives.Dict ? acroForm : _primitives.Dict.empty;
    const parameters = {
      xref,
      ref,
      dict,
      subtype,
      id,
      pdfManager,
      acroForm: acroFormDict,
      attachments,
      xfaDatasets,
      collectFields,
      needAppearances: !collectFields && acroFormDict.get("NeedAppearances") === true,
      pageIndex,
      isOffscreenCanvasSupported: _util.FeatureTest.isOffscreenCanvasSupported && pdfManager.evaluatorOptions.isOffscreenCanvasSupported
    };
    switch (subtype) {
      case "Link":
        return new LinkAnnotation(parameters);
      case "Text":
        return new TextAnnotation(parameters);
      case "Widget":
        let fieldType = (0, _core_utils.getInheritableProperty)({
          dict,
          key: "FT"
        });
        fieldType = fieldType instanceof _primitives.Name ? fieldType.name : null;
        switch (fieldType) {
          case "Tx":
            return new TextWidgetAnnotation(parameters);
          case "Btn":
            return new ButtonWidgetAnnotation(parameters);
          case "Ch":
            return new ChoiceWidgetAnnotation(parameters);
          case "Sig":
            return new SignatureWidgetAnnotation(parameters);
        }
        (0, _util.warn)(`Unimplemented widget field type "${fieldType}", ` + "falling back to base field type.");
        return new WidgetAnnotation(parameters);
      case "Popup":
        return new PopupAnnotation(parameters);
      case "FreeText":
        return new FreeTextAnnotation(parameters);
      case "Line":
        return new LineAnnotation(parameters);
      case "Square":
        return new SquareAnnotation(parameters);
      case "Circle":
        return new CircleAnnotation(parameters);
      case "PolyLine":
        return new PolylineAnnotation(parameters);
      case "Polygon":
        return new PolygonAnnotation(parameters);
      case "Caret":
        return new CaretAnnotation(parameters);
      case "Ink":
        return new InkAnnotation(parameters);
      case "Highlight":
        return new HighlightAnnotation(parameters);
      case "Underline":
        return new UnderlineAnnotation(parameters);
      case "Squiggly":
        return new SquigglyAnnotation(parameters);
      case "StrikeOut":
        return new StrikeOutAnnotation(parameters);
      case "Stamp":
        return new StampAnnotation(parameters);
      case "FileAttachment":
        return new FileAttachmentAnnotation(parameters);
      default:
        if (!collectFields) {
          if (!subtype) {
            (0, _util.warn)("Annotation is missing the required /Subtype.");
          } else {
            (0, _util.warn)(`Unimplemented annotation type "${subtype}", ` + "falling back to base annotation.");
          }
        }
        return new Annotation(parameters);
    }
  }
  static async _getPageIndex(xref, ref, pdfManager) {
    try {
      const annotDict = await xref.fetchIfRefAsync(ref);
      if (!(annotDict instanceof _primitives.Dict)) {
        return -1;
      }
      const pageRef = annotDict.getRaw("P");
      if (!(pageRef instanceof _primitives.Ref)) {
        return -1;
      }
      const pageIndex = await pdfManager.ensureCatalog("getPageIndex", [pageRef]);
      return pageIndex;
    } catch (ex) {
      (0, _util.warn)(`_getPageIndex: "${ex}".`);
      return -1;
    }
  }
  static async saveNewAnnotations(evaluator, task, annotations) {
    const xref = evaluator.xref;
    let baseFontRef;
    const dependencies = [];
    const promises = [];
    for (const annotation of annotations) {
      switch (annotation.annotationType) {
        case _util.AnnotationEditorType.FREETEXT:
          if (!baseFontRef) {
            const baseFont = new _primitives.Dict(xref);
            baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
            baseFont.set("Type", _primitives.Name.get("Font"));
            baseFont.set("Subtype", _primitives.Name.get("Type1"));
            baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
            const buffer = [];
            baseFontRef = xref.getNewTemporaryRef();
            (0, _writer.writeObject)(baseFontRef, baseFont, buffer, null);
            dependencies.push({
              ref: baseFontRef,
              data: buffer.join("")
            });
          }
          promises.push(FreeTextAnnotation.createNewAnnotation(xref, annotation, dependencies, {
            evaluator,
            task,
            baseFontRef
          }));
          break;
        case _util.AnnotationEditorType.INK:
          promises.push(InkAnnotation.createNewAnnotation(xref, annotation, dependencies));
      }
    }
    return {
      annotations: await Promise.all(promises),
      dependencies
    };
  }
  static async printNewAnnotations(evaluator, task, annotations) {
    if (!annotations) {
      return null;
    }
    const xref = evaluator.xref;
    const promises = [];
    const isOffscreenCanvasSupported = _util.FeatureTest.isOffscreenCanvasSupported && evaluator.options.isOffscreenCanvasSupported;
    for (const annotation of annotations) {
      switch (annotation.annotationType) {
        case _util.AnnotationEditorType.FREETEXT:
          promises.push(FreeTextAnnotation.createNewPrintAnnotation(xref, annotation, {
            evaluator,
            task,
            isOffscreenCanvasSupported
          }));
          break;
        case _util.AnnotationEditorType.INK:
          promises.push(InkAnnotation.createNewPrintAnnotation(xref, annotation, {
            isOffscreenCanvasSupported
          }));
          break;
      }
    }
    return Promise.all(promises);
  }
}
exports.AnnotationFactory = AnnotationFactory;
function getRgbColor(color, defaultColor = new Uint8ClampedArray(3)) {
  if (!Array.isArray(color)) {
    return defaultColor;
  }
  const rgbColor = defaultColor || new Uint8ClampedArray(3);
  switch (color.length) {
    case 0:
      return null;
    case 1:
      _colorspace.ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
      return rgbColor;
    case 3:
      _colorspace.ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
      return rgbColor;
    case 4:
      _colorspace.ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
      return rgbColor;
    default:
      return defaultColor;
  }
}
function getPdfColorArray(color) {
  return Array.from(color, c => c / 255);
}
function getQuadPoints(dict, rect) {
  const quadPoints = dict.getArray("QuadPoints");
  if (!Array.isArray(quadPoints) || quadPoints.length === 0 || quadPoints.length % 8 > 0) {
    return null;
  }
  const quadPointsLists = [];
  for (let i = 0, ii = quadPoints.length / 8; i < ii; i++) {
    let minX = Infinity,
      maxX = -Infinity,
      minY = Infinity,
      maxY = -Infinity;
    for (let j = i * 8, jj = i * 8 + 8; j < jj; j += 2) {
      const x = quadPoints[j];
      const y = quadPoints[j + 1];
      minX = Math.min(x, minX);
      maxX = Math.max(x, maxX);
      minY = Math.min(y, minY);
      maxY = Math.max(y, maxY);
    }
    if (rect !== null && (minX < rect[0] || maxX > rect[2] || minY < rect[1] || maxY > rect[3])) {
      return null;
    }
    quadPointsLists.push([{
      x: minX,
      y: maxY
    }, {
      x: maxX,
      y: maxY
    }, {
      x: minX,
      y: minY
    }, {
      x: maxX,
      y: minY
    }]);
  }
  return quadPointsLists;
}
function getTransformMatrix(rect, bbox, matrix) {
  const [minX, minY, maxX, maxY] = _util.Util.getAxialAlignedBoundingBox(bbox, matrix);
  if (minX === maxX || minY === maxY) {
    return [1, 0, 0, 1, rect[0], rect[1]];
  }
  const xRatio = (rect[2] - rect[0]) / (maxX - minX);
  const yRatio = (rect[3] - rect[1]) / (maxY - minY);
  return [xRatio, 0, 0, yRatio, rect[0] - minX * xRatio, rect[1] - minY * yRatio];
}
class Annotation {
  constructor(params) {
    const {
      dict,
      xref
    } = params;
    this.setTitle(dict.get("T"));
    this.setContents(dict.get("Contents"));
    this.setModificationDate(dict.get("M"));
    this.setFlags(dict.get("F"));
    this.setRectangle(dict.getArray("Rect"));
    this.setColor(dict.getArray("C"));
    this.setBorderStyle(dict);
    this.setAppearance(dict);
    this.setOptionalContent(dict);
    const MK = dict.get("MK");
    this.setBorderAndBackgroundColors(MK);
    this.setRotation(MK);
    this._streams = [];
    if (this.appearance) {
      this._streams.push(this.appearance);
    }
    this.data = {
      annotationFlags: this.flags,
      borderStyle: this.borderStyle,
      color: this.color,
      backgroundColor: this.backgroundColor,
      borderColor: this.borderColor,
      rotation: this.rotation,
      contentsObj: this._contents,
      hasAppearance: !!this.appearance,
      id: params.id,
      modificationDate: this.modificationDate,
      rect: this.rectangle,
      subtype: params.subtype,
      hasOwnCanvas: false
    };
    if (params.collectFields) {
      const kids = dict.get("Kids");
      if (Array.isArray(kids)) {
        const kidIds = [];
        for (const kid of kids) {
          if (kid instanceof _primitives.Ref) {
            kidIds.push(kid.toString());
          }
        }
        if (kidIds.length !== 0) {
          this.data.kidIds = kidIds;
        }
      }
      this.data.actions = (0, _core_utils.collectActions)(xref, dict, _util.AnnotationActionEventType);
      this.data.fieldName = this._constructFieldName(dict);
      this.data.pageIndex = params.pageIndex;
    }
    this._isOffscreenCanvasSupported = params.isOffscreenCanvasSupported;
    this._fallbackFontDict = null;
    this._needAppearances = false;
  }
  _hasFlag(flags, flag) {
    return !!(flags & flag);
  }
  _isViewable(flags) {
    return !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.NOVIEW);
  }
  _isPrintable(flags) {
    return this._hasFlag(flags, _util.AnnotationFlag.PRINT) && !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE);
  }
  mustBeViewed(annotationStorage) {
    const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
    if (storageEntry && storageEntry.hidden !== undefined) {
      return !storageEntry.hidden;
    }
    return this.viewable && !this._hasFlag(this.flags, _util.AnnotationFlag.HIDDEN);
  }
  mustBePrinted(annotationStorage) {
    const storageEntry = annotationStorage && annotationStorage.get(this.data.id);
    if (storageEntry && storageEntry.print !== undefined) {
      return storageEntry.print;
    }
    return this.printable;
  }
  get viewable() {
    if (this.data.quadPoints === null) {
      return false;
    }
    if (this.flags === 0) {
      return true;
    }
    return this._isViewable(this.flags);
  }
  get printable() {
    if (this.data.quadPoints === null) {
      return false;
    }
    if (this.flags === 0) {
      return false;
    }
    return this._isPrintable(this.flags);
  }
  _parseStringHelper(data) {
    const str = typeof data === "string" ? (0, _util.stringToPDFString)(data) : "";
    const dir = str && (0, _bidi.bidi)(str).dir === "rtl" ? "rtl" : "ltr";
    return {
      str,
      dir
    };
  }
  setDefaultAppearance(params) {
    const defaultAppearance = (0, _core_utils.getInheritableProperty)({
      dict: params.dict,
      key: "DA"
    }) || params.acroForm.get("DA");
    this._defaultAppearance = typeof defaultAppearance === "string" ? defaultAppearance : "";
    this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance);
  }
  setTitle(title) {
    this._title = this._parseStringHelper(title);
  }
  setContents(contents) {
    this._contents = this._parseStringHelper(contents);
  }
  setModificationDate(modificationDate) {
    this.modificationDate = typeof modificationDate === "string" ? modificationDate : null;
  }
  setFlags(flags) {
    this.flags = Number.isInteger(flags) && flags > 0 ? flags : 0;
  }
  hasFlag(flag) {
    return this._hasFlag(this.flags, flag);
  }
  setRectangle(rectangle) {
    if (Array.isArray(rectangle) && rectangle.length === 4) {
      this.rectangle = _util.Util.normalizeRect(rectangle);
    } else {
      this.rectangle = [0, 0, 0, 0];
    }
  }
  setColor(color) {
    this.color = getRgbColor(color);
  }
  setLineEndings(lineEndings) {
    this.lineEndings = ["None", "None"];
    if (Array.isArray(lineEndings) && lineEndings.length === 2) {
      for (let i = 0; i < 2; i++) {
        const obj = lineEndings[i];
        if (obj instanceof _primitives.Name) {
          switch (obj.name) {
            case "None":
              continue;
            case "Square":
            case "Circle":
            case "Diamond":
            case "OpenArrow":
            case "ClosedArrow":
            case "Butt":
            case "ROpenArrow":
            case "RClosedArrow":
            case "Slash":
              this.lineEndings[i] = obj.name;
              continue;
          }
        }
        (0, _util.warn)(`Ignoring invalid lineEnding: ${obj}`);
      }
    }
  }
  setRotation(mk) {
    this.rotation = 0;
    if (mk instanceof _primitives.Dict) {
      let angle = mk.get("R") || 0;
      if (Number.isInteger(angle) && angle !== 0) {
        angle %= 360;
        if (angle < 0) {
          angle += 360;
        }
        if (angle % 90 === 0) {
          this.rotation = angle;
        }
      }
    }
  }
  setBorderAndBackgroundColors(mk) {
    if (mk instanceof _primitives.Dict) {
      this.borderColor = getRgbColor(mk.getArray("BC"), null);
      this.backgroundColor = getRgbColor(mk.getArray("BG"), null);
    } else {
      this.borderColor = this.backgroundColor = null;
    }
  }
  setBorderStyle(borderStyle) {
    this.borderStyle = new AnnotationBorderStyle();
    if (!(borderStyle instanceof _primitives.Dict)) {
      return;
    }
    if (borderStyle.has("BS")) {
      const dict = borderStyle.get("BS");
      const dictType = dict.get("Type");
      if (!dictType || (0, _primitives.isName)(dictType, "Border")) {
        this.borderStyle.setWidth(dict.get("W"), this.rectangle);
        this.borderStyle.setStyle(dict.get("S"));
        this.borderStyle.setDashArray(dict.getArray("D"));
      }
    } else if (borderStyle.has("Border")) {
      const array = borderStyle.getArray("Border");
      if (Array.isArray(array) && array.length >= 3) {
        this.borderStyle.setHorizontalCornerRadius(array[0]);
        this.borderStyle.setVerticalCornerRadius(array[1]);
        this.borderStyle.setWidth(array[2], this.rectangle);
        if (array.length === 4) {
          this.borderStyle.setDashArray(array[3], true);
        }
      }
    } else {
      this.borderStyle.setWidth(0);
    }
  }
  setAppearance(dict) {
    this.appearance = null;
    const appearanceStates = dict.get("AP");
    if (!(appearanceStates instanceof _primitives.Dict)) {
      return;
    }
    const normalAppearanceState = appearanceStates.get("N");
    if (normalAppearanceState instanceof _base_stream.BaseStream) {
      this.appearance = normalAppearanceState;
      return;
    }
    if (!(normalAppearanceState instanceof _primitives.Dict)) {
      return;
    }
    const as = dict.get("AS");
    if (!(as instanceof _primitives.Name) || !normalAppearanceState.has(as.name)) {
      return;
    }
    const appearance = normalAppearanceState.get(as.name);
    if (appearance instanceof _base_stream.BaseStream) {
      this.appearance = appearance;
    }
  }
  setOptionalContent(dict) {
    this.oc = null;
    const oc = dict.get("OC");
    if (oc instanceof _primitives.Name) {
      (0, _util.warn)("setOptionalContent: Support for /Name-entry is not implemented.");
    } else if (oc instanceof _primitives.Dict) {
      this.oc = oc;
    }
  }
  loadResources(keys, appearance) {
    return appearance.dict.getAsync("Resources").then(resources => {
      if (!resources) {
        return undefined;
      }
      const objectLoader = new _object_loader.ObjectLoader(resources, keys, resources.xref);
      return objectLoader.load().then(function () {
        return resources;
      });
    });
  }
  async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
    const data = this.data;
    let appearance = this.appearance;
    const isUsingOwnCanvas = !!(this.data.hasOwnCanvas && intent & _util.RenderingIntentFlag.DISPLAY);
    if (!appearance) {
      if (!isUsingOwnCanvas) {
        return {
          opList: new _operator_list.OperatorList(),
          separateForm: false,
          separateCanvas: false
        };
      }
      appearance = new _stream.StringStream("");
      appearance.dict = new _primitives.Dict();
    }
    const appearanceDict = appearance.dict;
    const resources = await this.loadResources(["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"], appearance);
    const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];
    const matrix = appearanceDict.getArray("Matrix") || [1, 0, 0, 1, 0, 0];
    const transform = getTransformMatrix(data.rect, bbox, matrix);
    const opList = new _operator_list.OperatorList();
    let optionalContent;
    if (this.oc) {
      optionalContent = await evaluator.parseMarkedContentProps(this.oc, null);
    }
    if (optionalContent !== undefined) {
      opList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
    }
    opList.addOp(_util.OPS.beginAnnotation, [data.id, data.rect, transform, matrix, isUsingOwnCanvas]);
    await evaluator.getOperatorList({
      stream: appearance,
      task,
      resources,
      operatorList: opList,
      fallbackFontDict: this._fallbackFontDict
    });
    opList.addOp(_util.OPS.endAnnotation, []);
    if (optionalContent !== undefined) {
      opList.addOp(_util.OPS.endMarkedContent, []);
    }
    this.reset();
    return {
      opList,
      separateForm: false,
      separateCanvas: isUsingOwnCanvas
    };
  }
  async save(evaluator, task, annotationStorage) {
    return null;
  }
  get hasTextContent() {
    return false;
  }
  async extractTextContent(evaluator, task, viewBox) {
    if (!this.appearance) {
      return;
    }
    const resources = await this.loadResources(["ExtGState", "Font", "Properties", "XObject"], this.appearance);
    const text = [];
    const buffer = [];
    const sink = {
      desiredSize: Math.Infinity,
      ready: true,
      enqueue(chunk, size) {
        for (const item of chunk.items) {
          buffer.push(item.str);
          if (item.hasEOL) {
            text.push(buffer.join(""));
            buffer.length = 0;
          }
        }
      }
    };
    await evaluator.getTextContent({
      stream: this.appearance,
      task,
      resources,
      includeMarkedContent: true,
      combineTextItems: true,
      sink,
      viewBox
    });
    this.reset();
    if (buffer.length) {
      text.push(buffer.join(""));
    }
    if (text.length > 0) {
      this.data.textContent = text;
    }
  }
  getFieldObject() {
    if (this.data.kidIds) {
      return {
        id: this.data.id,
        actions: this.data.actions,
        name: this.data.fieldName,
        strokeColor: this.data.borderColor,
        fillColor: this.data.backgroundColor,
        type: "",
        kidIds: this.data.kidIds,
        page: this.data.pageIndex,
        rotation: this.rotation
      };
    }
    return null;
  }
  reset() {
    for (const stream of this._streams) {
      stream.reset();
    }
  }
  _constructFieldName(dict) {
    if (!dict.has("T") && !dict.has("Parent")) {
      (0, _util.warn)("Unknown field name, falling back to empty field name.");
      return "";
    }
    if (!dict.has("Parent")) {
      return (0, _util.stringToPDFString)(dict.get("T"));
    }
    const fieldName = [];
    if (dict.has("T")) {
      fieldName.unshift((0, _util.stringToPDFString)(dict.get("T")));
    }
    let loopDict = dict;
    const visited = new _primitives.RefSet();
    if (dict.objId) {
      visited.put(dict.objId);
    }
    while (loopDict.has("Parent")) {
      loopDict = loopDict.get("Parent");
      if (!(loopDict instanceof _primitives.Dict) || loopDict.objId && visited.has(loopDict.objId)) {
        break;
      }
      if (loopDict.objId) {
        visited.put(loopDict.objId);
      }
      if (loopDict.has("T")) {
        fieldName.unshift((0, _util.stringToPDFString)(loopDict.get("T")));
      }
    }
    return fieldName.join(".");
  }
}
exports.Annotation = Annotation;
class AnnotationBorderStyle {
  constructor() {
    this.width = 1;
    this.style = _util.AnnotationBorderStyleType.SOLID;
    this.dashArray = [3];
    this.horizontalCornerRadius = 0;
    this.verticalCornerRadius = 0;
  }
  setWidth(width, rect = [0, 0, 0, 0]) {
    if (width instanceof _primitives.Name) {
      this.width = 0;
      return;
    }
    if (typeof width === "number") {
      if (width > 0) {
        const maxWidth = (rect[2] - rect[0]) / 2;
        const maxHeight = (rect[3] - rect[1]) / 2;
        if (maxWidth > 0 && maxHeight > 0 && (width > maxWidth || width > maxHeight)) {
          (0, _util.warn)(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
          width = 1;
        }
      }
      this.width = width;
    }
  }
  setStyle(style) {
    if (!(style instanceof _primitives.Name)) {
      return;
    }
    switch (style.name) {
      case "S":
        this.style = _util.AnnotationBorderStyleType.SOLID;
        break;
      case "D":
        this.style = _util.AnnotationBorderStyleType.DASHED;
        break;
      case "B":
        this.style = _util.AnnotationBorderStyleType.BEVELED;
        break;
      case "I":
        this.style = _util.AnnotationBorderStyleType.INSET;
        break;
      case "U":
        this.style = _util.AnnotationBorderStyleType.UNDERLINE;
        break;
      default:
        break;
    }
  }
  setDashArray(dashArray, forceStyle = false) {
    if (Array.isArray(dashArray) && dashArray.length > 0) {
      let isValid = true;
      let allZeros = true;
      for (const element of dashArray) {
        const validNumber = +element >= 0;
        if (!validNumber) {
          isValid = false;
          break;
        } else if (element > 0) {
          allZeros = false;
        }
      }
      if (isValid && !allZeros) {
        this.dashArray = dashArray;
        if (forceStyle) {
          this.setStyle(_primitives.Name.get("D"));
        }
      } else {
        this.width = 0;
      }
    } else if (dashArray) {
      this.width = 0;
    }
  }
  setHorizontalCornerRadius(radius) {
    if (Number.isInteger(radius)) {
      this.horizontalCornerRadius = radius;
    }
  }
  setVerticalCornerRadius(radius) {
    if (Number.isInteger(radius)) {
      this.verticalCornerRadius = radius;
    }
  }
}
exports.AnnotationBorderStyle = AnnotationBorderStyle;
class MarkupAnnotation extends Annotation {
  constructor(params) {
    super(params);
    const {
      dict
    } = params;
    if (dict.has("IRT")) {
      const rawIRT = dict.getRaw("IRT");
      this.data.inReplyTo = rawIRT instanceof _primitives.Ref ? rawIRT.toString() : null;
      const rt = dict.get("RT");
      this.data.replyType = rt instanceof _primitives.Name ? rt.name : _util.AnnotationReplyType.REPLY;
    }
    if (this.data.replyType === _util.AnnotationReplyType.GROUP) {
      const parent = dict.get("IRT");
      this.setTitle(parent.get("T"));
      this.data.titleObj = this._title;
      this.setContents(parent.get("Contents"));
      this.data.contentsObj = this._contents;
      if (!parent.has("CreationDate")) {
        this.data.creationDate = null;
      } else {
        this.setCreationDate(parent.get("CreationDate"));
        this.data.creationDate = this.creationDate;
      }
      if (!parent.has("M")) {
        this.data.modificationDate = null;
      } else {
        this.setModificationDate(parent.get("M"));
        this.data.modificationDate = this.modificationDate;
      }
      this.data.hasPopup = parent.has("Popup");
      if (!parent.has("C")) {
        this.data.color = null;
      } else {
        this.setColor(parent.getArray("C"));
        this.data.color = this.color;
      }
    } else {
      this.data.titleObj = this._title;
      this.setCreationDate(dict.get("CreationDate"));
      this.data.creationDate = this.creationDate;
      this.data.hasPopup = dict.has("Popup");
      if (!dict.has("C")) {
        this.data.color = null;
      }
    }
    if (dict.has("RC")) {
      this.data.richText = _factory.XFAFactory.getRichTextAsHtml(dict.get("RC"));
    }
  }
  setCreationDate(creationDate) {
    this.creationDate = typeof creationDate === "string" ? creationDate : null;
  }
  _setDefaultAppearance({
    xref,
    extra,
    strokeColor,
    fillColor,
    blendMode,
    strokeAlpha,
    fillAlpha,
    pointsCallback
  }) {
    let minX = Number.MAX_VALUE;
    let minY = Number.MAX_VALUE;
    let maxX = Number.MIN_VALUE;
    let maxY = Number.MIN_VALUE;
    const buffer = ["q"];
    if (extra) {
      buffer.push(extra);
    }
    if (strokeColor) {
      buffer.push(`${strokeColor[0]} ${strokeColor[1]} ${strokeColor[2]} RG`);
    }
    if (fillColor) {
      buffer.push(`${fillColor[0]} ${fillColor[1]} ${fillColor[2]} rg`);
    }
    let pointsArray = this.data.quadPoints;
    if (!pointsArray) {
      pointsArray = [[{
        x: this.rectangle[0],
        y: this.rectangle[3]
      }, {
        x: this.rectangle[2],
        y: this.rectangle[3]
      }, {
        x: this.rectangle[0],
        y: this.rectangle[1]
      }, {
        x: this.rectangle[2],
        y: this.rectangle[1]
      }]];
    }
    for (const points of pointsArray) {
      const [mX, MX, mY, MY] = pointsCallback(buffer, points);
      minX = Math.min(minX, mX);
      maxX = Math.max(maxX, MX);
      minY = Math.min(minY, mY);
      maxY = Math.max(maxY, MY);
    }
    buffer.push("Q");
    const formDict = new _primitives.Dict(xref);
    const appearanceStreamDict = new _primitives.Dict(xref);
    appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
    const appearanceStream = new _stream.StringStream(buffer.join(" "));
    appearanceStream.dict = appearanceStreamDict;
    formDict.set("Fm0", appearanceStream);
    const gsDict = new _primitives.Dict(xref);
    if (blendMode) {
      gsDict.set("BM", _primitives.Name.get(blendMode));
    }
    if (typeof strokeAlpha === "number") {
      gsDict.set("CA", strokeAlpha);
    }
    if (typeof fillAlpha === "number") {
      gsDict.set("ca", fillAlpha);
    }
    const stateDict = new _primitives.Dict(xref);
    stateDict.set("GS0", gsDict);
    const resources = new _primitives.Dict(xref);
    resources.set("ExtGState", stateDict);
    resources.set("XObject", formDict);
    const appearanceDict = new _primitives.Dict(xref);
    appearanceDict.set("Resources", resources);
    const bbox = this.data.rect = [minX, minY, maxX, maxY];
    appearanceDict.set("BBox", bbox);
    this.appearance = new _stream.StringStream("/GS0 gs /Fm0 Do");
    this.appearance.dict = appearanceDict;
    this._streams.push(this.appearance, appearanceStream);
  }
  static async createNewAnnotation(xref, annotation, dependencies, params) {
    const annotationRef = xref.getNewTemporaryRef();
    const ap = await this.createNewAppearanceStream(annotation, xref, params);
    const buffer = [];
    let annotationDict;
    if (ap) {
      const apRef = xref.getNewTemporaryRef();
      annotationDict = this.createNewDict(annotation, xref, {
        apRef
      });
      const transform = xref.encrypt ? xref.encrypt.createCipherTransform(apRef.num, apRef.gen) : null;
      (0, _writer.writeObject)(apRef, ap, buffer, transform);
      dependencies.push({
        ref: apRef,
        data: buffer.join("")
      });
    } else {
      annotationDict = this.createNewDict(annotation, xref, {});
    }
    buffer.length = 0;
    const transform = xref.encrypt ? xref.encrypt.createCipherTransform(annotationRef.num, annotationRef.gen) : null;
    (0, _writer.writeObject)(annotationRef, annotationDict, buffer, transform);
    return {
      ref: annotationRef,
      data: buffer.join("")
    };
  }
  static async createNewPrintAnnotation(xref, annotation, params) {
    const ap = await this.createNewAppearanceStream(annotation, xref, params);
    const annotationDict = this.createNewDict(annotation, xref, {
      ap
    });
    return new this.prototype.constructor({
      dict: annotationDict,
      xref,
      isOffscreenCanvasSupported: params.isOffscreenCanvasSupported
    });
  }
}
exports.MarkupAnnotation = MarkupAnnotation;
class WidgetAnnotation extends Annotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    const data = this.data;
    this.ref = params.ref;
    this._needAppearances = params.needAppearances;
    data.annotationType = _util.AnnotationType.WIDGET;
    if (data.fieldName === undefined) {
      data.fieldName = this._constructFieldName(dict);
    }
    if (data.actions === undefined) {
      data.actions = (0, _core_utils.collectActions)(xref, dict, _util.AnnotationActionEventType);
    }
    let fieldValue = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "V",
      getArray: true
    });
    data.fieldValue = this._decodeFormValue(fieldValue);
    const defaultFieldValue = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "DV",
      getArray: true
    });
    data.defaultFieldValue = this._decodeFormValue(defaultFieldValue);
    if (fieldValue === undefined && params.xfaDatasets) {
      const path = this._title.str;
      if (path) {
        this._hasValueFromXFA = true;
        data.fieldValue = fieldValue = params.xfaDatasets.getValue(path);
      }
    }
    if (fieldValue === undefined && data.defaultFieldValue !== null) {
      data.fieldValue = data.defaultFieldValue;
    }
    data.alternativeText = (0, _util.stringToPDFString)(dict.get("TU") || "");
    this.setDefaultAppearance(params);
    data.hasAppearance = this._needAppearances && data.fieldValue !== undefined && data.fieldValue !== null || data.hasAppearance;
    const fieldType = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "FT"
    });
    data.fieldType = fieldType instanceof _primitives.Name ? fieldType.name : null;
    const localResources = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "DR"
    });
    const acroFormResources = params.acroForm.get("DR");
    const appearanceResources = this.appearance && this.appearance.dict.get("Resources");
    this._fieldResources = {
      localResources,
      acroFormResources,
      appearanceResources,
      mergedResources: _primitives.Dict.merge({
        xref,
        dictArray: [localResources, appearanceResources, acroFormResources],
        mergeSubDicts: true
      })
    };
    data.fieldFlags = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "Ff"
    });
    if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
      data.fieldFlags = 0;
    }
    data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
    data.required = this.hasFieldFlag(_util.AnnotationFieldFlag.REQUIRED);
    data.hidden = this._hasFlag(data.annotationFlags, _util.AnnotationFlag.HIDDEN);
  }
  _decodeFormValue(formValue) {
    if (Array.isArray(formValue)) {
      return formValue.filter(item => typeof item === "string").map(item => (0, _util.stringToPDFString)(item));
    } else if (formValue instanceof _primitives.Name) {
      return (0, _util.stringToPDFString)(formValue.name);
    } else if (typeof formValue === "string") {
      return (0, _util.stringToPDFString)(formValue);
    }
    return null;
  }
  hasFieldFlag(flag) {
    return !!(this.data.fieldFlags & flag);
  }
  getRotationMatrix(annotationStorage) {
    const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
    let rotation = storageEntry && storageEntry.rotation;
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    if (rotation === 0) {
      return _util.IDENTITY_MATRIX;
    }
    const width = this.data.rect[2] - this.data.rect[0];
    const height = this.data.rect[3] - this.data.rect[1];
    return (0, _core_utils.getRotationMatrix)(rotation, width, height);
  }
  getBorderAndBackgroundAppearances(annotationStorage) {
    const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
    let rotation = storageEntry && storageEntry.rotation;
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    if (!this.backgroundColor && !this.borderColor) {
      return "";
    }
    const width = this.data.rect[2] - this.data.rect[0];
    const height = this.data.rect[3] - this.data.rect[1];
    const rect = rotation === 0 || rotation === 180 ? `0 0 ${width} ${height} re` : `0 0 ${height} ${width} re`;
    let str = "";
    if (this.backgroundColor) {
      str = `${(0, _default_appearance.getPdfColor)(this.backgroundColor, true)} ${rect} f `;
    }
    if (this.borderColor) {
      const borderWidth = this.borderStyle.width || 1;
      str += `${borderWidth} w ${(0, _default_appearance.getPdfColor)(this.borderColor, false)} ${rect} S `;
    }
    return str;
  }
  async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
    if (renderForms && !(this instanceof SignatureWidgetAnnotation)) {
      return {
        opList: new _operator_list.OperatorList(),
        separateForm: true,
        separateCanvas: false
      };
    }
    if (!this._hasText) {
      return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
    }
    const content = await this._getAppearance(evaluator, task, intent, annotationStorage);
    if (this.appearance && content === null) {
      return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
    }
    const opList = new _operator_list.OperatorList();
    if (!this._defaultAppearance || content === null) {
      return {
        opList,
        separateForm: false,
        separateCanvas: false
      };
    }
    const matrix = [1, 0, 0, 1, 0, 0];
    const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
    const transform = getTransformMatrix(this.data.rect, bbox, matrix);
    let optionalContent;
    if (this.oc) {
      optionalContent = await evaluator.parseMarkedContentProps(this.oc, null);
    }
    if (optionalContent !== undefined) {
      opList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
    }
    opList.addOp(_util.OPS.beginAnnotation, [this.data.id, this.data.rect, transform, this.getRotationMatrix(annotationStorage), false]);
    const stream = new _stream.StringStream(content);
    await evaluator.getOperatorList({
      stream,
      task,
      resources: this._fieldResources.mergedResources,
      operatorList: opList
    });
    opList.addOp(_util.OPS.endAnnotation, []);
    if (optionalContent !== undefined) {
      opList.addOp(_util.OPS.endMarkedContent, []);
    }
    return {
      opList,
      separateForm: false,
      separateCanvas: false
    };
  }
  _getMKDict(rotation) {
    const mk = new _primitives.Dict(null);
    if (rotation) {
      mk.set("R", rotation);
    }
    if (this.borderColor) {
      mk.set("BC", getPdfColorArray(this.borderColor));
    }
    if (this.backgroundColor) {
      mk.set("BG", getPdfColorArray(this.backgroundColor));
    }
    return mk.size > 0 ? mk : null;
  }
  async save(evaluator, task, annotationStorage) {
    const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
    let value = storageEntry && storageEntry.value;
    let rotation = storageEntry && storageEntry.rotation;
    if (value === this.data.fieldValue || value === undefined) {
      if (!this._hasValueFromXFA && rotation === undefined) {
        return null;
      }
      value = value || this.data.fieldValue;
    }
    if (rotation === undefined && !this._hasValueFromXFA && Array.isArray(value) && Array.isArray(this.data.fieldValue) && value.length === this.data.fieldValue.length && value.every((x, i) => x === this.data.fieldValue[i])) {
      return null;
    }
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    let appearance = null;
    if (!this._needAppearances) {
      appearance = await this._getAppearance(evaluator, task, _util.RenderingIntentFlag.SAVE, annotationStorage);
      if (appearance === null) {
        return null;
      }
    } else {}
    let needAppearances = false;
    if (appearance && appearance.needAppearances) {
      needAppearances = true;
      appearance = null;
    }
    const {
      xref
    } = evaluator;
    const originalDict = xref.fetchIfRef(this.ref);
    if (!(originalDict instanceof _primitives.Dict)) {
      return null;
    }
    const dict = new _primitives.Dict(xref);
    for (const key of originalDict.getKeys()) {
      if (key !== "AP") {
        dict.set(key, originalDict.getRaw(key));
      }
    }
    const xfa = {
      path: (0, _util.stringToPDFString)(dict.get("T") || ""),
      value
    };
    const encoder = val => {
      return (0, _core_utils.isAscii)(val) ? val : (0, _core_utils.stringToUTF16String)(val, true);
    };
    dict.set("V", Array.isArray(value) ? value.map(encoder) : encoder(value));
    const maybeMK = this._getMKDict(rotation);
    if (maybeMK) {
      dict.set("MK", maybeMK);
    }
    const encrypt = xref.encrypt;
    const originalTransform = encrypt ? encrypt.createCipherTransform(this.ref.num, this.ref.gen) : null;
    const buffer = [];
    const changes = [{
      ref: this.ref,
      data: "",
      xfa,
      needAppearances
    }];
    if (appearance !== null) {
      const newRef = xref.getNewTemporaryRef();
      const AP = new _primitives.Dict(xref);
      dict.set("AP", AP);
      AP.set("N", newRef);
      let newTransform = null;
      if (encrypt) {
        newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
        appearance = newTransform.encryptString(appearance);
      }
      const resources = this._getSaveFieldResources(xref);
      const appearanceStream = new _stream.StringStream(appearance);
      const appearanceDict = appearanceStream.dict = new _primitives.Dict(xref);
      appearanceDict.set("Length", appearance.length);
      appearanceDict.set("Subtype", _primitives.Name.get("Form"));
      appearanceDict.set("Resources", resources);
      appearanceDict.set("BBox", [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]]);
      const rotationMatrix = this.getRotationMatrix(annotationStorage);
      if (rotationMatrix !== _util.IDENTITY_MATRIX) {
        appearanceDict.set("Matrix", rotationMatrix);
      }
      (0, _writer.writeObject)(newRef, appearanceStream, buffer, newTransform);
      changes.push({
        ref: newRef,
        data: buffer.join(""),
        xfa: null,
        needAppearances: false
      });
      buffer.length = 0;
    }
    dict.set("M", `D:${(0, _util.getModificationDate)()}`);
    (0, _writer.writeObject)(this.ref, dict, buffer, originalTransform);
    changes[0].data = buffer.join("");
    return changes;
  }
  async _getAppearance(evaluator, task, intent, annotationStorage) {
    const isPassword = this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD);
    if (isPassword) {
      return null;
    }
    const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
    let value, rotation;
    if (storageEntry) {
      value = storageEntry.formattedValue || storageEntry.value;
      rotation = storageEntry.rotation;
    }
    if (rotation === undefined && value === undefined && !this._needAppearances) {
      if (!this._hasValueFromXFA || this.appearance) {
        return null;
      }
    }
    const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
    if (value === undefined) {
      value = this.data.fieldValue;
      if (!value) {
        return `/Tx BMC q ${colors}Q EMC`;
      }
    }
    if (Array.isArray(value) && value.length === 1) {
      value = value[0];
    }
    (0, _util.assert)(typeof value === "string", "Expected `value` to be a string.");
    if (!this.data.combo) {
      value = value.trim();
    } else {
      const option = this.data.options.find(({
        exportValue
      }) => value === exportValue) || this.data.options[0];
      value = option && option.displayValue || "";
    }
    if (value === "") {
      return `/Tx BMC q ${colors}Q EMC`;
    }
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    let lineCount = -1;
    let lines;
    if (this.data.multiLine) {
      lines = value.split(/\r\n?|\n/).map(line => line.normalize("NFC"));
      lineCount = lines.length;
    } else {
      lines = [value.replace(/\r\n?|\n/, "").normalize("NFC")];
    }
    const defaultPadding = 1;
    const defaultHPadding = 2;
    let totalHeight = this.data.rect[3] - this.data.rect[1];
    let totalWidth = this.data.rect[2] - this.data.rect[0];
    if (rotation === 90 || rotation === 270) {
      [totalWidth, totalHeight] = [totalHeight, totalWidth];
    }
    if (!this._defaultAppearance) {
      this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
    }
    let font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
    let defaultAppearance, fontSize, lineHeight;
    const encodedLines = [];
    let encodingError = false;
    for (const line of lines) {
      const encodedString = font.encodeString(line);
      if (encodedString.length > 1) {
        encodingError = true;
      }
      encodedLines.push(encodedString.join(""));
    }
    if (encodingError && intent & _util.RenderingIntentFlag.SAVE) {
      return {
        needAppearances: true
      };
    }
    if (encodingError && this._isOffscreenCanvasSupported) {
      const fontFamily = this.data.comb ? "monospace" : "sans-serif";
      const fakeUnicodeFont = new _default_appearance.FakeUnicodeFont(evaluator.xref, fontFamily);
      const resources = fakeUnicodeFont.createFontResources(lines.join(""));
      const newFont = resources.getRaw("Font");
      if (this._fieldResources.mergedResources.has("Font")) {
        const oldFont = this._fieldResources.mergedResources.get("Font");
        for (const key of newFont.getKeys()) {
          oldFont.set(key, newFont.getRaw(key));
        }
      } else {
        this._fieldResources.mergedResources.set("Font", newFont);
      }
      const fontName = fakeUnicodeFont.fontName.name;
      font = await WidgetAnnotation._getFontData(evaluator, task, {
        fontName,
        fontSize: 0
      }, resources);
      for (let i = 0, ii = encodedLines.length; i < ii; i++) {
        encodedLines[i] = (0, _core_utils.stringToUTF16String)(lines[i]);
      }
      const savedDefaultAppearance = Object.assign(Object.create(null), this.data.defaultAppearanceData);
      this.data.defaultAppearanceData.fontSize = 0;
      this.data.defaultAppearanceData.fontName = fontName;
      [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(totalHeight - 2 * defaultPadding, totalWidth - 2 * defaultHPadding, value, font, lineCount);
      this.data.defaultAppearanceData = savedDefaultAppearance;
    } else {
      if (!this._isOffscreenCanvasSupported) {
        (0, _util.warn)("_getAppearance: OffscreenCanvas is not supported, annotation may not render correctly.");
      }
      [defaultAppearance, fontSize, lineHeight] = this._computeFontSize(totalHeight - 2 * defaultPadding, totalWidth - 2 * defaultHPadding, value, font, lineCount);
    }
    let descent = font.descent;
    if (isNaN(descent)) {
      descent = _util.BASELINE_FACTOR * lineHeight;
    } else {
      descent = Math.max(_util.BASELINE_FACTOR * lineHeight, Math.abs(descent) * fontSize);
    }
    const defaultVPadding = Math.min(Math.floor((totalHeight - fontSize) / 2), defaultPadding);
    const alignment = this.data.textAlignment;
    if (this.data.multiLine) {
      return this._getMultilineAppearance(defaultAppearance, encodedLines, font, fontSize, totalWidth, totalHeight, alignment, defaultHPadding, defaultVPadding, descent, lineHeight, annotationStorage);
    }
    if (this.data.comb) {
      return this._getCombAppearance(defaultAppearance, font, encodedLines[0], fontSize, totalWidth, totalHeight, defaultHPadding, defaultVPadding, descent, lineHeight, annotationStorage);
    }
    const bottomPadding = defaultVPadding + descent;
    if (alignment === 0 || alignment > 2) {
      return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${(0, _core_utils.numberToString)(defaultHPadding)} ${(0, _core_utils.numberToString)(bottomPadding)} Tm (${(0, _core_utils.escapeString)(encodedLines[0])}) Tj` + " ET Q EMC";
    }
    const prevInfo = {
      shift: 0
    };
    const renderedText = this._renderText(encodedLines[0], font, fontSize, totalWidth, alignment, prevInfo, defaultHPadding, bottomPadding);
    return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
  }
  static async _getFontData(evaluator, task, appearanceData, resources) {
    const operatorList = new _operator_list.OperatorList();
    const initialState = {
      font: null,
      clone() {
        return this;
      }
    };
    const {
      fontName,
      fontSize
    } = appearanceData;
    await evaluator.handleSetFont(resources, [fontName && _primitives.Name.get(fontName), fontSize], null, operatorList, task, initialState, null);
    return initialState.font;
  }
  _getTextWidth(text, font) {
    return font.charsToGlyphs(text).reduce((width, glyph) => width + glyph.width, 0) / 1000;
  }
  _computeFontSize(height, width, text, font, lineCount) {
    let {
      fontSize
    } = this.data.defaultAppearanceData;
    let lineHeight = (fontSize || 12) * _util.LINE_FACTOR,
      numberOfLines = Math.round(height / lineHeight);
    if (!fontSize) {
      const roundWithTwoDigits = x => Math.floor(x * 100) / 100;
      if (lineCount === -1) {
        const textWidth = this._getTextWidth(text, font);
        fontSize = roundWithTwoDigits(Math.min(height / _util.LINE_FACTOR, textWidth > width ? width / textWidth : Infinity));
        numberOfLines = 1;
      } else {
        const lines = text.split(/\r\n?|\n/);
        const cachedLines = [];
        for (const line of lines) {
          const encoded = font.encodeString(line).join("");
          const glyphs = font.charsToGlyphs(encoded);
          const positions = font.getCharPositions(encoded);
          cachedLines.push({
            line: encoded,
            glyphs,
            positions
          });
        }
        const isTooBig = fsize => {
          let totalHeight = 0;
          for (const cache of cachedLines) {
            const chunks = this._splitLine(null, font, fsize, width, cache);
            totalHeight += chunks.length * fsize;
            if (totalHeight > height) {
              return true;
            }
          }
          return false;
        };
        numberOfLines = Math.max(numberOfLines, lineCount);
        while (true) {
          lineHeight = height / numberOfLines;
          fontSize = roundWithTwoDigits(lineHeight / _util.LINE_FACTOR);
          if (isTooBig(fontSize)) {
            numberOfLines++;
            continue;
          }
          break;
        }
      }
      const {
        fontName,
        fontColor
      } = this.data.defaultAppearanceData;
      this._defaultAppearance = (0, _default_appearance.createDefaultAppearance)({
        fontSize,
        fontName,
        fontColor
      });
    }
    return [this._defaultAppearance, fontSize, height / numberOfLines];
  }
  _renderText(text, font, fontSize, totalWidth, alignment, prevInfo, hPadding, vPadding) {
    let shift;
    if (alignment === 1) {
      const width = this._getTextWidth(text, font) * fontSize;
      shift = (totalWidth - width) / 2;
    } else if (alignment === 2) {
      const width = this._getTextWidth(text, font) * fontSize;
      shift = totalWidth - width - hPadding;
    } else {
      shift = hPadding;
    }
    const shiftStr = (0, _core_utils.numberToString)(shift - prevInfo.shift);
    prevInfo.shift = shift;
    vPadding = (0, _core_utils.numberToString)(vPadding);
    return `${shiftStr} ${vPadding} Td (${(0, _core_utils.escapeString)(text)}) Tj`;
  }
  _getSaveFieldResources(xref) {
    const {
      localResources,
      appearanceResources,
      acroFormResources
    } = this._fieldResources;
    const fontName = this.data.defaultAppearanceData && this.data.defaultAppearanceData.fontName;
    if (!fontName) {
      return localResources || _primitives.Dict.empty;
    }
    for (const resources of [localResources, appearanceResources]) {
      if (resources instanceof _primitives.Dict) {
        const localFont = resources.get("Font");
        if (localFont instanceof _primitives.Dict && localFont.has(fontName)) {
          return resources;
        }
      }
    }
    if (acroFormResources instanceof _primitives.Dict) {
      const acroFormFont = acroFormResources.get("Font");
      if (acroFormFont instanceof _primitives.Dict && acroFormFont.has(fontName)) {
        const subFontDict = new _primitives.Dict(xref);
        subFontDict.set(fontName, acroFormFont.getRaw(fontName));
        const subResourcesDict = new _primitives.Dict(xref);
        subResourcesDict.set("Font", subFontDict);
        return _primitives.Dict.merge({
          xref,
          dictArray: [subResourcesDict, localResources],
          mergeSubDicts: true
        });
      }
    }
    return localResources || _primitives.Dict.empty;
  }
  getFieldObject() {
    return null;
  }
}
class TextWidgetAnnotation extends WidgetAnnotation {
  constructor(params) {
    super(params);
    this._hasText = true;
    const dict = params.dict;
    if (typeof this.data.fieldValue !== "string") {
      this.data.fieldValue = "";
    }
    let alignment = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "Q"
    });
    if (!Number.isInteger(alignment) || alignment < 0 || alignment > 2) {
      alignment = null;
    }
    this.data.textAlignment = alignment;
    let maximumLength = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "MaxLen"
    });
    if (!Number.isInteger(maximumLength) || maximumLength < 0) {
      maximumLength = 0;
    }
    this.data.maxLen = maximumLength;
    this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
    this.data.comb = this.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !this.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== 0;
    this.data.doNotScroll = this.hasFieldFlag(_util.AnnotationFieldFlag.DONOTSCROLL);
  }
  _getCombAppearance(defaultAppearance, font, text, fontSize, width, height, hPadding, vPadding, descent, lineHeight, annotationStorage) {
    const combWidth = width / this.data.maxLen;
    const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
    const buf = [];
    const positions = font.getCharPositions(text);
    for (const [start, end] of positions) {
      buf.push(`(${(0, _core_utils.escapeString)(text.substring(start, end))}) Tj`);
    }
    const renderedComb = buf.join(` ${(0, _core_utils.numberToString)(combWidth)} 0 Td `);
    return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 ${(0, _core_utils.numberToString)(hPadding)} ${(0, _core_utils.numberToString)(vPadding + descent)} Tm ${renderedComb}` + " ET Q EMC";
  }
  _getMultilineAppearance(defaultAppearance, lines, font, fontSize, width, height, alignment, hPadding, vPadding, descent, lineHeight, annotationStorage) {
    const buf = [];
    const totalWidth = width - 2 * hPadding;
    const prevInfo = {
      shift: 0
    };
    for (let i = 0, ii = lines.length; i < ii; i++) {
      const line = lines[i];
      const chunks = this._splitLine(line, font, fontSize, totalWidth);
      for (let j = 0, jj = chunks.length; j < jj; j++) {
        const chunk = chunks[j];
        const vShift = i === 0 && j === 0 ? -vPadding - (lineHeight - descent) : -lineHeight;
        buf.push(this._renderText(chunk, font, fontSize, width, alignment, prevInfo, hPadding, vShift));
      }
    }
    const colors = this.getBorderAndBackgroundAppearances(annotationStorage);
    const renderedText = buf.join("\n");
    return `/Tx BMC q ${colors}BT ` + defaultAppearance + ` 1 0 0 1 0 ${(0, _core_utils.numberToString)(height)} Tm ${renderedText}` + " ET Q EMC";
  }
  _splitLine(line, font, fontSize, width, cache = {}) {
    line = cache.line || line;
    const glyphs = cache.glyphs || font.charsToGlyphs(line);
    if (glyphs.length <= 1) {
      return [line];
    }
    const positions = cache.positions || font.getCharPositions(line);
    const scale = fontSize / 1000;
    const chunks = [];
    let lastSpacePosInStringStart = -1,
      lastSpacePosInStringEnd = -1,
      lastSpacePos = -1,
      startChunk = 0,
      currentWidth = 0;
    for (let i = 0, ii = glyphs.length; i < ii; i++) {
      const [start, end] = positions[i];
      const glyph = glyphs[i];
      const glyphWidth = glyph.width * scale;
      if (glyph.unicode === " ") {
        if (currentWidth + glyphWidth > width) {
          chunks.push(line.substring(startChunk, start));
          startChunk = start;
          currentWidth = glyphWidth;
          lastSpacePosInStringStart = -1;
          lastSpacePos = -1;
        } else {
          currentWidth += glyphWidth;
          lastSpacePosInStringStart = start;
          lastSpacePosInStringEnd = end;
          lastSpacePos = i;
        }
      } else {
        if (currentWidth + glyphWidth > width) {
          if (lastSpacePosInStringStart !== -1) {
            chunks.push(line.substring(startChunk, lastSpacePosInStringEnd));
            startChunk = lastSpacePosInStringEnd;
            i = lastSpacePos + 1;
            lastSpacePosInStringStart = -1;
            currentWidth = 0;
          } else {
            chunks.push(line.substring(startChunk, start));
            startChunk = start;
            currentWidth = glyphWidth;
          }
        } else {
          currentWidth += glyphWidth;
        }
      }
    }
    if (startChunk < line.length) {
      chunks.push(line.substring(startChunk, line.length));
    }
    return chunks;
  }
  getFieldObject() {
    return {
      id: this.data.id,
      value: this.data.fieldValue,
      defaultValue: this.data.defaultFieldValue || "",
      multiline: this.data.multiLine,
      password: this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD),
      charLimit: this.data.maxLen,
      comb: this.data.comb,
      editable: !this.data.readOnly,
      hidden: this.data.hidden,
      name: this.data.fieldName,
      rect: this.data.rect,
      actions: this.data.actions,
      page: this.data.pageIndex,
      strokeColor: this.data.borderColor,
      fillColor: this.data.backgroundColor,
      rotation: this.rotation,
      type: "text"
    };
  }
}
class ButtonWidgetAnnotation extends WidgetAnnotation {
  constructor(params) {
    super(params);
    this.checkedAppearance = null;
    this.uncheckedAppearance = null;
    this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
    this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
    this.data.pushButton = this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
    this.data.isTooltipOnly = false;
    if (this.data.checkBox) {
      this._processCheckBox(params);
    } else if (this.data.radioButton) {
      this._processRadioButton(params);
    } else if (this.data.pushButton) {
      this.data.hasOwnCanvas = true;
      this._processPushButton(params);
    } else {
      (0, _util.warn)("Invalid field flags for button widget annotation");
    }
  }
  async getOperatorList(evaluator, task, intent, renderForms, annotationStorage) {
    if (this.data.pushButton) {
      return super.getOperatorList(evaluator, task, intent, false, annotationStorage);
    }
    let value = null;
    let rotation = null;
    if (annotationStorage) {
      const storageEntry = annotationStorage.get(this.data.id);
      value = storageEntry ? storageEntry.value : null;
      rotation = storageEntry ? storageEntry.rotation : null;
    }
    if (value === null && this.appearance) {
      return super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
    }
    if (value === null || value === undefined) {
      if (this.data.checkBox) {
        value = this.data.fieldValue === this.data.exportValue;
      } else {
        value = this.data.fieldValue === this.data.buttonValue;
      }
    }
    const appearance = value ? this.checkedAppearance : this.uncheckedAppearance;
    if (appearance) {
      const savedAppearance = this.appearance;
      const savedMatrix = appearance.dict.getArray("Matrix") || _util.IDENTITY_MATRIX;
      if (rotation) {
        appearance.dict.set("Matrix", this.getRotationMatrix(annotationStorage));
      }
      this.appearance = appearance;
      const operatorList = super.getOperatorList(evaluator, task, intent, renderForms, annotationStorage);
      this.appearance = savedAppearance;
      appearance.dict.set("Matrix", savedMatrix);
      return operatorList;
    }
    return {
      opList: new _operator_list.OperatorList(),
      separateForm: false,
      separateCanvas: false
    };
  }
  async save(evaluator, task, annotationStorage) {
    if (this.data.checkBox) {
      return this._saveCheckbox(evaluator, task, annotationStorage);
    }
    if (this.data.radioButton) {
      return this._saveRadioButton(evaluator, task, annotationStorage);
    }
    return null;
  }
  async _saveCheckbox(evaluator, task, annotationStorage) {
    if (!annotationStorage) {
      return null;
    }
    const storageEntry = annotationStorage.get(this.data.id);
    let rotation = storageEntry && storageEntry.rotation;
    let value = storageEntry && storageEntry.value;
    if (rotation === undefined) {
      if (value === undefined) {
        return null;
      }
      const defaultValue = this.data.fieldValue === this.data.exportValue;
      if (defaultValue === value) {
        return null;
      }
    }
    const dict = evaluator.xref.fetchIfRef(this.ref);
    if (!(dict instanceof _primitives.Dict)) {
      return null;
    }
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    if (value === undefined) {
      value = this.data.fieldValue === this.data.exportValue;
    }
    const xfa = {
      path: (0, _util.stringToPDFString)(dict.get("T") || ""),
      value: value ? this.data.exportValue : ""
    };
    const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
    dict.set("V", name);
    dict.set("AS", name);
    dict.set("M", `D:${(0, _util.getModificationDate)()}`);
    const maybeMK = this._getMKDict(rotation);
    if (maybeMK) {
      dict.set("MK", maybeMK);
    }
    const encrypt = evaluator.xref.encrypt;
    let originalTransform = null;
    if (encrypt) {
      originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
    }
    const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
    (0, _writer.writeDict)(dict, buffer, originalTransform);
    buffer.push("\nendobj\n");
    return [{
      ref: this.ref,
      data: buffer.join(""),
      xfa
    }];
  }
  async _saveRadioButton(evaluator, task, annotationStorage) {
    if (!annotationStorage) {
      return null;
    }
    const storageEntry = annotationStorage.get(this.data.id);
    let rotation = storageEntry && storageEntry.rotation;
    let value = storageEntry && storageEntry.value;
    if (rotation === undefined) {
      if (value === undefined) {
        return null;
      }
      const defaultValue = this.data.fieldValue === this.data.buttonValue;
      if (defaultValue === value) {
        return null;
      }
    }
    const dict = evaluator.xref.fetchIfRef(this.ref);
    if (!(dict instanceof _primitives.Dict)) {
      return null;
    }
    if (value === undefined) {
      value = this.data.fieldValue === this.data.buttonValue;
    }
    if (rotation === undefined) {
      rotation = this.rotation;
    }
    const xfa = {
      path: (0, _util.stringToPDFString)(dict.get("T") || ""),
      value: value ? this.data.buttonValue : ""
    };
    const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
    let parentBuffer = null;
    const encrypt = evaluator.xref.encrypt;
    if (value) {
      if (this.parent instanceof _primitives.Ref) {
        const parent = evaluator.xref.fetch(this.parent);
        let parentTransform = null;
        if (encrypt) {
          parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
        }
        parent.set("V", name);
        parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
        (0, _writer.writeDict)(parent, parentBuffer, parentTransform);
        parentBuffer.push("\nendobj\n");
      } else if (this.parent instanceof _primitives.Dict) {
        this.parent.set("V", name);
      }
    }
    dict.set("AS", name);
    dict.set("M", `D:${(0, _util.getModificationDate)()}`);
    const maybeMK = this._getMKDict(rotation);
    if (maybeMK) {
      dict.set("MK", maybeMK);
    }
    let originalTransform = null;
    if (encrypt) {
      originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
    }
    const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
    (0, _writer.writeDict)(dict, buffer, originalTransform);
    buffer.push("\nendobj\n");
    const newRefs = [{
      ref: this.ref,
      data: buffer.join(""),
      xfa
    }];
    if (parentBuffer !== null) {
      newRefs.push({
        ref: this.parent,
        data: parentBuffer.join(""),
        xfa: null
      });
    }
    return newRefs;
  }
  _getDefaultCheckedAppearance(params, type) {
    const width = this.data.rect[2] - this.data.rect[0];
    const height = this.data.rect[3] - this.data.rect[1];
    const bbox = [0, 0, width, height];
    const FONT_RATIO = 0.8;
    const fontSize = Math.min(width, height) * FONT_RATIO;
    let metrics, char;
    if (type === "check") {
      metrics = {
        width: 0.755 * fontSize,
        height: 0.705 * fontSize
      };
      char = "\x33";
    } else if (type === "disc") {
      metrics = {
        width: 0.791 * fontSize,
        height: 0.705 * fontSize
      };
      char = "\x6C";
    } else {
      (0, _util.unreachable)(`_getDefaultCheckedAppearance - unsupported type: ${type}`);
    }
    const xShift = (0, _core_utils.numberToString)((width - metrics.width) / 2);
    const yShift = (0, _core_utils.numberToString)((height - metrics.height) / 2);
    const appearance = `q BT /PdfJsZaDb ${fontSize} Tf 0 g ${xShift} ${yShift} Td (${char}) Tj ET Q`;
    const appearanceStreamDict = new _primitives.Dict(params.xref);
    appearanceStreamDict.set("FormType", 1);
    appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
    appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
    appearanceStreamDict.set("BBox", bbox);
    appearanceStreamDict.set("Matrix", [1, 0, 0, 1, 0, 0]);
    appearanceStreamDict.set("Length", appearance.length);
    const resources = new _primitives.Dict(params.xref);
    const font = new _primitives.Dict(params.xref);
    font.set("PdfJsZaDb", this.fallbackFontDict);
    resources.set("Font", font);
    appearanceStreamDict.set("Resources", resources);
    this.checkedAppearance = new _stream.StringStream(appearance);
    this.checkedAppearance.dict = appearanceStreamDict;
    this._streams.push(this.checkedAppearance);
  }
  _processCheckBox(params) {
    const customAppearance = params.dict.get("AP");
    if (!(customAppearance instanceof _primitives.Dict)) {
      return;
    }
    const normalAppearance = customAppearance.get("N");
    if (!(normalAppearance instanceof _primitives.Dict)) {
      return;
    }
    const asValue = this._decodeFormValue(params.dict.get("AS"));
    if (typeof asValue === "string") {
      this.data.fieldValue = asValue;
    }
    const yes = this.data.fieldValue !== null && this.data.fieldValue !== "Off" ? this.data.fieldValue : "Yes";
    const exportValues = normalAppearance.getKeys();
    if (exportValues.length === 0) {
      exportValues.push("Off", yes);
    } else if (exportValues.length === 1) {
      if (exportValues[0] === "Off") {
        exportValues.push(yes);
      } else {
        exportValues.unshift("Off");
      }
    } else if (exportValues.includes(yes)) {
      exportValues.length = 0;
      exportValues.push("Off", yes);
    } else {
      const otherYes = exportValues.find(v => v !== "Off");
      exportValues.length = 0;
      exportValues.push("Off", otherYes);
    }
    if (!exportValues.includes(this.data.fieldValue)) {
      this.data.fieldValue = "Off";
    }
    this.data.exportValue = exportValues[1];
    const checkedAppearance = normalAppearance.get(this.data.exportValue);
    this.checkedAppearance = checkedAppearance instanceof _base_stream.BaseStream ? checkedAppearance : null;
    const uncheckedAppearance = normalAppearance.get("Off");
    this.uncheckedAppearance = uncheckedAppearance instanceof _base_stream.BaseStream ? uncheckedAppearance : null;
    if (this.checkedAppearance) {
      this._streams.push(this.checkedAppearance);
    } else {
      this._getDefaultCheckedAppearance(params, "check");
    }
    if (this.uncheckedAppearance) {
      this._streams.push(this.uncheckedAppearance);
    }
    this._fallbackFontDict = this.fallbackFontDict;
  }
  _processRadioButton(params) {
    this.data.fieldValue = this.data.buttonValue = null;
    const fieldParent = params.dict.get("Parent");
    if (fieldParent instanceof _primitives.Dict) {
      this.parent = params.dict.getRaw("Parent");
      const fieldParentValue = fieldParent.get("V");
      if (fieldParentValue instanceof _primitives.Name) {
        this.data.fieldValue = this._decodeFormValue(fieldParentValue);
      }
    }
    const appearanceStates = params.dict.get("AP");
    if (!(appearanceStates instanceof _primitives.Dict)) {
      return;
    }
    const normalAppearance = appearanceStates.get("N");
    if (!(normalAppearance instanceof _primitives.Dict)) {
      return;
    }
    for (const key of normalAppearance.getKeys()) {
      if (key !== "Off") {
        this.data.buttonValue = this._decodeFormValue(key);
        break;
      }
    }
    const checkedAppearance = normalAppearance.get(this.data.buttonValue);
    this.checkedAppearance = checkedAppearance instanceof _base_stream.BaseStream ? checkedAppearance : null;
    const uncheckedAppearance = normalAppearance.get("Off");
    this.uncheckedAppearance = uncheckedAppearance instanceof _base_stream.BaseStream ? uncheckedAppearance : null;
    if (this.checkedAppearance) {
      this._streams.push(this.checkedAppearance);
    } else {
      this._getDefaultCheckedAppearance(params, "disc");
    }
    if (this.uncheckedAppearance) {
      this._streams.push(this.uncheckedAppearance);
    }
    this._fallbackFontDict = this.fallbackFontDict;
  }
  _processPushButton(params) {
    if (!params.dict.has("A") && !params.dict.has("AA") && !this.data.alternativeText) {
      (0, _util.warn)("Push buttons without action dictionaries are not supported");
      return;
    }
    this.data.isTooltipOnly = !params.dict.has("A") && !params.dict.has("AA");
    _catalog.Catalog.parseDestDictionary({
      destDict: params.dict,
      resultObj: this.data,
      docBaseUrl: params.pdfManager.docBaseUrl,
      docAttachments: params.attachments
    });
  }
  getFieldObject() {
    let type = "button";
    let exportValues;
    if (this.data.checkBox) {
      type = "checkbox";
      exportValues = this.data.exportValue;
    } else if (this.data.radioButton) {
      type = "radiobutton";
      exportValues = this.data.buttonValue;
    }
    return {
      id: this.data.id,
      value: this.data.fieldValue || "Off",
      defaultValue: this.data.defaultFieldValue,
      exportValues,
      editable: !this.data.readOnly,
      name: this.data.fieldName,
      rect: this.data.rect,
      hidden: this.data.hidden,
      actions: this.data.actions,
      page: this.data.pageIndex,
      strokeColor: this.data.borderColor,
      fillColor: this.data.backgroundColor,
      rotation: this.rotation,
      type
    };
  }
  get fallbackFontDict() {
    const dict = new _primitives.Dict();
    dict.set("BaseFont", _primitives.Name.get("ZapfDingbats"));
    dict.set("Type", _primitives.Name.get("FallbackType"));
    dict.set("Subtype", _primitives.Name.get("FallbackType"));
    dict.set("Encoding", _primitives.Name.get("ZapfDingbatsEncoding"));
    return (0, _util.shadow)(this, "fallbackFontDict", dict);
  }
}
class ChoiceWidgetAnnotation extends WidgetAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.options = [];
    const options = (0, _core_utils.getInheritableProperty)({
      dict,
      key: "Opt"
    });
    if (Array.isArray(options)) {
      for (let i = 0, ii = options.length; i < ii; i++) {
        const option = xref.fetchIfRef(options[i]);
        const isOptionArray = Array.isArray(option);
        this.data.options[i] = {
          exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
          displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
        };
      }
    }
    if (typeof this.data.fieldValue === "string") {
      this.data.fieldValue = [this.data.fieldValue];
    } else if (!this.data.fieldValue) {
      this.data.fieldValue = [];
    }
    this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
    this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
    this._hasText = true;
  }
  getFieldObject() {
    const type = this.data.combo ? "combobox" : "listbox";
    const value = this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null;
    return {
      id: this.data.id,
      value,
      defaultValue: this.data.defaultFieldValue,
      editable: !this.data.readOnly,
      name: this.data.fieldName,
      rect: this.data.rect,
      numItems: this.data.fieldValue.length,
      multipleSelection: this.data.multiSelect,
      hidden: this.data.hidden,
      actions: this.data.actions,
      items: this.data.options,
      page: this.data.pageIndex,
      strokeColor: this.data.borderColor,
      fillColor: this.data.backgroundColor,
      rotation: this.rotation,
      type
    };
  }
  async _getAppearance(evaluator, task, intent, annotationStorage) {
    if (this.data.combo) {
      return super._getAppearance(evaluator, task, intent, annotationStorage);
    }
    let exportedValue, rotation;
    const storageEntry = annotationStorage ? annotationStorage.get(this.data.id) : undefined;
    if (storageEntry) {
      rotation = storageEntry.rotation;
      exportedValue = storageEntry.value;
    }
    if (rotation === undefined && exportedValue === undefined && !this._needAppearances) {
      return null;
    }
    if (exportedValue === undefined) {
      exportedValue = this.data.fieldValue;
    } else if (!Array.isArray(exportedValue)) {
      exportedValue = [exportedValue];
    }
    const defaultPadding = 1;
    const defaultHPadding = 2;
    let totalHeight = this.data.rect[3] - this.data.rect[1];
    let totalWidth = this.data.rect[2] - this.data.rect[0];
    if (rotation === 90 || rotation === 270) {
      [totalWidth, totalHeight] = [totalHeight, totalWidth];
    }
    const lineCount = this.data.options.length;
    const valueIndices = [];
    for (let i = 0; i < lineCount; i++) {
      const {
        exportValue
      } = this.data.options[i];
      if (exportedValue.includes(exportValue)) {
        valueIndices.push(i);
      }
    }
    if (!this._defaultAppearance) {
      this.data.defaultAppearanceData = (0, _default_appearance.parseDefaultAppearance)(this._defaultAppearance = "/Helvetica 0 Tf 0 g");
    }
    const font = await WidgetAnnotation._getFontData(evaluator, task, this.data.defaultAppearanceData, this._fieldResources.mergedResources);
    let defaultAppearance;
    let {
      fontSize
    } = this.data.defaultAppearanceData;
    if (!fontSize) {
      const lineHeight = (totalHeight - defaultPadding) / lineCount;
      let lineWidth = -1;
      let value;
      for (const {
        displayValue
      } of this.data.options) {
        const width = this._getTextWidth(displayValue, font);
        if (width > lineWidth) {
          lineWidth = width;
          value = displayValue;
        }
      }
      [defaultAppearance, fontSize] = this._computeFontSize(lineHeight, totalWidth - 2 * defaultHPadding, value, font, -1);
    } else {
      defaultAppearance = this._defaultAppearance;
    }
    const lineHeight = fontSize * _util.LINE_FACTOR;
    const vPadding = (lineHeight - fontSize) / 2;
    const numberOfVisibleLines = Math.floor(totalHeight / lineHeight);
    let firstIndex;
    if (valueIndices.length === 1) {
      const valuePosition = valueIndices[0];
      const indexInPage = valuePosition % numberOfVisibleLines;
      firstIndex = valuePosition - indexInPage;
    } else {
      firstIndex = valueIndices.length ? valueIndices[0] : 0;
    }
    const end = Math.min(firstIndex + numberOfVisibleLines + 1, lineCount);
    const buf = ["/Tx BMC q", `1 1 ${totalWidth} ${totalHeight} re W n`];
    if (valueIndices.length) {
      buf.push("0.600006 0.756866 0.854904 rg");
      for (const index of valueIndices) {
        if (firstIndex <= index && index < end) {
          buf.push(`1 ${totalHeight - (index - firstIndex + 1) * lineHeight} ${totalWidth} ${lineHeight} re f`);
        }
      }
    }
    buf.push("BT", defaultAppearance, `1 0 0 1 0 ${totalHeight} Tm`);
    const prevInfo = {
      shift: 0
    };
    for (let i = firstIndex; i < end; i++) {
      const {
        displayValue
      } = this.data.options[i];
      const vpadding = i === firstIndex ? vPadding : 0;
      buf.push(this._renderText(displayValue, font, fontSize, totalWidth, 0, prevInfo, defaultHPadding, -lineHeight + vpadding));
    }
    buf.push("ET Q EMC");
    return buf.join("\n");
  }
}
class SignatureWidgetAnnotation extends WidgetAnnotation {
  constructor(params) {
    super(params);
    this.data.fieldValue = null;
  }
  getFieldObject() {
    return {
      id: this.data.id,
      value: null,
      page: this.data.pageIndex,
      type: "signature"
    };
  }
}
class TextAnnotation extends MarkupAnnotation {
  constructor(params) {
    const DEFAULT_ICON_SIZE = 22;
    super(params);
    const {
      dict
    } = params;
    this.data.annotationType = _util.AnnotationType.TEXT;
    if (this.data.hasAppearance) {
      this.data.name = "NoIcon";
    } else {
      this.data.rect[1] = this.data.rect[3] - DEFAULT_ICON_SIZE;
      this.data.rect[2] = this.data.rect[0] + DEFAULT_ICON_SIZE;
      this.data.name = dict.has("Name") ? dict.get("Name").name : "Note";
    }
    if (dict.has("State")) {
      this.data.state = dict.get("State") || null;
      this.data.stateModel = dict.get("StateModel") || null;
    } else {
      this.data.state = null;
      this.data.stateModel = null;
    }
  }
}
class LinkAnnotation extends Annotation {
  constructor(params) {
    super(params);
    this.data.annotationType = _util.AnnotationType.LINK;
    const quadPoints = getQuadPoints(params.dict, this.rectangle);
    if (quadPoints) {
      this.data.quadPoints = quadPoints;
    }
    this.data.borderColor = this.data.borderColor || this.data.color;
    _catalog.Catalog.parseDestDictionary({
      destDict: params.dict,
      resultObj: this.data,
      docBaseUrl: params.pdfManager.docBaseUrl,
      docAttachments: params.attachments
    });
  }
}
class PopupAnnotation extends Annotation {
  constructor(params) {
    super(params);
    const {
      dict
    } = params;
    this.data.annotationType = _util.AnnotationType.POPUP;
    let parentItem = dict.get("Parent");
    if (!parentItem) {
      (0, _util.warn)("Popup annotation has a missing or invalid parent annotation.");
      return;
    }
    const parentSubtype = parentItem.get("Subtype");
    this.data.parentType = parentSubtype instanceof _primitives.Name ? parentSubtype.name : null;
    const rawParent = dict.getRaw("Parent");
    this.data.parentId = rawParent instanceof _primitives.Ref ? rawParent.toString() : null;
    const parentRect = parentItem.getArray("Rect");
    if (Array.isArray(parentRect) && parentRect.length === 4) {
      this.data.parentRect = _util.Util.normalizeRect(parentRect);
    } else {
      this.data.parentRect = [0, 0, 0, 0];
    }
    const rt = parentItem.get("RT");
    if ((0, _primitives.isName)(rt, _util.AnnotationReplyType.GROUP)) {
      parentItem = parentItem.get("IRT");
    }
    if (!parentItem.has("M")) {
      this.data.modificationDate = null;
    } else {
      this.setModificationDate(parentItem.get("M"));
      this.data.modificationDate = this.modificationDate;
    }
    if (!parentItem.has("C")) {
      this.data.color = null;
    } else {
      this.setColor(parentItem.getArray("C"));
      this.data.color = this.color;
    }
    if (!this.viewable) {
      const parentFlags = parentItem.get("F");
      if (this._isViewable(parentFlags)) {
        this.setFlags(parentFlags);
      }
    }
    this.setTitle(parentItem.get("T"));
    this.data.titleObj = this._title;
    this.setContents(parentItem.get("Contents"));
    this.data.contentsObj = this._contents;
    if (parentItem.has("RC")) {
      this.data.richText = _factory.XFAFactory.getRichTextAsHtml(parentItem.get("RC"));
    }
  }
}
exports.PopupAnnotation = PopupAnnotation;
class FreeTextAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.FREETEXT;
    this.setDefaultAppearance(params);
    if (!this.appearance && this._isOffscreenCanvasSupported) {
      const fakeUnicodeFont = new _default_appearance.FakeUnicodeFont(xref, "sans-serif");
      const fontData = this.data.defaultAppearanceData;
      this.appearance = fakeUnicodeFont.createAppearance(this._contents.str, this.rectangle, this.rotation, fontData.fontSize || 10, fontData.fontColor);
      this._streams.push(this.appearance, _default_appearance.FakeUnicodeFont.toUnicodeStream);
    } else if (!this._isOffscreenCanvasSupported) {
      (0, _util.warn)("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.");
    }
  }
  get hasTextContent() {
    return !!this.appearance;
  }
  static createNewDict(annotation, xref, {
    apRef,
    ap
  }) {
    const {
      color,
      fontSize,
      rect,
      rotation,
      user,
      value
    } = annotation;
    const freetext = new _primitives.Dict(xref);
    freetext.set("Type", _primitives.Name.get("Annot"));
    freetext.set("Subtype", _primitives.Name.get("FreeText"));
    freetext.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
    freetext.set("Rect", rect);
    const da = `/Helv ${fontSize} Tf ${(0, _default_appearance.getPdfColor)(color, true)}`;
    freetext.set("DA", da);
    freetext.set("Contents", (0, _core_utils.isAscii)(value) ? value : (0, _core_utils.stringToUTF16String)(value, true));
    freetext.set("F", 4);
    freetext.set("Border", [0, 0, 0]);
    freetext.set("Rotate", rotation);
    if (user) {
      freetext.set("T", (0, _core_utils.isAscii)(user) ? user : (0, _core_utils.stringToUTF16String)(user, true));
    }
    if (apRef || ap) {
      const n = new _primitives.Dict(xref);
      freetext.set("AP", n);
      if (apRef) {
        n.set("N", apRef);
      } else {
        n.set("N", ap);
      }
    }
    return freetext;
  }
  static async createNewAppearanceStream(annotation, xref, params) {
    const {
      baseFontRef,
      evaluator,
      task
    } = params;
    const {
      color,
      fontSize,
      rect,
      rotation,
      value
    } = annotation;
    const resources = new _primitives.Dict(xref);
    const font = new _primitives.Dict(xref);
    if (baseFontRef) {
      font.set("Helv", baseFontRef);
    } else {
      const baseFont = new _primitives.Dict(xref);
      baseFont.set("BaseFont", _primitives.Name.get("Helvetica"));
      baseFont.set("Type", _primitives.Name.get("Font"));
      baseFont.set("Subtype", _primitives.Name.get("Type1"));
      baseFont.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
      font.set("Helv", baseFont);
    }
    resources.set("Font", font);
    const helv = await WidgetAnnotation._getFontData(evaluator, task, {
      fontName: "Helvetica",
      fontSize
    }, resources);
    const [x1, y1, x2, y2] = rect;
    let w = x2 - x1;
    let h = y2 - y1;
    if (rotation % 180 !== 0) {
      [w, h] = [h, w];
    }
    const lines = value.split("\n");
    const scale = fontSize / 1000;
    let totalWidth = -Infinity;
    const encodedLines = [];
    for (let line of lines) {
      const encoded = helv.encodeString(line);
      if (encoded.length > 1) {
        return null;
      }
      line = encoded.join("");
      encodedLines.push(line);
      let lineWidth = 0;
      const glyphs = helv.charsToGlyphs(line);
      for (const glyph of glyphs) {
        lineWidth += glyph.width * scale;
      }
      totalWidth = Math.max(totalWidth, lineWidth);
    }
    let hscale = 1;
    if (totalWidth > w) {
      hscale = w / totalWidth;
    }
    let vscale = 1;
    const lineHeight = _util.LINE_FACTOR * fontSize;
    const lineDescent = _util.LINE_DESCENT_FACTOR * fontSize;
    const totalHeight = lineHeight * lines.length;
    if (totalHeight > h) {
      vscale = h / totalHeight;
    }
    const fscale = Math.min(hscale, vscale);
    const newFontSize = fontSize * fscale;
    const buffer = ["q", `0 0 ${(0, _core_utils.numberToString)(w)} ${(0, _core_utils.numberToString)(h)} re W n`, `BT`, `1 0 0 1 0 ${(0, _core_utils.numberToString)(h + lineDescent)} Tm 0 Tc ${(0, _default_appearance.getPdfColor)(color, true)}`, `/Helv ${(0, _core_utils.numberToString)(newFontSize)} Tf`];
    const vShift = (0, _core_utils.numberToString)(lineHeight);
    for (const line of encodedLines) {
      buffer.push(`0 -${vShift} Td (${(0, _core_utils.escapeString)(line)}) Tj`);
    }
    buffer.push("ET", "Q");
    const appearance = buffer.join("\n");
    const appearanceStreamDict = new _primitives.Dict(xref);
    appearanceStreamDict.set("FormType", 1);
    appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
    appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
    appearanceStreamDict.set("BBox", [0, 0, w, h]);
    appearanceStreamDict.set("Length", appearance.length);
    appearanceStreamDict.set("Resources", resources);
    if (rotation) {
      const matrix = (0, _core_utils.getRotationMatrix)(rotation, w, h);
      appearanceStreamDict.set("Matrix", matrix);
    }
    const ap = new _stream.StringStream(appearance);
    ap.dict = appearanceStreamDict;
    return ap;
  }
}
class LineAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.LINE;
    const lineCoordinates = dict.getArray("L");
    this.data.lineCoordinates = _util.Util.normalizeRect(lineCoordinates);
    this.setLineEndings(dict.getArray("LE"));
    this.data.lineEndings = this.lineEndings;
    if (!this.appearance) {
      const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
      const strokeAlpha = dict.get("CA");
      const interiorColor = getRgbColor(dict.getArray("IC"), null);
      const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
      const fillAlpha = fillColor ? strokeAlpha : null;
      const borderWidth = this.borderStyle.width || 1,
        borderAdjust = 2 * borderWidth;
      const bbox = [this.data.lineCoordinates[0] - borderAdjust, this.data.lineCoordinates[1] - borderAdjust, this.data.lineCoordinates[2] + borderAdjust, this.data.lineCoordinates[3] + borderAdjust];
      if (!_util.Util.intersect(this.rectangle, bbox)) {
        this.rectangle = bbox;
      }
      this._setDefaultAppearance({
        xref,
        extra: `${borderWidth} w`,
        strokeColor,
        fillColor,
        strokeAlpha,
        fillAlpha,
        pointsCallback: (buffer, points) => {
          buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`, `${lineCoordinates[2]} ${lineCoordinates[3]} l`, "S");
          return [points[0].x - borderWidth, points[1].x + borderWidth, points[3].y - borderWidth, points[1].y + borderWidth];
        }
      });
    }
  }
}
class SquareAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.SQUARE;
    if (!this.appearance) {
      const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
      const strokeAlpha = dict.get("CA");
      const interiorColor = getRgbColor(dict.getArray("IC"), null);
      const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
      const fillAlpha = fillColor ? strokeAlpha : null;
      if (this.borderStyle.width === 0 && !fillColor) {
        return;
      }
      this._setDefaultAppearance({
        xref,
        extra: `${this.borderStyle.width} w`,
        strokeColor,
        fillColor,
        strokeAlpha,
        fillAlpha,
        pointsCallback: (buffer, points) => {
          const x = points[2].x + this.borderStyle.width / 2;
          const y = points[2].y + this.borderStyle.width / 2;
          const width = points[3].x - points[2].x - this.borderStyle.width;
          const height = points[1].y - points[3].y - this.borderStyle.width;
          buffer.push(`${x} ${y} ${width} ${height} re`);
          if (fillColor) {
            buffer.push("B");
          } else {
            buffer.push("S");
          }
          return [points[0].x, points[1].x, points[3].y, points[1].y];
        }
      });
    }
  }
}
class CircleAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.CIRCLE;
    if (!this.appearance) {
      const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
      const strokeAlpha = dict.get("CA");
      const interiorColor = getRgbColor(dict.getArray("IC"), null);
      const fillColor = interiorColor ? getPdfColorArray(interiorColor) : null;
      const fillAlpha = fillColor ? strokeAlpha : null;
      if (this.borderStyle.width === 0 && !fillColor) {
        return;
      }
      const controlPointsDistance = 4 / 3 * Math.tan(Math.PI / (2 * 4));
      this._setDefaultAppearance({
        xref,
        extra: `${this.borderStyle.width} w`,
        strokeColor,
        fillColor,
        strokeAlpha,
        fillAlpha,
        pointsCallback: (buffer, points) => {
          const x0 = points[0].x + this.borderStyle.width / 2;
          const y0 = points[0].y - this.borderStyle.width / 2;
          const x1 = points[3].x - this.borderStyle.width / 2;
          const y1 = points[3].y + this.borderStyle.width / 2;
          const xMid = x0 + (x1 - x0) / 2;
          const yMid = y0 + (y1 - y0) / 2;
          const xOffset = (x1 - x0) / 2 * controlPointsDistance;
          const yOffset = (y1 - y0) / 2 * controlPointsDistance;
          buffer.push(`${xMid} ${y1} m`, `${xMid + xOffset} ${y1} ${x1} ${yMid + yOffset} ${x1} ${yMid} c`, `${x1} ${yMid - yOffset} ${xMid + xOffset} ${y0} ${xMid} ${y0} c`, `${xMid - xOffset} ${y0} ${x0} ${yMid - yOffset} ${x0} ${yMid} c`, `${x0} ${yMid + yOffset} ${xMid - xOffset} ${y1} ${xMid} ${y1} c`, "h");
          if (fillColor) {
            buffer.push("B");
          } else {
            buffer.push("S");
          }
          return [points[0].x, points[1].x, points[3].y, points[1].y];
        }
      });
    }
  }
}
class PolylineAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.POLYLINE;
    this.data.vertices = [];
    if (!(this instanceof PolygonAnnotation)) {
      this.setLineEndings(dict.getArray("LE"));
      this.data.lineEndings = this.lineEndings;
    }
    const rawVertices = dict.getArray("Vertices");
    if (!Array.isArray(rawVertices)) {
      return;
    }
    for (let i = 0, ii = rawVertices.length; i < ii; i += 2) {
      this.data.vertices.push({
        x: rawVertices[i],
        y: rawVertices[i + 1]
      });
    }
    if (!this.appearance) {
      const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
      const strokeAlpha = dict.get("CA");
      const borderWidth = this.borderStyle.width || 1,
        borderAdjust = 2 * borderWidth;
      const bbox = [Infinity, Infinity, -Infinity, -Infinity];
      for (const vertex of this.data.vertices) {
        bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
        bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
        bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
        bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
      }
      if (!_util.Util.intersect(this.rectangle, bbox)) {
        this.rectangle = bbox;
      }
      this._setDefaultAppearance({
        xref,
        extra: `${borderWidth} w`,
        strokeColor,
        strokeAlpha,
        pointsCallback: (buffer, points) => {
          const vertices = this.data.vertices;
          for (let i = 0, ii = vertices.length; i < ii; i++) {
            buffer.push(`${vertices[i].x} ${vertices[i].y} ${i === 0 ? "m" : "l"}`);
          }
          buffer.push("S");
          return [points[0].x, points[1].x, points[3].y, points[1].y];
        }
      });
    }
  }
}
class PolygonAnnotation extends PolylineAnnotation {
  constructor(params) {
    super(params);
    this.data.annotationType = _util.AnnotationType.POLYGON;
  }
}
class CaretAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    this.data.annotationType = _util.AnnotationType.CARET;
  }
}
class InkAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.INK;
    this.data.inkLists = [];
    const rawInkLists = dict.getArray("InkList");
    if (!Array.isArray(rawInkLists)) {
      return;
    }
    for (let i = 0, ii = rawInkLists.length; i < ii; ++i) {
      this.data.inkLists.push([]);
      for (let j = 0, jj = rawInkLists[i].length; j < jj; j += 2) {
        this.data.inkLists[i].push({
          x: xref.fetchIfRef(rawInkLists[i][j]),
          y: xref.fetchIfRef(rawInkLists[i][j + 1])
        });
      }
    }
    if (!this.appearance) {
      const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
      const strokeAlpha = dict.get("CA");
      const borderWidth = this.borderStyle.width || 1,
        borderAdjust = 2 * borderWidth;
      const bbox = [Infinity, Infinity, -Infinity, -Infinity];
      for (const inkLists of this.data.inkLists) {
        for (const vertex of inkLists) {
          bbox[0] = Math.min(bbox[0], vertex.x - borderAdjust);
          bbox[1] = Math.min(bbox[1], vertex.y - borderAdjust);
          bbox[2] = Math.max(bbox[2], vertex.x + borderAdjust);
          bbox[3] = Math.max(bbox[3], vertex.y + borderAdjust);
        }
      }
      if (!_util.Util.intersect(this.rectangle, bbox)) {
        this.rectangle = bbox;
      }
      this._setDefaultAppearance({
        xref,
        extra: `${borderWidth} w`,
        strokeColor,
        strokeAlpha,
        pointsCallback: (buffer, points) => {
          for (const inkList of this.data.inkLists) {
            for (let i = 0, ii = inkList.length; i < ii; i++) {
              buffer.push(`${inkList[i].x} ${inkList[i].y} ${i === 0 ? "m" : "l"}`);
            }
            buffer.push("S");
          }
          return [points[0].x, points[1].x, points[3].y, points[1].y];
        }
      });
    }
  }
  static createNewDict(annotation, xref, {
    apRef,
    ap
  }) {
    const {
      paths,
      rect,
      rotation
    } = annotation;
    const ink = new _primitives.Dict(xref);
    ink.set("Type", _primitives.Name.get("Annot"));
    ink.set("Subtype", _primitives.Name.get("Ink"));
    ink.set("CreationDate", `D:${(0, _util.getModificationDate)()}`);
    ink.set("Rect", rect);
    ink.set("InkList", paths.map(p => p.points));
    ink.set("F", 4);
    ink.set("Border", [0, 0, 0]);
    ink.set("Rotate", rotation);
    const n = new _primitives.Dict(xref);
    ink.set("AP", n);
    if (apRef) {
      n.set("N", apRef);
    } else {
      n.set("N", ap);
    }
    return ink;
  }
  static async createNewAppearanceStream(annotation, xref, params) {
    const {
      color,
      rect,
      rotation,
      paths,
      thickness,
      opacity
    } = annotation;
    const [x1, y1, x2, y2] = rect;
    let w = x2 - x1;
    let h = y2 - y1;
    if (rotation % 180 !== 0) {
      [w, h] = [h, w];
    }
    const appearanceBuffer = [`${thickness} w 1 J 1 j`, `${(0, _default_appearance.getPdfColor)(color, false)}`];
    if (opacity !== 1) {
      appearanceBuffer.push("/R0 gs");
    }
    const buffer = [];
    for (const {
      bezier
    } of paths) {
      buffer.length = 0;
      buffer.push(`${(0, _core_utils.numberToString)(bezier[0])} ${(0, _core_utils.numberToString)(bezier[1])} m`);
      for (let i = 2, ii = bezier.length; i < ii; i += 6) {
        const curve = bezier.slice(i, i + 6).map(_core_utils.numberToString).join(" ");
        buffer.push(`${curve} c`);
      }
      buffer.push("S");
      appearanceBuffer.push(buffer.join("\n"));
    }
    const appearance = appearanceBuffer.join("\n");
    const appearanceStreamDict = new _primitives.Dict(xref);
    appearanceStreamDict.set("FormType", 1);
    appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
    appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
    appearanceStreamDict.set("BBox", [0, 0, w, h]);
    appearanceStreamDict.set("Length", appearance.length);
    if (rotation) {
      const matrix = (0, _core_utils.getRotationMatrix)(rotation, w, h);
      appearanceStreamDict.set("Matrix", matrix);
    }
    if (opacity !== 1) {
      const resources = new _primitives.Dict(xref);
      const extGState = new _primitives.Dict(xref);
      const r0 = new _primitives.Dict(xref);
      r0.set("CA", opacity);
      r0.set("Type", _primitives.Name.get("ExtGState"));
      extGState.set("R0", r0);
      resources.set("ExtGState", extGState);
      appearanceStreamDict.set("Resources", resources);
    }
    const ap = new _stream.StringStream(appearance);
    ap.dict = appearanceStreamDict;
    return ap;
  }
}
class HighlightAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
    const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
    if (quadPoints) {
      const resources = this.appearance && this.appearance.dict.get("Resources");
      if (!this.appearance || !(resources && resources.has("ExtGState"))) {
        if (this.appearance) {
          (0, _util.warn)("HighlightAnnotation - ignoring built-in appearance stream.");
        }
        const fillColor = this.color ? getPdfColorArray(this.color) : [1, 1, 0];
        const fillAlpha = dict.get("CA");
        this._setDefaultAppearance({
          xref,
          fillColor,
          blendMode: "Multiply",
          fillAlpha,
          pointsCallback: (buffer, points) => {
            buffer.push(`${points[0].x} ${points[0].y} m`, `${points[1].x} ${points[1].y} l`, `${points[3].x} ${points[3].y} l`, `${points[2].x} ${points[2].y} l`, "f");
            return [points[0].x, points[1].x, points[3].y, points[1].y];
          }
        });
      }
    } else {
      this.data.hasPopup = false;
    }
  }
}
class UnderlineAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.UNDERLINE;
    const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
    if (quadPoints) {
      if (!this.appearance) {
        const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
        const strokeAlpha = dict.get("CA");
        this._setDefaultAppearance({
          xref,
          extra: "[] 0 d 1 w",
          strokeColor,
          strokeAlpha,
          pointsCallback: (buffer, points) => {
            buffer.push(`${points[2].x} ${points[2].y} m`, `${points[3].x} ${points[3].y} l`, "S");
            return [points[0].x, points[1].x, points[3].y, points[1].y];
          }
        });
      }
    } else {
      this.data.hasPopup = false;
    }
  }
}
class SquigglyAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.SQUIGGLY;
    const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
    if (quadPoints) {
      if (!this.appearance) {
        const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
        const strokeAlpha = dict.get("CA");
        this._setDefaultAppearance({
          xref,
          extra: "[] 0 d 1 w",
          strokeColor,
          strokeAlpha,
          pointsCallback: (buffer, points) => {
            const dy = (points[0].y - points[2].y) / 6;
            let shift = dy;
            let x = points[2].x;
            const y = points[2].y;
            const xEnd = points[3].x;
            buffer.push(`${x} ${y + shift} m`);
            do {
              x += 2;
              shift = shift === 0 ? dy : 0;
              buffer.push(`${x} ${y + shift} l`);
            } while (x < xEnd);
            buffer.push("S");
            return [points[2].x, xEnd, y - 2 * dy, y + 2 * dy];
          }
        });
      }
    } else {
      this.data.hasPopup = false;
    }
  }
}
class StrikeOutAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    this.data.annotationType = _util.AnnotationType.STRIKEOUT;
    const quadPoints = this.data.quadPoints = getQuadPoints(dict, null);
    if (quadPoints) {
      if (!this.appearance) {
        const strokeColor = this.color ? getPdfColorArray(this.color) : [0, 0, 0];
        const strokeAlpha = dict.get("CA");
        this._setDefaultAppearance({
          xref,
          extra: "[] 0 d 1 w",
          strokeColor,
          strokeAlpha,
          pointsCallback: (buffer, points) => {
            buffer.push(`${(points[0].x + points[2].x) / 2} ` + `${(points[0].y + points[2].y) / 2} m`, `${(points[1].x + points[3].x) / 2} ` + `${(points[1].y + points[3].y) / 2} l`, "S");
            return [points[0].x, points[1].x, points[3].y, points[1].y];
          }
        });
      }
    } else {
      this.data.hasPopup = false;
    }
  }
}
class StampAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    this.data.annotationType = _util.AnnotationType.STAMP;
  }
}
class FileAttachmentAnnotation extends MarkupAnnotation {
  constructor(params) {
    super(params);
    const {
      dict,
      xref
    } = params;
    const file = new _file_spec.FileSpec(dict.get("FS"), xref);
    this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
    this.data.file = file.serializable;
    const name = dict.get("Name");
    this.data.name = name instanceof _primitives.Name ? (0, _util.stringToPDFString)(name.name) : "PushPin";
  }
}

/***/ }),
/* 11 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FakeUnicodeFont = void 0;
exports.createDefaultAppearance = createDefaultAppearance;
exports.getPdfColor = getPdfColor;
exports.parseDefaultAppearance = parseDefaultAppearance;
var _primitives = __w_pdfjs_require__(3);
var _core_utils = __w_pdfjs_require__(4);
var _util = __w_pdfjs_require__(2);
var _colorspace = __w_pdfjs_require__(12);
var _evaluator = __w_pdfjs_require__(13);
var _stream = __w_pdfjs_require__(8);
class DefaultAppearanceEvaluator extends _evaluator.EvaluatorPreprocessor {
  constructor(str) {
    super(new _stream.StringStream(str));
  }
  parse() {
    const operation = {
      fn: 0,
      args: []
    };
    const result = {
      fontSize: 0,
      fontName: "",
      fontColor: new Uint8ClampedArray(3)
    };
    try {
      while (true) {
        operation.args.length = 0;
        if (!this.read(operation)) {
          break;
        }
        if (this.savedStatesDepth !== 0) {
          continue;
        }
        const {
          fn,
          args
        } = operation;
        switch (fn | 0) {
          case _util.OPS.setFont:
            const [fontName, fontSize] = args;
            if (fontName instanceof _primitives.Name) {
              result.fontName = fontName.name;
            }
            if (typeof fontSize === "number" && fontSize > 0) {
              result.fontSize = fontSize;
            }
            break;
          case _util.OPS.setFillRGBColor:
            _colorspace.ColorSpace.singletons.rgb.getRgbItem(args, 0, result.fontColor, 0);
            break;
          case _util.OPS.setFillGray:
            _colorspace.ColorSpace.singletons.gray.getRgbItem(args, 0, result.fontColor, 0);
            break;
          case _util.OPS.setFillColorSpace:
            _colorspace.ColorSpace.singletons.cmyk.getRgbItem(args, 0, result.fontColor, 0);
            break;
        }
      }
    } catch (reason) {
      (0, _util.warn)(`parseDefaultAppearance - ignoring errors: "${reason}".`);
    }
    return result;
  }
}
function parseDefaultAppearance(str) {
  return new DefaultAppearanceEvaluator(str).parse();
}
function getPdfColor(color, isFill) {
  if (color[0] === color[1] && color[1] === color[2]) {
    const gray = color[0] / 255;
    return `${(0, _core_utils.numberToString)(gray)} ${isFill ? "g" : "G"}`;
  }
  return Array.from(color, c => (0, _core_utils.numberToString)(c / 255)).join(" ") + ` ${isFill ? "rg" : "RG"}`;
}
function createDefaultAppearance({
  fontSize,
  fontName,
  fontColor
}) {
  return `/${(0, _core_utils.escapePDFName)(fontName)} ${fontSize} Tf ${getPdfColor(fontColor, true)}`;
}
class FakeUnicodeFont {
  constructor(xref, fontFamily) {
    this.xref = xref;
    this.widths = null;
    this.firstChar = Infinity;
    this.lastChar = -Infinity;
    this.fontFamily = fontFamily;
    const canvas = new OffscreenCanvas(1, 1);
    this.ctxMeasure = canvas.getContext("2d");
    if (!FakeUnicodeFont._fontNameId) {
      FakeUnicodeFont._fontNameId = 1;
    }
    this.fontName = _primitives.Name.get(`InvalidPDFjsFont_${fontFamily}_${FakeUnicodeFont._fontNameId++}`);
  }
  get toUnicodeRef() {
    if (!FakeUnicodeFont._toUnicodeRef) {
      const toUnicode = `/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo
<< /Registry (Adobe)
/Ordering (UCS) /Supplement 0 >> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000> <FFFF>
endcodespacerange
1 beginbfrange
<0000> <FFFF> <0000>
endbfrange
endcmap CMapName currentdict /CMap defineresource pop end end`;
      const toUnicodeStream = FakeUnicodeFont.toUnicodeStream = new _stream.StringStream(toUnicode);
      const toUnicodeDict = new _primitives.Dict(this.xref);
      toUnicodeStream.dict = toUnicodeDict;
      toUnicodeDict.set("Length", toUnicode.length);
      FakeUnicodeFont._toUnicodeRef = this.xref.getNewPersistentRef(toUnicodeStream);
    }
    return FakeUnicodeFont._toUnicodeRef;
  }
  get fontDescriptorRef() {
    if (!FakeUnicodeFont._fontDescriptorRef) {
      const fontDescriptor = new _primitives.Dict(this.xref);
      fontDescriptor.set("Type", _primitives.Name.get("FontDescriptor"));
      fontDescriptor.set("FontName", this.fontName);
      fontDescriptor.set("FontFamily", "MyriadPro Regular");
      fontDescriptor.set("FontBBox", [0, 0, 0, 0]);
      fontDescriptor.set("FontStretch", _primitives.Name.get("Normal"));
      fontDescriptor.set("FontWeight", 400);
      fontDescriptor.set("ItalicAngle", 0);
      FakeUnicodeFont._fontDescriptorRef = this.xref.getNewPersistentRef(fontDescriptor);
    }
    return FakeUnicodeFont._fontDescriptorRef;
  }
  get descendantFontRef() {
    const descendantFont = new _primitives.Dict(this.xref);
    descendantFont.set("BaseFont", this.fontName);
    descendantFont.set("Type", _primitives.Name.get("Font"));
    descendantFont.set("Subtype", _primitives.Name.get("CIDFontType0"));
    descendantFont.set("CIDToGIDMap", _primitives.Name.get("Identity"));
    descendantFont.set("FirstChar", this.firstChar);
    descendantFont.set("LastChar", this.lastChar);
    descendantFont.set("FontDescriptor", this.fontDescriptorRef);
    descendantFont.set("DW", 1000);
    const widths = [];
    const chars = [...this.widths.entries()].sort();
    let currentChar = null;
    let currentWidths = null;
    for (const [char, width] of chars) {
      if (!currentChar) {
        currentChar = char;
        currentWidths = [width];
        continue;
      }
      if (char === currentChar + currentWidths.length) {
        currentWidths.push(width);
      } else {
        widths.push(currentChar, currentWidths);
        currentChar = char;
        currentWidths = [width];
      }
    }
    if (currentChar) {
      widths.push(currentChar, currentWidths);
    }
    descendantFont.set("W", widths);
    const cidSystemInfo = new _primitives.Dict(this.xref);
    cidSystemInfo.set("Ordering", "Identity");
    cidSystemInfo.set("Registry", "Adobe");
    cidSystemInfo.set("Supplement", 0);
    descendantFont.set("CIDSystemInfo", cidSystemInfo);
    return this.xref.getNewPersistentRef(descendantFont);
  }
  get baseFontRef() {
    const baseFont = new _primitives.Dict(this.xref);
    baseFont.set("BaseFont", this.fontName);
    baseFont.set("Type", _primitives.Name.get("Font"));
    baseFont.set("Subtype", _primitives.Name.get("Type0"));
    baseFont.set("Encoding", _primitives.Name.get("Identity-H"));
    baseFont.set("DescendantFonts", [this.descendantFontRef]);
    baseFont.set("ToUnicode", this.toUnicodeRef);
    return this.xref.getNewPersistentRef(baseFont);
  }
  get resources() {
    const resources = new _primitives.Dict(this.xref);
    const font = new _primitives.Dict(this.xref);
    font.set(this.fontName.name, this.baseFontRef);
    resources.set("Font", font);
    return resources;
  }
  _createContext() {
    this.widths = new Map();
    this.ctxMeasure.font = `1000px ${this.fontFamily}`;
    return this.ctxMeasure;
  }
  createFontResources(text) {
    const ctx = this._createContext();
    for (const line of text.split(/\r\n?|\n/)) {
      for (const char of line.split("")) {
        const code = char.charCodeAt(0);
        if (this.widths.has(code)) {
          continue;
        }
        const metrics = ctx.measureText(char);
        const width = Math.ceil(metrics.width);
        this.widths.set(code, width);
        this.firstChar = Math.min(code, this.firstChar);
        this.lastChar = Math.max(code, this.lastChar);
      }
    }
    return this.resources;
  }
  createAppearance(text, rect, rotation, fontSize, bgColor) {
    const ctx = this._createContext();
    const lines = [];
    let maxWidth = -Infinity;
    for (const line of text.split(/\r\n?|\n/)) {
      lines.push(line);
      const lineWidth = ctx.measureText(line).width;
      maxWidth = Math.max(maxWidth, lineWidth);
      for (const char of line.split("")) {
        const code = char.charCodeAt(0);
        let width = this.widths.get(code);
        if (width === undefined) {
          const metrics = ctx.measureText(char);
          width = Math.ceil(metrics.width);
          this.widths.set(code, width);
          this.firstChar = Math.min(code, this.firstChar);
          this.lastChar = Math.max(code, this.lastChar);
        }
      }
    }
    maxWidth *= fontSize / 1000;
    const [x1, y1, x2, y2] = rect;
    let w = x2 - x1;
    let h = y2 - y1;
    if (rotation % 180 !== 0) {
      [w, h] = [h, w];
    }
    let hscale = 1;
    if (maxWidth > w) {
      hscale = w / maxWidth;
    }
    let vscale = 1;
    const lineHeight = _util.LINE_FACTOR * fontSize;
    const lineDescent = _util.LINE_DESCENT_FACTOR * fontSize;
    const maxHeight = lineHeight * lines.length;
    if (maxHeight > h) {
      vscale = h / maxHeight;
    }
    const fscale = Math.min(hscale, vscale);
    const newFontSize = fontSize * fscale;
    const buffer = ["q", `0 0 ${(0, _core_utils.numberToString)(w)} ${(0, _core_utils.numberToString)(h)} re W n`, `BT`, `1 0 0 1 0 ${(0, _core_utils.numberToString)(h + lineDescent)} Tm 0 Tc ${getPdfColor(bgColor, true)}`, `/${this.fontName.name} ${(0, _core_utils.numberToString)(newFontSize)} Tf`];
    const vShift = (0, _core_utils.numberToString)(lineHeight);
    for (const line of lines) {
      buffer.push(`0 -${vShift} Td <${(0, _core_utils.stringToUTF16HexString)(line)}> Tj`);
    }
    buffer.push("ET", "Q");
    const appearance = buffer.join("\n");
    const appearanceStreamDict = new _primitives.Dict(this.xref);
    appearanceStreamDict.set("Subtype", _primitives.Name.get("Form"));
    appearanceStreamDict.set("Type", _primitives.Name.get("XObject"));
    appearanceStreamDict.set("BBox", [0, 0, w, h]);
    appearanceStreamDict.set("Length", appearance.length);
    appearanceStreamDict.set("Resources", this.resources);
    if (rotation) {
      const matrix = (0, _core_utils.getRotationMatrix)(rotation, w, h);
      appearanceStreamDict.set("Matrix", matrix);
    }
    const ap = new _stream.StringStream(appearance);
    ap.dict = appearanceStreamDict;
    return ap;
  }
}
exports.FakeUnicodeFont = FakeUnicodeFont;

/***/ }),
/* 12 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ColorSpace = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _base_stream = __w_pdfjs_require__(5);
var _core_utils = __w_pdfjs_require__(4);
function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {
  const COMPONENTS = 3;
  alpha01 = alpha01 !== 1 ? 0 : alpha01;
  const xRatio = w1 / w2;
  const yRatio = h1 / h2;
  let newIndex = 0,
    oldIndex;
  const xScaled = new Uint16Array(w2);
  const w1Scanline = w1 * COMPONENTS;
  for (let i = 0; i < w2; i++) {
    xScaled[i] = Math.floor(i * xRatio) * COMPONENTS;
  }
  for (let i = 0; i < h2; i++) {
    const py = Math.floor(i * yRatio) * w1Scanline;
    for (let j = 0; j < w2; j++) {
      oldIndex = py + xScaled[j];
      dest[newIndex++] = src[oldIndex++];
      dest[newIndex++] = src[oldIndex++];
      dest[newIndex++] = src[oldIndex++];
      newIndex += alpha01;
    }
  }
}
class ColorSpace {
  constructor(name, numComps) {
    if (this.constructor === ColorSpace) {
      (0, _util.unreachable)("Cannot initialize ColorSpace.");
    }
    this.name = name;
    this.numComps = numComps;
  }
  getRgb(src, srcOffset) {
    const rgb = new Uint8ClampedArray(3);
    this.getRgbItem(src, srcOffset, rgb, 0);
    return rgb;
  }
  getRgbItem(src, srcOffset, dest, destOffset) {
    (0, _util.unreachable)("Should not call ColorSpace.getRgbItem");
  }
  getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
    (0, _util.unreachable)("Should not call ColorSpace.getRgbBuffer");
  }
  getOutputLength(inputLength, alpha01) {
    (0, _util.unreachable)("Should not call ColorSpace.getOutputLength");
  }
  isPassthrough(bits) {
    return false;
  }
  isDefaultDecode(decodeMap, bpc) {
    return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
  }
  fillRgb(dest, originalWidth, originalHeight, width, height, actualHeight, bpc, comps, alpha01) {
    const count = originalWidth * originalHeight;
    let rgbBuf = null;
    const numComponentColors = 1 << bpc;
    const needsResizing = originalHeight !== height || originalWidth !== width;
    if (this.isPassthrough(bpc)) {
      rgbBuf = comps;
    } else if (this.numComps === 1 && count > numComponentColors && this.name !== "DeviceGray" && this.name !== "DeviceRGB") {
      const allColors = bpc <= 8 ? new Uint8Array(numComponentColors) : new Uint16Array(numComponentColors);
      for (let i = 0; i < numComponentColors; i++) {
        allColors[i] = i;
      }
      const colorMap = new Uint8ClampedArray(numComponentColors * 3);
      this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc, 0);
      if (!needsResizing) {
        let destPos = 0;
        for (let i = 0; i < count; ++i) {
          const key = comps[i] * 3;
          dest[destPos++] = colorMap[key];
          dest[destPos++] = colorMap[key + 1];
          dest[destPos++] = colorMap[key + 2];
          destPos += alpha01;
        }
      } else {
        rgbBuf = new Uint8Array(count * 3);
        let rgbPos = 0;
        for (let i = 0; i < count; ++i) {
          const key = comps[i] * 3;
          rgbBuf[rgbPos++] = colorMap[key];
          rgbBuf[rgbPos++] = colorMap[key + 1];
          rgbBuf[rgbPos++] = colorMap[key + 2];
        }
      }
    } else {
      if (!needsResizing) {
        this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc, alpha01);
      } else {
        rgbBuf = new Uint8ClampedArray(count * 3);
        this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc, 0);
      }
    }
    if (rgbBuf) {
      if (needsResizing) {
        resizeRgbImage(rgbBuf, dest, originalWidth, originalHeight, width, height, alpha01);
      } else {
        let destPos = 0,
          rgbPos = 0;
        for (let i = 0, ii = width * actualHeight; i < ii; i++) {
          dest[destPos++] = rgbBuf[rgbPos++];
          dest[destPos++] = rgbBuf[rgbPos++];
          dest[destPos++] = rgbBuf[rgbPos++];
          destPos += alpha01;
        }
      }
    }
  }
  get usesZeroToOneRange() {
    return (0, _util.shadow)(this, "usesZeroToOneRange", true);
  }
  static _cache(cacheKey, xref, localColorSpaceCache, parsedColorSpace) {
    if (!localColorSpaceCache) {
      throw new Error('ColorSpace._cache - expected "localColorSpaceCache" argument.');
    }
    if (!parsedColorSpace) {
      throw new Error('ColorSpace._cache - expected "parsedColorSpace" argument.');
    }
    let csName, csRef;
    if (cacheKey instanceof _primitives.Ref) {
      csRef = cacheKey;
      cacheKey = xref.fetch(cacheKey);
    }
    if (cacheKey instanceof _primitives.Name) {
      csName = cacheKey.name;
    }
    if (csName || csRef) {
      localColorSpaceCache.set(csName, csRef, parsedColorSpace);
    }
  }
  static getCached(cacheKey, xref, localColorSpaceCache) {
    if (!localColorSpaceCache) {
      throw new Error('ColorSpace.getCached - expected "localColorSpaceCache" argument.');
    }
    if (cacheKey instanceof _primitives.Ref) {
      const localColorSpace = localColorSpaceCache.getByRef(cacheKey);
      if (localColorSpace) {
        return localColorSpace;
      }
      try {
        cacheKey = xref.fetch(cacheKey);
      } catch (ex) {
        if (ex instanceof _core_utils.MissingDataException) {
          throw ex;
        }
      }
    }
    if (cacheKey instanceof _primitives.Name) {
      const localColorSpace = localColorSpaceCache.getByName(cacheKey.name);
      if (localColorSpace) {
        return localColorSpace;
      }
    }
    return null;
  }
  static async parseAsync({
    cs,
    xref,
    resources = null,
    pdfFunctionFactory,
    localColorSpaceCache
  }) {
    const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
    this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
    return parsedColorSpace;
  }
  static parse({
    cs,
    xref,
    resources = null,
    pdfFunctionFactory,
    localColorSpaceCache
  }) {
    const cachedColorSpace = this.getCached(cs, xref, localColorSpaceCache);
    if (cachedColorSpace) {
      return cachedColorSpace;
    }
    const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
    this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
    return parsedColorSpace;
  }
  static _parse(cs, xref, resources = null, pdfFunctionFactory) {
    cs = xref.fetchIfRef(cs);
    if (cs instanceof _primitives.Name) {
      switch (cs.name) {
        case "G":
        case "DeviceGray":
          return this.singletons.gray;
        case "RGB":
        case "DeviceRGB":
          return this.singletons.rgb;
        case "CMYK":
        case "DeviceCMYK":
          return this.singletons.cmyk;
        case "Pattern":
          return new PatternCS(null);
        default:
          if (resources instanceof _primitives.Dict) {
            const colorSpaces = resources.get("ColorSpace");
            if (colorSpaces instanceof _primitives.Dict) {
              const resourcesCS = colorSpaces.get(cs.name);
              if (resourcesCS) {
                if (resourcesCS instanceof _primitives.Name) {
                  return this._parse(resourcesCS, xref, resources, pdfFunctionFactory);
                }
                cs = resourcesCS;
                break;
              }
            }
          }
          throw new _util.FormatError(`Unrecognized ColorSpace: ${cs.name}`);
      }
    }
    if (Array.isArray(cs)) {
      const mode = xref.fetchIfRef(cs[0]).name;
      let params, numComps, baseCS, whitePoint, blackPoint, gamma;
      switch (mode) {
        case "G":
        case "DeviceGray":
          return this.singletons.gray;
        case "RGB":
        case "DeviceRGB":
          return this.singletons.rgb;
        case "CMYK":
        case "DeviceCMYK":
          return this.singletons.cmyk;
        case "CalGray":
          params = xref.fetchIfRef(cs[1]);
          whitePoint = params.getArray("WhitePoint");
          blackPoint = params.getArray("BlackPoint");
          gamma = params.get("Gamma");
          return new CalGrayCS(whitePoint, blackPoint, gamma);
        case "CalRGB":
          params = xref.fetchIfRef(cs[1]);
          whitePoint = params.getArray("WhitePoint");
          blackPoint = params.getArray("BlackPoint");
          gamma = params.getArray("Gamma");
          const matrix = params.getArray("Matrix");
          return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
        case "ICCBased":
          const stream = xref.fetchIfRef(cs[1]);
          const dict = stream.dict;
          numComps = dict.get("N");
          const alt = dict.get("Alternate");
          if (alt) {
            const altCS = this._parse(alt, xref, resources, pdfFunctionFactory);
            if (altCS.numComps === numComps) {
              return altCS;
            }
            (0, _util.warn)("ICCBased color space: Ignoring incorrect /Alternate entry.");
          }
          if (numComps === 1) {
            return this.singletons.gray;
          } else if (numComps === 3) {
            return this.singletons.rgb;
          } else if (numComps === 4) {
            return this.singletons.cmyk;
          }
          break;
        case "Pattern":
          baseCS = cs[1] || null;
          if (baseCS) {
            baseCS = this._parse(baseCS, xref, resources, pdfFunctionFactory);
          }
          return new PatternCS(baseCS);
        case "I":
        case "Indexed":
          baseCS = this._parse(cs[1], xref, resources, pdfFunctionFactory);
          const hiVal = xref.fetchIfRef(cs[2]) + 1;
          const lookup = xref.fetchIfRef(cs[3]);
          return new IndexedCS(baseCS, hiVal, lookup);
        case "Separation":
        case "DeviceN":
          const name = xref.fetchIfRef(cs[1]);
          numComps = Array.isArray(name) ? name.length : 1;
          baseCS = this._parse(cs[2], xref, resources, pdfFunctionFactory);
          const tintFn = pdfFunctionFactory.create(cs[3]);
          return new AlternateCS(numComps, baseCS, tintFn);
        case "Lab":
          params = xref.fetchIfRef(cs[1]);
          whitePoint = params.getArray("WhitePoint");
          blackPoint = params.getArray("BlackPoint");
          const range = params.getArray("Range");
          return new LabCS(whitePoint, blackPoint, range);
        default:
          throw new _util.FormatError(`Unimplemented ColorSpace object: ${mode}`);
      }
    }
    throw new _util.FormatError(`Unrecognized ColorSpace object: ${cs}`);
  }
  static isDefaultDecode(decode, numComps) {
    if (!Array.isArray(decode)) {
      return true;
    }
    if (numComps * 2 !== decode.length) {
      (0, _util.warn)("The decode map is not the correct length");
      return true;
    }
    for (let i = 0, ii = decode.length; i < ii; i += 2) {
      if (decode[i] !== 0 || decode[i + 1] !== 1) {
        return false;
      }
    }
    return true;
  }
  static get singletons() {
    return (0, _util.shadow)(this, "singletons", {
      get gray() {
        return (0, _util.shadow)(this, "gray", new DeviceGrayCS());
      },
      get rgb() {
        return (0, _util.shadow)(this, "rgb", new DeviceRgbCS());
      },
      get cmyk() {
        return (0, _util.shadow)(this, "cmyk", new DeviceCmykCS());
      }
    });
  }
}
exports.ColorSpace = ColorSpace;
class AlternateCS extends ColorSpace {
  constructor(numComps, base, tintFn) {
    super("Alternate", numComps);
    this.base = base;
    this.tintFn = tintFn;
    this.tmpBuf = new Float32Array(base.numComps);
  }
  getRgbItem(src, srcOffset, dest, destOffset) {
    const tmpBuf = this.tmpBuf;
    this.tintFn(src, srcOffset, tmpBuf, 0);
    this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
  }
  getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
    const tintFn = this.tintFn;
    const base = this.base;
    const scale = 1 / ((1 << bits) - 1);
    const baseNumComps = base.numComps;
    const usesZeroToOneRange = base.usesZeroToOneRange;
    const isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) && alpha01 === 0;
    let pos = isPassthrough ? destOffset : 0;
    const baseBuf = isPassthrough ? dest : new Uint8ClampedArray(baseNumComps * count);
    const numComps = this.numComps;
    const scaled = new Float32Array(numComps);
    const tinted = new Float32Array(baseNumComps);
    let i, j;
    for (i = 0; i < count; i++) {
      for (j = 0; j < numComps; j++) {
        scaled[j] = src[srcOffset++] * scale;
      }
      tintFn(scaled, 0, tinted, 0);
      if (usesZeroToOneRange) {
        for (j = 0; j < baseNumComps; j++) {
          baseBuf[pos++] = tinted[j] * 255;
        }
      } else {
        base.getRgbItem(tinted, 0, baseBuf, pos);
        pos += baseNumComps;
      }
    }
    if (!isPassthrough) {
      base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
    }
  }
  getOutputLength(inputLength, alpha01) {
    return this.base.getOutputLength(inputLength * this.base.numComps / this.numComps, alpha01);
  }
}
class PatternCS extends ColorSpace {
  constructor(baseCS) {
    super("Pattern", null);
    this.base = baseCS;
  }
  isDefaultDecode(decodeMap, bpc) {
    (0, _util.unreachable)("Should not call PatternCS.isDefaultDecode");
  }
}
class IndexedCS extends ColorSpace {
  constructor(base, highVal, lookup) {
    super("Indexed", 1);
    this.base = base;
    this.highVal = highVal;
    const length = base.numComps * highVal;
    this.lookup = new Uint8Array(length);
    if (lookup instanceof _base_stream.BaseStream) {
      const bytes = lookup.getBytes(length);
      this.lookup.set(bytes);
    } else if (typeof lookup === "string") {
      for (let i = 0; i < length; ++i) {
        this.lookup[i] = lookup.charCodeAt(i) & 0xff;
      }
    } else {
      throw new _util.FormatError(`IndexedCS - unrecognized lookup table: ${lookup}`);
    }
  }
  getRgbItem(src, srcOffset, dest, destOffset) {
    const numComps = this.base.numComps;
    const start = src[srcOffset] * numComps;
    this.base.getRgbBuffer(this.lookup, start, 1, dest, destOffset, 8, 0);
  }
  getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
    const base = this.base;
    const numComps = base.numComps;
    const outputDelta = base.getOutputLength(numComps, alpha01);
    const lookup = this.lookup;
    for (let i = 0; i < count; ++i) {
      const lookupPos = src[srcOffset++] * numComps;
      base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
      destOffset += outputDelta;
    }
  }
  getOutputLength(inputLength, alpha01) {
    return this.base.getOutputLength(inputLength * this.base.numComps, alpha01);
  }
  isDefaultDecode(decodeMap, bpc) {
    if (!Array.isArray(decodeMap)) {
      return true;
    }
    if (decodeMap.length !== 2) {
      (0, _util.warn)("Decode map length is not correct");
      return true;
    }
    if (!Number.isInteger(bpc) || bpc < 1) {
      (0, _util.warn)("Bits per component is not correct");
      return true;
    }
    return decodeMap[0] === 0 && decodeMap[1] === (1 << bpc) - 1;
  }
}
class DeviceGrayCS extends ColorSpace {
  constructor() {
    super("DeviceGray", 1);
  }
  getRgbItem(src, srcOffset, dest, destOffset) {
    const c = src[srcOffset] * 255;
    dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
  }
  getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
    const scale = 255 / ((1 << bits) - 1);
    let j = srcOffset,
      q = destOffset;
    for (let i = 0; i < count; ++i) {
      const c = scale * src[j++];
      dest[q++] = c;
      dest[q++] = c;
      dest[q++] = c;
      q += alpha01;
    }
  }
  getOutputLength(inputLength, alpha01) {
    return inputLength * (3 + alpha01);
  }
}
class DeviceRgbCS extends ColorSpace {
  constructor() {
    super("DeviceRGB", 3);
  }
  getRgbItem(src, srcOffset, dest, destOffset) {
    dest[destOffset] = src[srcOffset] * 255;
    dest[destOffset + 1] = src[srcOffset + 1] * 255;
    dest[destOffset + 2] = src[srcOffset + 2] * 255;
  }
  getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
    if (bits === 8 && alpha01 === 0) {
      dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
      return;
    }
    const scale = 255 / ((1 << bits) - 1);
    let j = srcOffset,
      q = destOffset;
    for (let i = 0; i < count; ++i) {
      dest[q++] = scale * src[j++];
      dest[q++] = scale * src[j++];
      dest[q++] = scale * src[j++];
      q += alpha01;
    }
  }
  getOutputLength(inputLength, alpha01) {
    return inputLength * (3 + alpha01) / 3 | 0;
  }
  isPassthrough(bits) {
    return bits === 8;
  }
}
const DeviceCmykCS = function DeviceCmykCSClosure() {
  function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {
    const c = src[srcOffset] * srcScale;
    const m = src[srcOffset + 1] * srcScale;
    const y = src[srcOffset + 2] * srcScale;
    const k = src[srcOffset + 3] * srcScale;
    dest[destOffset] = 255 + c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * (1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747);
    dest[destOffset + 1] = 255 + c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578);
    dest[destOffset + 2] = 255 + c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367);
  }
  class DeviceCmykCS extends ColorSpace {
    constructor() {
      super("DeviceCMYK", 4);
    }
    getRgbItem(src, srcOffset, dest, destOffset) {
      convertToRgb(src, srcOffset, 1, dest, destOffset);
    }
    getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
      const scale = 1 / ((1 << bits) - 1);
      for (let i = 0; i < count; i++) {
        convertToRgb(src, srcOffset, scale, dest, destOffset);
        srcOffset += 4;
        destOffset += 3 + alpha01;
      }
    }
    getOutputLength(inputLength, alpha01) {
      return inputLength / 4 * (3 + alpha01) | 0;
    }
  }
  return DeviceCmykCS;
}();
const CalGrayCS = function CalGrayCSClosure() {
  function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
    const A = src[srcOffset] * scale;
    const AG = A ** cs.G;
    const L = cs.YW * AG;
    const val = Math.max(295.8 * L ** 0.3333333333333333 - 40.8, 0);
    dest[destOffset] = val;
    dest[destOffset + 1] = val;
    dest[destOffset + 2] = val;
  }
  class CalGrayCS extends ColorSpace {
    constructor(whitePoint, blackPoint, gamma) {
      super("CalGray", 1);
      if (!whitePoint) {
        throw new _util.FormatError("WhitePoint missing - required for color space CalGray");
      }
      blackPoint = blackPoint || [0, 0, 0];
      gamma = gamma || 1;
      this.XW = whitePoint[0];
      this.YW = whitePoint[1];
      this.ZW = whitePoint[2];
      this.XB = blackPoint[0];
      this.YB = blackPoint[1];
      this.ZB = blackPoint[2];
      this.G = gamma;
      if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
        throw new _util.FormatError(`Invalid WhitePoint components for ${this.name}` + ", no fallback available");
      }
      if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
        (0, _util.info)(`Invalid BlackPoint for ${this.name}, falling back to default.`);
        this.XB = this.YB = this.ZB = 0;
      }
      if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
        (0, _util.warn)(`${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ` + `ZB: ${this.ZB}, only default values are supported.`);
      }
      if (this.G < 1) {
        (0, _util.info)(`Invalid Gamma: ${this.G} for ${this.name}, ` + "falling back to default.");
        this.G = 1;
      }
    }
    getRgbItem(src, srcOffset, dest, destOffset) {
      convertToRgb(this, src, srcOffset, dest, destOffset, 1);
    }
    getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
      const scale = 1 / ((1 << bits) - 1);
      for (let i = 0; i < count; ++i) {
        convertToRgb(this, src, srcOffset, dest, destOffset, scale);
        srcOffset += 1;
        destOffset += 3 + alpha01;
      }
    }
    getOutputLength(inputLength, alpha01) {
      return inputLength * (3 + alpha01);
    }
  }
  return CalGrayCS;
}();
const CalRGBCS = function CalRGBCSClosure() {
  const BRADFORD_SCALE_MATRIX = new Float32Array([0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296]);
  const BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428, 0.9684867]);
  const SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252]);
  const FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
  const tempNormalizeMatrix = new Float32Array(3);
  const tempConvertMatrix1 = new Float32Array(3);
  const tempConvertMatrix2 = new Float32Array(3);
  const DECODE_L_CONSTANT = ((8 + 16) / 116) ** 3 / 8.0;
  function matrixProduct(a, b, result) {
    result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
    result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
  }
  function convertToFlat(sourceWhitePoint, LMS, result) {
    result[0] = LMS[0] * 1 / sourceWhitePoint[0];
    result[1] = LMS[1] * 1 / sourceWhitePoint[1];
    result[2] = LMS[2] * 1 / sourceWhitePoint[2];
  }
  function convertToD65(sourceWhitePoint, LMS, result) {
    const D65X = 0.95047;
    const D65Y = 1;
    const D65Z = 1.08883;
    result[0] = LMS[0] * D65X / sourceWhitePoint[0];
    result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
    result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
  }
  function sRGBTransferFunction(color) {
    if (color <= 0.0031308) {
      return adjustToRange(0, 1, 12.92 * color);
    }
    if (color >= 0.99554525) {
      return 1;
    }
    return adjustToRange(0, 1, (1 + 0.055) * color ** (1 / 2.4) - 0.055);
  }
  function adjustToRange(min, max, value) {
    return Math.max(min, Math.min(max, value));
  }
  function decodeL(L) {
    if (L < 0) {
      return -decodeL(-L);
    }
    if (L > 8.0) {
      return ((L + 16) / 116) ** 3;
    }
    return L * DECODE_L_CONSTANT;
  }
  function compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
    if (sourceBlackPoint[0] === 0 && sourceBlackPoint[1] === 0 && sourceBlackPoint[2] === 0) {
      result[0] = XYZ_Flat[0];
      result[1] = XYZ_Flat[1];
      result[2] = XYZ_Flat[2];
      return;
    }
    const zeroDecodeL = decodeL(0);
    const X_DST = zeroDecodeL;
    const X_SRC = decodeL(sourceBlackPoint[0]);
    const Y_DST = zeroDecodeL;
    const Y_SRC = decodeL(sourceBlackPoint[1]);
    const Z_DST = zeroDecodeL;
    const Z_SRC = decodeL(sourceBlackPoint[2]);
    const X_Scale = (1 - X_DST) / (1 - X_SRC);
    const X_Offset = 1 - X_Scale;
    const Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
    const Y_Offset = 1 - Y_Scale;
    const Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
    const Z_Offset = 1 - Z_Scale;
    result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
    result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
    result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
  }
  function normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
    if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
      result[0] = XYZ_In[0];
      result[1] = XYZ_In[1];
      result[2] = XYZ_In[2];
      return;
    }
    const LMS = result;
    matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
    const LMS_Flat = tempNormalizeMatrix;
    convertToFlat(sourceWhitePoint, LMS, LMS_Flat);
    matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
  }
  function normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
    const LMS = result;
    matrixProduct(BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
    const LMS_D65 = tempNormalizeMatrix;
    convertToD65(sourceWhitePoint, LMS, LMS_D65);
    matrixProduct(BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
  }
  function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {
    const A = adjustToRange(0, 1, src[srcOffset] * scale);
    const B = adjustToRange(0, 1, src[srcOffset + 1] * scale);
    const C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
    const AGR = A === 1 ? 1 : A ** cs.GR;
    const BGG = B === 1 ? 1 : B ** cs.GG;
    const CGB = C === 1 ? 1 : C ** cs.GB;
    const X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;
    const Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;
    const Z = cs.MZA * AGR + cs.MZB * BGG + cs.MZC * CGB;
    const XYZ = tempConvertMatrix1;
    XYZ[0] = X;
    XYZ[1] = Y;
    XYZ[2] = Z;
    const XYZ_Flat = tempConvertMatrix2;
    normalizeWhitePointToFlat(cs.whitePoint, XYZ, XYZ_Flat);
    const XYZ_Black = tempConvertMatrix1;
    compensateBlackPoint(cs.blackPoint, XYZ_Flat, XYZ_Black);
    const XYZ_D65 = tempConvertMatrix2;
    normalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
    const SRGB = tempConvertMatrix1;
    matrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
    dest[destOffset] = sRGBTransferFunction(SRGB[0]) * 255;
    dest[destOffset + 1] = sRGBTransferFunction(SRGB[1]) * 255;
    dest[destOffset + 2] = sRGBTransferFunction(SRGB[2]) * 255;
  }
  class CalRGBCS extends ColorSpace {
    constructor(whitePoint, blackPoint, gamma, matrix) {
      super("CalRGB", 3);
      if (!whitePoint) {
        throw new _util.FormatError("WhitePoint missing - required for color space CalRGB");
      }
      blackPoint = blackPoint || new Float32Array(3);
      gamma = gamma || new Float32Array([1, 1, 1]);
      matrix = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
      const XW = whitePoint[0];
      const YW = whitePoint[1];
      const ZW = whitePoint[2];
      this.whitePoint = whitePoint;
      const XB = blackPoint[0];
      const YB = blackPoint[1];
      const ZB = blackPoint[2];
      this.blackPoint = blackPoint;
      this.GR = gamma[0];
      this.GG = gamma[1];
      this.GB = gamma[2];
      this.MXA = matrix[0];
      this.MYA = matrix[1];
      this.MZA = matrix[2];
      this.MXB = matrix[3];
      this.MYB = matrix[4];
      this.MZB = matrix[5];
      this.MXC = matrix[6];
      this.MYC = matrix[7];
      this.MZC = matrix[8];
      if (XW < 0 || ZW < 0 || YW !== 1) {
        throw new _util.FormatError(`Invalid WhitePoint components for ${this.name}` + ", no fallback available");
      }
      if (XB < 0 || YB < 0 || ZB < 0) {
        (0, _util.info)(`Invalid BlackPoint for ${this.name} [${XB}, ${YB}, ${ZB}], ` + "falling back to default.");
        this.blackPoint = new Float32Array(3);
      }
      if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
        (0, _util.info)(`Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ` + `${this.name}, falling back to default.`);
        this.GR = this.GG = this.GB = 1;
      }
    }
    getRgbItem(src, srcOffset, dest, destOffset) {
      convertToRgb(this, src, srcOffset, dest, destOffset, 1);
    }
    getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
      const scale = 1 / ((1 << bits) - 1);
      for (let i = 0; i < count; ++i) {
        convertToRgb(this, src, srcOffset, dest, destOffset, scale);
        srcOffset += 3;
        destOffset += 3 + alpha01;
      }
    }
    getOutputLength(inputLength, alpha01) {
      return inputLength * (3 + alpha01) / 3 | 0;
    }
  }
  return CalRGBCS;
}();
const LabCS = function LabCSClosure() {
  function fn_g(x) {
    let result;
    if (x >= 6 / 29) {
      result = x ** 3;
    } else {
      result = 108 / 841 * (x - 4 / 29);
    }
    return result;
  }
  function decode(value, high1, low2, high2) {
    return low2 + value * (high2 - low2) / high1;
  }
  function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
    let Ls = src[srcOffset];
    let as = src[srcOffset + 1];
    let bs = src[srcOffset + 2];
    if (maxVal !== false) {
      Ls = decode(Ls, maxVal, 0, 100);
      as = decode(as, maxVal, cs.amin, cs.amax);
      bs = decode(bs, maxVal, cs.bmin, cs.bmax);
    }
    if (as > cs.amax) {
      as = cs.amax;
    } else if (as < cs.amin) {
      as = cs.amin;
    }
    if (bs > cs.bmax) {
      bs = cs.bmax;
    } else if (bs < cs.bmin) {
      bs = cs.bmin;
    }
    const M = (Ls + 16) / 116;
    const L = M + as / 500;
    const N = M - bs / 200;
    const X = cs.XW * fn_g(L);
    const Y = cs.YW * fn_g(M);
    const Z = cs.ZW * fn_g(N);
    let r, g, b;
    if (cs.ZW < 1) {
      r = X * 3.1339 + Y * -1.617 + Z * -0.4906;
      g = X * -0.9785 + Y * 1.916 + Z * 0.0333;
      b = X * 0.072 + Y * -0.229 + Z * 1.4057;
    } else {
      r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
      g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
      b = X * 0.0557 + Y * -0.204 + Z * 1.057;
    }
    dest[destOffset] = Math.sqrt(r) * 255;
    dest[destOffset + 1] = Math.sqrt(g) * 255;
    dest[destOffset + 2] = Math.sqrt(b) * 255;
  }
  class LabCS extends ColorSpace {
    constructor(whitePoint, blackPoint, range) {
      super("Lab", 3);
      if (!whitePoint) {
        throw new _util.FormatError("WhitePoint missing - required for color space Lab");
      }
      blackPoint = blackPoint || [0, 0, 0];
      range = range || [-100, 100, -100, 100];
      this.XW = whitePoint[0];
      this.YW = whitePoint[1];
      this.ZW = whitePoint[2];
      this.amin = range[0];
      this.amax = range[1];
      this.bmin = range[2];
      this.bmax = range[3];
      this.XB = blackPoint[0];
      this.YB = blackPoint[1];
      this.ZB = blackPoint[2];
      if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
        throw new _util.FormatError("Invalid WhitePoint components, no fallback available");
      }
      if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
        (0, _util.info)("Invalid BlackPoint, falling back to default");
        this.XB = this.YB = this.ZB = 0;
      }
      if (this.amin > this.amax || this.bmin > this.bmax) {
        (0, _util.info)("Invalid Range, falling back to defaults");
        this.amin = -100;
        this.amax = 100;
        this.bmin = -100;
        this.bmax = 100;
      }
    }
    getRgbItem(src, srcOffset, dest, destOffset) {
      convertToRgb(this, src, srcOffset, false, dest, destOffset);
    }
    getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
      const maxVal = (1 << bits) - 1;
      for (let i = 0; i < count; i++) {
        convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);
        srcOffset += 3;
        destOffset += 3 + alpha01;
      }
    }
    getOutputLength(inputLength, alpha01) {
      return inputLength * (3 + alpha01) / 3 | 0;
    }
    isDefaultDecode(decodeMap, bpc) {
      return true;
    }
    get usesZeroToOneRange() {
      return (0, _util.shadow)(this, "usesZeroToOneRange", false);
    }
  }
  return LabCS;
}();

/***/ }),
/* 13 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PartialEvaluator = exports.EvaluatorPreprocessor = void 0;
var _util = __w_pdfjs_require__(2);
var _cmap = __w_pdfjs_require__(14);
var _primitives = __w_pdfjs_require__(3);
var _fonts = __w_pdfjs_require__(32);
var _encodings = __w_pdfjs_require__(35);
var _standard_fonts = __w_pdfjs_require__(39);
var _pattern = __w_pdfjs_require__(48);
var _xfa_fonts = __w_pdfjs_require__(49);
var _to_unicode_map = __w_pdfjs_require__(40);
var _function = __w_pdfjs_require__(55);
var _parser = __w_pdfjs_require__(15);
var _image_utils = __w_pdfjs_require__(57);
var _stream = __w_pdfjs_require__(8);
var _base_stream = __w_pdfjs_require__(5);
var _bidi = __w_pdfjs_require__(58);
var _colorspace = __w_pdfjs_require__(12);
var _decode_stream = __w_pdfjs_require__(17);
var _fonts_utils = __w_pdfjs_require__(36);
var _glyphlist = __w_pdfjs_require__(37);
var _core_utils = __w_pdfjs_require__(4);
var _metrics = __w_pdfjs_require__(43);
var _unicode = __w_pdfjs_require__(38);
var _murmurhash = __w_pdfjs_require__(59);
var _operator_list = __w_pdfjs_require__(60);
var _image = __w_pdfjs_require__(61);
const DefaultPartialEvaluatorOptions = Object.freeze({
  maxImageSize: -1,
  disableFontFace: false,
  ignoreErrors: false,
  isEvalSupported: true,
  isOffscreenCanvasSupported: true,
  fontExtraProperties: false,
  useSystemFonts: true,
  cMapUrl: null,
  standardFontDataUrl: null
});
const PatternType = {
  TILING: 1,
  SHADING: 2
};
const TEXT_CHUNK_BATCH_SIZE = 10;
const deferred = Promise.resolve();
function normalizeBlendMode(value, parsingArray = false) {
  if (Array.isArray(value)) {
    for (const val of value) {
      const maybeBM = normalizeBlendMode(val, true);
      if (maybeBM) {
        return maybeBM;
      }
    }
    (0, _util.warn)(`Unsupported blend mode Array: ${value}`);
    return "source-over";
  }
  if (!(value instanceof _primitives.Name)) {
    if (parsingArray) {
      return null;
    }
    return "source-over";
  }
  switch (value.name) {
    case "Normal":
    case "Compatible":
      return "source-over";
    case "Multiply":
      return "multiply";
    case "Screen":
      return "screen";
    case "Overlay":
      return "overlay";
    case "Darken":
      return "darken";
    case "Lighten":
      return "lighten";
    case "ColorDodge":
      return "color-dodge";
    case "ColorBurn":
      return "color-burn";
    case "HardLight":
      return "hard-light";
    case "SoftLight":
      return "soft-light";
    case "Difference":
      return "difference";
    case "Exclusion":
      return "exclusion";
    case "Hue":
      return "hue";
    case "Saturation":
      return "saturation";
    case "Color":
      return "color";
    case "Luminosity":
      return "luminosity";
  }
  if (parsingArray) {
    return null;
  }
  (0, _util.warn)(`Unsupported blend mode: ${value.name}`);
  return "source-over";
}
function incrementCachedImageMaskCount(data) {
  if (data.fn === _util.OPS.paintImageMaskXObject && data.args[0] && data.args[0].count > 0) {
    data.args[0].count++;
  }
}
class TimeSlotManager {
  static get TIME_SLOT_DURATION_MS() {
    return (0, _util.shadow)(this, "TIME_SLOT_DURATION_MS", 20);
  }
  static get CHECK_TIME_EVERY() {
    return (0, _util.shadow)(this, "CHECK_TIME_EVERY", 100);
  }
  constructor() {
    this.reset();
  }
  check() {
    if (++this.checked < TimeSlotManager.CHECK_TIME_EVERY) {
      return false;
    }
    this.checked = 0;
    return this.endTime <= Date.now();
  }
  reset() {
    this.endTime = Date.now() + TimeSlotManager.TIME_SLOT_DURATION_MS;
    this.checked = 0;
  }
}
class PartialEvaluator {
  constructor({
    xref,
    handler,
    pageIndex,
    idFactory,
    fontCache,
    builtInCMapCache,
    standardFontDataCache,
    globalImageCache,
    options = null
  }) {
    this.xref = xref;
    this.handler = handler;
    this.pageIndex = pageIndex;
    this.idFactory = idFactory;
    this.fontCache = fontCache;
    this.builtInCMapCache = builtInCMapCache;
    this.standardFontDataCache = standardFontDataCache;
    this.globalImageCache = globalImageCache;
    this.options = options || DefaultPartialEvaluatorOptions;
    this.parsingType3Font = false;
    this._fetchBuiltInCMapBound = this.fetchBuiltInCMap.bind(this);
  }
  get _pdfFunctionFactory() {
    const pdfFunctionFactory = new _function.PDFFunctionFactory({
      xref: this.xref,
      isEvalSupported: this.options.isEvalSupported
    });
    return (0, _util.shadow)(this, "_pdfFunctionFactory", pdfFunctionFactory);
  }
  clone(newOptions = null) {
    const newEvaluator = Object.create(this);
    newEvaluator.options = Object.assign(Object.create(null), this.options, newOptions);
    return newEvaluator;
  }
  hasBlendModes(resources, nonBlendModesSet) {
    if (!(resources instanceof _primitives.Dict)) {
      return false;
    }
    if (resources.objId && nonBlendModesSet.has(resources.objId)) {
      return false;
    }
    const processed = new _primitives.RefSet(nonBlendModesSet);
    if (resources.objId) {
      processed.put(resources.objId);
    }
    const nodes = [resources],
      xref = this.xref;
    while (nodes.length) {
      const node = nodes.shift();
      const graphicStates = node.get("ExtGState");
      if (graphicStates instanceof _primitives.Dict) {
        for (let graphicState of graphicStates.getRawValues()) {
          if (graphicState instanceof _primitives.Ref) {
            if (processed.has(graphicState)) {
              continue;
            }
            try {
              graphicState = xref.fetch(graphicState);
            } catch (ex) {
              processed.put(graphicState);
              (0, _util.info)(`hasBlendModes - ignoring ExtGState: "${ex}".`);
              continue;
            }
          }
          if (!(graphicState instanceof _primitives.Dict)) {
            continue;
          }
          if (graphicState.objId) {
            processed.put(graphicState.objId);
          }
          const bm = graphicState.get("BM");
          if (bm instanceof _primitives.Name) {
            if (bm.name !== "Normal") {
              return true;
            }
            continue;
          }
          if (bm !== undefined && Array.isArray(bm)) {
            for (const element of bm) {
              if (element instanceof _primitives.Name && element.name !== "Normal") {
                return true;
              }
            }
          }
        }
      }
      const xObjects = node.get("XObject");
      if (!(xObjects instanceof _primitives.Dict)) {
        continue;
      }
      for (let xObject of xObjects.getRawValues()) {
        if (xObject instanceof _primitives.Ref) {
          if (processed.has(xObject)) {
            continue;
          }
          try {
            xObject = xref.fetch(xObject);
          } catch (ex) {
            processed.put(xObject);
            (0, _util.info)(`hasBlendModes - ignoring XObject: "${ex}".`);
            continue;
          }
        }
        if (!(xObject instanceof _base_stream.BaseStream)) {
          continue;
        }
        if (xObject.dict.objId) {
          processed.put(xObject.dict.objId);
        }
        const xResources = xObject.dict.get("Resources");
        if (!(xResources instanceof _primitives.Dict)) {
          continue;
        }
        if (xResources.objId && processed.has(xResources.objId)) {
          continue;
        }
        nodes.push(xResources);
        if (xResources.objId) {
          processed.put(xResources.objId);
        }
      }
    }
    for (const ref of processed) {
      nonBlendModesSet.put(ref);
    }
    return false;
  }
  async fetchBuiltInCMap(name) {
    const cachedData = this.builtInCMapCache.get(name);
    if (cachedData) {
      return cachedData;
    }
    let data;
    if (this.options.cMapUrl !== null) {
      const url = `${this.options.cMapUrl}${name}.bcmap`;
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`fetchBuiltInCMap: failed to fetch file "${url}" with "${response.statusText}".`);
      }
      data = {
        cMapData: new Uint8Array(await response.arrayBuffer()),
        compressionType: _util.CMapCompressionType.BINARY
      };
    } else {
      data = await this.handler.sendWithPromise("FetchBuiltInCMap", {
        name
      });
    }
    if (data.compressionType !== _util.CMapCompressionType.NONE) {
      this.builtInCMapCache.set(name, data);
    }
    return data;
  }
  async fetchStandardFontData(name) {
    const cachedData = this.standardFontDataCache.get(name);
    if (cachedData) {
      return new _stream.Stream(cachedData);
    }
    if (this.options.useSystemFonts && name !== "Symbol" && name !== "ZapfDingbats") {
      return null;
    }
    const standardFontNameToFileName = (0, _standard_fonts.getFontNameToFileMap)(),
      filename = standardFontNameToFileName[name];
    let data;
    if (this.options.standardFontDataUrl !== null) {
      const url = `${this.options.standardFontDataUrl}${filename}`;
      const response = await fetch(url);
      if (!response.ok) {
        (0, _util.warn)(`fetchStandardFontData: failed to fetch file "${url}" with "${response.statusText}".`);
      } else {
        data = await response.arrayBuffer();
      }
    } else {
      try {
        data = await this.handler.sendWithPromise("FetchStandardFontData", {
          filename
        });
      } catch (e) {
        (0, _util.warn)(`fetchStandardFontData: failed to fetch file "${filename}" with "${e}".`);
      }
    }
    if (!data) {
      return null;
    }
    this.standardFontDataCache.set(name, data);
    return new _stream.Stream(data);
  }
  async buildFormXObject(resources, xobj, smask, operatorList, task, initialState, localColorSpaceCache) {
    const dict = xobj.dict;
    const matrix = dict.getArray("Matrix");
    let bbox = dict.getArray("BBox");
    if (Array.isArray(bbox) && bbox.length === 4) {
      bbox = _util.Util.normalizeRect(bbox);
    } else {
      bbox = null;
    }
    let optionalContent, groupOptions;
    if (dict.has("OC")) {
      optionalContent = await this.parseMarkedContentProps(dict.get("OC"), resources);
    }
    if (optionalContent !== undefined) {
      operatorList.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
    }
    const group = dict.get("Group");
    if (group) {
      groupOptions = {
        matrix,
        bbox,
        smask,
        isolated: false,
        knockout: false
      };
      const groupSubtype = group.get("S");
      let colorSpace = null;
      if ((0, _primitives.isName)(groupSubtype, "Transparency")) {
        groupOptions.isolated = group.get("I") || false;
        groupOptions.knockout = group.get("K") || false;
        if (group.has("CS")) {
          const cs = group.getRaw("CS");
          const cachedColorSpace = _colorspace.ColorSpace.getCached(cs, this.xref, localColorSpaceCache);
          if (cachedColorSpace) {
            colorSpace = cachedColorSpace;
          } else {
            colorSpace = await this.parseColorSpace({
              cs,
              resources,
              localColorSpaceCache
            });
          }
        }
      }
      if (smask && smask.backdrop) {
        colorSpace = colorSpace || _colorspace.ColorSpace.singletons.rgb;
        smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
      }
      operatorList.addOp(_util.OPS.beginGroup, [groupOptions]);
    }
    const args = group ? [matrix, null] : [matrix, bbox];
    operatorList.addOp(_util.OPS.paintFormXObjectBegin, args);
    return this.getOperatorList({
      stream: xobj,
      task,
      resources: dict.get("Resources") || resources,
      operatorList,
      initialState
    }).then(function () {
      operatorList.addOp(_util.OPS.paintFormXObjectEnd, []);
      if (group) {
        operatorList.addOp(_util.OPS.endGroup, [groupOptions]);
      }
      if (optionalContent !== undefined) {
        operatorList.addOp(_util.OPS.endMarkedContent, []);
      }
    });
  }
  _sendImgData(objId, imgData, cacheGlobally = false) {
    const transfers = imgData ? [imgData.bitmap || imgData.data.buffer] : null;
    if (this.parsingType3Font || cacheGlobally) {
      return this.handler.send("commonobj", [objId, "Image", imgData], transfers);
    }
    return this.handler.send("obj", [objId, this.pageIndex, "Image", imgData], transfers);
  }
  async buildPaintImageXObject({
    resources,
    image,
    isInline = false,
    operatorList,
    cacheKey,
    localImageCache,
    localColorSpaceCache
  }) {
    const dict = image.dict;
    const imageRef = dict.objId;
    const w = dict.get("W", "Width");
    const h = dict.get("H", "Height");
    if (!(w && typeof w === "number") || !(h && typeof h === "number")) {
      (0, _util.warn)("Image dimensions are missing, or not numbers.");
      return;
    }
    const maxImageSize = this.options.maxImageSize;
    if (maxImageSize !== -1 && w * h > maxImageSize) {
      const msg = "Image exceeded maximum allowed size and was removed.";
      if (this.options.ignoreErrors) {
        (0, _util.warn)(msg);
        return;
      }
      throw new Error(msg);
    }
    let optionalContent;
    if (dict.has("OC")) {
      optionalContent = await this.parseMarkedContentProps(dict.get("OC"), resources);
    }
    const imageMask = dict.get("IM", "ImageMask") || false;
    let imgData, args;
    if (imageMask) {
      const interpolate = dict.get("I", "Interpolate");
      const bitStrideLength = w + 7 >> 3;
      const imgArray = image.getBytes(bitStrideLength * h);
      const decode = dict.getArray("D", "Decode");
      if (this.parsingType3Font) {
        imgData = _image.PDFImage.createRawMask({
          imgArray,
          width: w,
          height: h,
          imageIsFromDecodeStream: image instanceof _decode_stream.DecodeStream,
          inverseDecode: !!decode && decode[0] > 0,
          interpolate
        });
        imgData.cached = !!cacheKey;
        args = [imgData];
        operatorList.addImageOps(_util.OPS.paintImageMaskXObject, args, optionalContent);
        if (cacheKey) {
          localImageCache.set(cacheKey, imageRef, {
            fn: _util.OPS.paintImageMaskXObject,
            args,
            optionalContent
          });
        }
        return;
      }
      imgData = _image.PDFImage.createMask({
        imgArray,
        width: w,
        height: h,
        imageIsFromDecodeStream: image instanceof _decode_stream.DecodeStream,
        inverseDecode: !!decode && decode[0] > 0,
        interpolate,
        isOffscreenCanvasSupported: this.options.isOffscreenCanvasSupported
      });
      if (imgData.isSingleOpaquePixel) {
        operatorList.addImageOps(_util.OPS.paintSolidColorImageMask, [], optionalContent);
        if (cacheKey) {
          localImageCache.set(cacheKey, imageRef, {
            fn: _util.OPS.paintSolidColorImageMask,
            args: [],
            optionalContent
          });
        }
        return;
      }
      const objId = `mask_${this.idFactory.createObjId()}`;
      operatorList.addDependency(objId);
      this._sendImgData(objId, imgData);
      args = [{
        data: objId,
        width: imgData.width,
        height: imgData.height,
        interpolate: imgData.interpolate,
        count: 1
      }];
      operatorList.addImageOps(_util.OPS.paintImageMaskXObject, args, optionalContent);
      if (cacheKey) {
        localImageCache.set(cacheKey, imageRef, {
          fn: _util.OPS.paintImageMaskXObject,
          args,
          optionalContent
        });
      }
      return;
    }
    const softMask = dict.get("SM", "SMask") || false;
    const mask = dict.get("Mask") || false;
    const SMALL_IMAGE_DIMENSIONS = 200;
    if (isInline && !softMask && !mask && w + h < SMALL_IMAGE_DIMENSIONS) {
      const imageObj = new _image.PDFImage({
        xref: this.xref,
        res: resources,
        image,
        isInline,
        pdfFunctionFactory: this._pdfFunctionFactory,
        localColorSpaceCache
      });
      imgData = imageObj.createImageData(true);
      operatorList.addImageOps(_util.OPS.paintInlineImageXObject, [imgData], optionalContent);
      return;
    }
    let objId = `img_${this.idFactory.createObjId()}`,
      cacheGlobally = false;
    if (this.parsingType3Font) {
      objId = `${this.idFactory.getDocId()}_type3_${objId}`;
    } else if (imageRef) {
      cacheGlobally = this.globalImageCache.shouldCache(imageRef, this.pageIndex);
      if (cacheGlobally) {
        objId = `${this.idFactory.getDocId()}_${objId}`;
      }
    }
    operatorList.addDependency(objId);
    args = [objId, w, h];
    _image.PDFImage.buildImage({
      xref: this.xref,
      res: resources,
      image,
      isInline,
      pdfFunctionFactory: this._pdfFunctionFactory,
      localColorSpaceCache
    }).then(imageObj => {
      imgData = imageObj.createImageData(false);
      if (cacheKey && imageRef && cacheGlobally) {
        this.globalImageCache.addByteSize(imageRef, imgData.data.length);
      }
      return this._sendImgData(objId, imgData, cacheGlobally);
    }).catch(reason => {
      (0, _util.warn)(`Unable to decode image "${objId}": "${reason}".`);
      return this._sendImgData(objId, null, cacheGlobally);
    });
    operatorList.addImageOps(_util.OPS.paintImageXObject, args, optionalContent);
    if (cacheKey) {
      localImageCache.set(cacheKey, imageRef, {
        fn: _util.OPS.paintImageXObject,
        args,
        optionalContent
      });
      if (imageRef) {
        (0, _util.assert)(!isInline, "Cannot cache an inline image globally.");
        this.globalImageCache.addPageIndex(imageRef, this.pageIndex);
        if (cacheGlobally) {
          this.globalImageCache.setData(imageRef, {
            objId,
            fn: _util.OPS.paintImageXObject,
            args,
            optionalContent,
            byteSize: 0
          });
        }
      }
    }
  }
  handleSMask(smask, resources, operatorList, task, stateManager, localColorSpaceCache) {
    const smaskContent = smask.get("G");
    const smaskOptions = {
      subtype: smask.get("S").name,
      backdrop: smask.get("BC")
    };
    const transferObj = smask.get("TR");
    if ((0, _function.isPDFFunction)(transferObj)) {
      const transferFn = this._pdfFunctionFactory.create(transferObj);
      const transferMap = new Uint8Array(256);
      const tmp = new Float32Array(1);
      for (let i = 0; i < 256; i++) {
        tmp[0] = i / 255;
        transferFn(tmp, 0, tmp, 0);
        transferMap[i] = tmp[0] * 255 | 0;
      }
      smaskOptions.transferMap = transferMap;
    }
    return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, task, stateManager.state.clone(), localColorSpaceCache);
  }
  handleTransferFunction(tr) {
    let transferArray;
    if (Array.isArray(tr)) {
      transferArray = tr;
    } else if ((0, _function.isPDFFunction)(tr)) {
      transferArray = [tr];
    } else {
      return null;
    }
    const transferMaps = [];
    let numFns = 0,
      numEffectfulFns = 0;
    for (const entry of transferArray) {
      const transferObj = this.xref.fetchIfRef(entry);
      numFns++;
      if ((0, _primitives.isName)(transferObj, "Identity")) {
        transferMaps.push(null);
        continue;
      } else if (!(0, _function.isPDFFunction)(transferObj)) {
        return null;
      }
      const transferFn = this._pdfFunctionFactory.create(transferObj);
      const transferMap = new Uint8Array(256),
        tmp = new Float32Array(1);
      for (let j = 0; j < 256; j++) {
        tmp[0] = j / 255;
        transferFn(tmp, 0, tmp, 0);
        transferMap[j] = tmp[0] * 255 | 0;
      }
      transferMaps.push(transferMap);
      numEffectfulFns++;
    }
    if (!(numFns === 1 || numFns === 4)) {
      return null;
    }
    if (numEffectfulFns === 0) {
      return null;
    }
    return transferMaps;
  }
  handleTilingType(fn, color, resources, pattern, patternDict, operatorList, task, localTilingPatternCache) {
    const tilingOpList = new _operator_list.OperatorList();
    const patternResources = _primitives.Dict.merge({
      xref: this.xref,
      dictArray: [patternDict.get("Resources"), resources]
    });
    return this.getOperatorList({
      stream: pattern,
      task,
      resources: patternResources,
      operatorList: tilingOpList
    }).then(function () {
      const operatorListIR = tilingOpList.getIR();
      const tilingPatternIR = (0, _pattern.getTilingPatternIR)(operatorListIR, patternDict, color);
      operatorList.addDependencies(tilingOpList.dependencies);
      operatorList.addOp(fn, tilingPatternIR);
      if (patternDict.objId) {
        localTilingPatternCache.set(null, patternDict.objId, {
          operatorListIR,
          dict: patternDict
        });
      }
    }).catch(reason => {
      if (reason instanceof _util.AbortException) {
        return;
      }
      if (this.options.ignoreErrors) {
        this.handler.send("UnsupportedFeature", {
          featureId: _util.UNSUPPORTED_FEATURES.errorTilingPattern
        });
        (0, _util.warn)(`handleTilingType - ignoring pattern: "${reason}".`);
        return;
      }
      throw reason;
    });
  }
  handleSetFont(resources, fontArgs, fontRef, operatorList, task, state, fallbackFontDict = null, cssFontInfo = null) {
    const fontName = fontArgs && fontArgs[0] instanceof _primitives.Name ? fontArgs[0].name : null;
    return this.loadFont(fontName, fontRef, resources, fallbackFontDict, cssFontInfo).then(translated => {
      if (!translated.font.isType3Font) {
        return translated;
      }
      return translated.loadType3Data(this, resources, task).then(function () {
        operatorList.addDependencies(translated.type3Dependencies);
        return translated;
      }).catch(reason => {
        this.handler.send("UnsupportedFeature", {
          featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadType3
        });
        return new TranslatedFont({
          loadedName: "g_font_error",
          font: new _fonts.ErrorFont(`Type3 font load error: ${reason}`),
          dict: translated.font,
          evaluatorOptions: this.options
        });
      });
    }).then(translated => {
      state.font = translated.font;
      translated.send(this.handler);
      return translated.loadedName;
    });
  }
  handleText(chars, state) {
    const font = state.font;
    const glyphs = font.charsToGlyphs(chars);
    if (font.data) {
      const isAddToPathSet = !!(state.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
      if (isAddToPathSet || state.fillColorSpace.name === "Pattern" || font.disableFontFace || this.options.disableFontFace) {
        PartialEvaluator.buildFontPaths(font, glyphs, this.handler, this.options);
      }
    }
    return glyphs;
  }
  ensureStateFont(state) {
    if (state.font) {
      return;
    }
    const reason = new _util.FormatError("Missing setFont (Tf) operator before text rendering operator.");
    if (this.options.ignoreErrors) {
      this.handler.send("UnsupportedFeature", {
        featureId: _util.UNSUPPORTED_FEATURES.errorFontState
      });
      (0, _util.warn)(`ensureStateFont: "${reason}".`);
      return;
    }
    throw reason;
  }
  async setGState({
    resources,
    gState,
    operatorList,
    cacheKey,
    task,
    stateManager,
    localGStateCache,
    localColorSpaceCache
  }) {
    const gStateRef = gState.objId;
    let isSimpleGState = true;
    const gStateObj = [];
    let promise = Promise.resolve();
    for (const key of gState.getKeys()) {
      const value = gState.get(key);
      switch (key) {
        case "Type":
          break;
        case "LW":
        case "LC":
        case "LJ":
        case "ML":
        case "D":
        case "RI":
        case "FL":
        case "CA":
        case "ca":
          gStateObj.push([key, value]);
          break;
        case "Font":
          isSimpleGState = false;
          promise = promise.then(() => {
            return this.handleSetFont(resources, null, value[0], operatorList, task, stateManager.state).then(function (loadedName) {
              operatorList.addDependency(loadedName);
              gStateObj.push([key, [loadedName, value[1]]]);
            });
          });
          break;
        case "BM":
          gStateObj.push([key, normalizeBlendMode(value)]);
          break;
        case "SMask":
          if ((0, _primitives.isName)(value, "None")) {
            gStateObj.push([key, false]);
            break;
          }
          if (value instanceof _primitives.Dict) {
            isSimpleGState = false;
            promise = promise.then(() => {
              return this.handleSMask(value, resources, operatorList, task, stateManager, localColorSpaceCache);
            });
            gStateObj.push([key, true]);
          } else {
            (0, _util.warn)("Unsupported SMask type");
          }
          break;
        case "TR":
          const transferMaps = this.handleTransferFunction(value);
          gStateObj.push([key, transferMaps]);
          break;
        case "OP":
        case "op":
        case "OPM":
        case "BG":
        case "BG2":
        case "UCR":
        case "UCR2":
        case "TR2":
        case "HT":
        case "SM":
        case "SA":
        case "AIS":
        case "TK":
          (0, _util.info)("graphic state operator " + key);
          break;
        default:
          (0, _util.info)("Unknown graphic state operator " + key);
          break;
      }
    }
    return promise.then(function () {
      if (gStateObj.length > 0) {
        operatorList.addOp(_util.OPS.setGState, [gStateObj]);
      }
      if (isSimpleGState) {
        localGStateCache.set(cacheKey, gStateRef, gStateObj);
      }
    });
  }
  loadFont(fontName, font, resources, fallbackFontDict = null, cssFontInfo = null) {
    const errorFont = async () => {
      return new TranslatedFont({
        loadedName: "g_font_error",
        font: new _fonts.ErrorFont(`Font "${fontName}" is not available.`),
        dict: font,
        evaluatorOptions: this.options
      });
    };
    const xref = this.xref;
    let fontRef;
    if (font) {
      if (font instanceof _primitives.Ref) {
        fontRef = font;
      }
    } else {
      const fontRes = resources.get("Font");
      if (fontRes) {
        fontRef = fontRes.getRaw(fontName);
      }
    }
    if (!fontRef) {
      const partialMsg = `Font "${fontName || font && font.toString()}" is not available`;
      if (!this.options.ignoreErrors && !this.parsingType3Font) {
        (0, _util.warn)(`${partialMsg}.`);
        return errorFont();
      }
      this.handler.send("UnsupportedFeature", {
        featureId: _util.UNSUPPORTED_FEATURES.errorFontMissing
      });
      (0, _util.warn)(`${partialMsg} -- attempting to fallback to a default font.`);
      if (fallbackFontDict) {
        fontRef = fallbackFontDict;
      } else {
        fontRef = PartialEvaluator.fallbackFontDict;
      }
    }
    if (this.parsingType3Font && this.type3FontRefs.has(fontRef)) {
      return errorFont();
    }
    if (this.fontCache.has(fontRef)) {
      return this.fontCache.get(fontRef);
    }
    font = xref.fetchIfRef(fontRef);
    if (!(font instanceof _primitives.Dict)) {
      return errorFont();
    }
    if (font.cacheKey && this.fontCache.has(font.cacheKey)) {
      return this.fontCache.get(font.cacheKey);
    }
    const fontCapability = (0, _util.createPromiseCapability)();
    let preEvaluatedFont;
    try {
      preEvaluatedFont = this.preEvaluateFont(font);
      preEvaluatedFont.cssFontInfo = cssFontInfo;
    } catch (reason) {
      (0, _util.warn)(`loadFont - preEvaluateFont failed: "${reason}".`);
      return errorFont();
    }
    const {
      descriptor,
      hash
    } = preEvaluatedFont;
    const fontRefIsRef = fontRef instanceof _primitives.Ref;
    let fontID;
    if (fontRefIsRef) {
      fontID = `f${fontRef.toString()}`;
    }
    if (hash && descriptor instanceof _primitives.Dict) {
      if (!descriptor.fontAliases) {
        descriptor.fontAliases = Object.create(null);
      }
      const fontAliases = descriptor.fontAliases;
      if (fontAliases[hash]) {
        const aliasFontRef = fontAliases[hash].aliasRef;
        if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
          this.fontCache.putAlias(fontRef, aliasFontRef);
          return this.fontCache.get(fontRef);
        }
      } else {
        fontAliases[hash] = {
          fontID: this.idFactory.createFontId()
        };
      }
      if (fontRefIsRef) {
        fontAliases[hash].aliasRef = fontRef;
      }
      fontID = fontAliases[hash].fontID;
    }
    if (fontRefIsRef) {
      this.fontCache.put(fontRef, fontCapability.promise);
    } else {
      if (!fontID) {
        fontID = this.idFactory.createFontId();
      }
      font.cacheKey = `cacheKey_${fontID}`;
      this.fontCache.put(font.cacheKey, fontCapability.promise);
    }
    (0, _util.assert)(fontID && fontID.startsWith("f"), 'The "fontID" must be (correctly) defined.');
    font.loadedName = `${this.idFactory.getDocId()}_${fontID}`;
    this.translateFont(preEvaluatedFont).then(translatedFont => {
      fontCapability.resolve(new TranslatedFont({
        loadedName: font.loadedName,
        font: translatedFont,
        dict: font,
        evaluatorOptions: this.options
      }));
    }).catch(reason => {
      this.handler.send("UnsupportedFeature", {
        featureId: _util.UNSUPPORTED_FEATURES.errorFontTranslate
      });
      (0, _util.warn)(`loadFont - translateFont failed: "${reason}".`);
      fontCapability.resolve(new TranslatedFont({
        loadedName: font.loadedName,
        font: new _fonts.ErrorFont(reason instanceof Error ? reason.message : reason),
        dict: font,
        evaluatorOptions: this.options
      }));
    });
    return fontCapability.promise;
  }
  buildPath(operatorList, fn, args, parsingText = false) {
    const lastIndex = operatorList.length - 1;
    if (!args) {
      args = [];
    }
    if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== _util.OPS.constructPath) {
      if (parsingText) {
        (0, _util.warn)(`Encountered path operator "${fn}" inside of a text object.`);
        operatorList.addOp(_util.OPS.save, null);
      }
      let minMax;
      switch (fn) {
        case _util.OPS.rectangle:
          const x = args[0] + args[2];
          const y = args[1] + args[3];
          minMax = [Math.min(args[0], x), Math.max(args[0], x), Math.min(args[1], y), Math.max(args[1], y)];
          break;
        case _util.OPS.moveTo:
        case _util.OPS.lineTo:
          minMax = [args[0], args[0], args[1], args[1]];
          break;
        default:
          minMax = [Infinity, -Infinity, Infinity, -Infinity];
          break;
      }
      operatorList.addOp(_util.OPS.constructPath, [[fn], args, minMax]);
      if (parsingText) {
        operatorList.addOp(_util.OPS.restore, null);
      }
    } else {
      const opArgs = operatorList.argsArray[lastIndex];
      opArgs[0].push(fn);
      opArgs[1].push(...args);
      const minMax = opArgs[2];
      switch (fn) {
        case _util.OPS.rectangle:
          const x = args[0] + args[2];
          const y = args[1] + args[3];
          minMax[0] = Math.min(minMax[0], args[0], x);
          minMax[1] = Math.max(minMax[1], args[0], x);
          minMax[2] = Math.min(minMax[2], args[1], y);
          minMax[3] = Math.max(minMax[3], args[1], y);
          break;
        case _util.OPS.moveTo:
        case _util.OPS.lineTo:
          minMax[0] = Math.min(minMax[0], args[0]);
          minMax[1] = Math.max(minMax[1], args[0]);
          minMax[2] = Math.min(minMax[2], args[1]);
          minMax[3] = Math.max(minMax[3], args[1]);
          break;
      }
    }
  }
  parseColorSpace({
    cs,
    resources,
    localColorSpaceCache
  }) {
    return _colorspace.ColorSpace.parseAsync({
      cs,
      xref: this.xref,
      resources,
      pdfFunctionFactory: this._pdfFunctionFactory,
      localColorSpaceCache
    }).catch(reason => {
      if (reason instanceof _util.AbortException) {
        return null;
      }
      if (this.options.ignoreErrors) {
        this.handler.send("UnsupportedFeature", {
          featureId: _util.UNSUPPORTED_FEATURES.errorColorSpace
        });
        (0, _util.warn)(`parseColorSpace - ignoring ColorSpace: "${reason}".`);
        return null;
      }
      throw reason;
    });
  }
  parseShading({
    shading,
    resources,
    localColorSpaceCache,
    localShadingPatternCache
  }) {
    let id = localShadingPatternCache.get(shading);
    if (!id) {
      var shadingFill = _pattern.Pattern.parseShading(shading, this.xref, resources, this.handler, this._pdfFunctionFactory, localColorSpaceCache);
      const patternIR = shadingFill.getIR();
      id = `pattern_${this.idFactory.createObjId()}`;
      localShadingPatternCache.set(shading, id);
      this.handler.send("obj", [id, this.pageIndex, "Pattern", patternIR]);
    }
    return id;
  }
  handleColorN(operatorList, fn, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache) {
    const patternName = args.pop();
    if (patternName instanceof _primitives.Name) {
      const rawPattern = patterns.getRaw(patternName.name);
      const localTilingPattern = rawPattern instanceof _primitives.Ref && localTilingPatternCache.getByRef(rawPattern);
      if (localTilingPattern) {
        try {
          const color = cs.base ? cs.base.getRgb(args, 0) : null;
          const tilingPatternIR = (0, _pattern.getTilingPatternIR)(localTilingPattern.operatorListIR, localTilingPattern.dict, color);
          operatorList.addOp(fn, tilingPatternIR);
          return undefined;
        } catch (ex) {}
      }
      const pattern = this.xref.fetchIfRef(rawPattern);
      if (pattern) {
        const dict = pattern instanceof _base_stream.BaseStream ? pattern.dict : pattern;
        const typeNum = dict.get("PatternType");
        if (typeNum === PatternType.TILING) {
          const color = cs.base ? cs.base.getRgb(args, 0) : null;
          return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task, localTilingPatternCache);
        } else if (typeNum === PatternType.SHADING) {
          const shading = dict.get("Shading");
          const matrix = dict.getArray("Matrix");
          const objId = this.parseShading({
            shading,
            resources,
            localColorSpaceCache,
            localShadingPatternCache
          });
          operatorList.addOp(fn, ["Shading", objId, matrix]);
          return undefined;
        }
        throw new _util.FormatError(`Unknown PatternType: ${typeNum}`);
      }
    }
    throw new _util.FormatError(`Unknown PatternName: ${patternName}`);
  }
  _parseVisibilityExpression(array, nestingCounter, currentResult) {
    const MAX_NESTING = 10;
    if (++nestingCounter > MAX_NESTING) {
      (0, _util.warn)("Visibility expression is too deeply nested");
      return;
    }
    const length = array.length;
    const operator = this.xref.fetchIfRef(array[0]);
    if (length < 2 || !(operator instanceof _primitives.Name)) {
      (0, _util.warn)("Invalid visibility expression");
      return;
    }
    switch (operator.name) {
      case "And":
      case "Or":
      case "Not":
        currentResult.push(operator.name);
        break;
      default:
        (0, _util.warn)(`Invalid operator ${operator.name} in visibility expression`);
        return;
    }
    for (let i = 1; i < length; i++) {
      const raw = array[i];
      const object = this.xref.fetchIfRef(raw);
      if (Array.isArray(object)) {
        const nestedResult = [];
        currentResult.push(nestedResult);
        this._parseVisibilityExpression(object, nestingCounter, nestedResult);
      } else if (raw instanceof _primitives.Ref) {
        currentResult.push(raw.toString());
      }
    }
  }
  async parseMarkedContentProps(contentProperties, resources) {
    let optionalContent;
    if (contentProperties instanceof _primitives.Name) {
      const properties = resources.get("Properties");
      optionalContent = properties.get(contentProperties.name);
    } else if (contentProperties instanceof _primitives.Dict) {
      optionalContent = contentProperties;
    } else {
      throw new _util.FormatError("Optional content properties malformed.");
    }
    const optionalContentType = optionalContent.get("Type").name;
    if (optionalContentType === "OCG") {
      return {
        type: optionalContentType,
        id: optionalContent.objId
      };
    } else if (optionalContentType === "OCMD") {
      const expression = optionalContent.get("VE");
      if (Array.isArray(expression)) {
        const result = [];
        this._parseVisibilityExpression(expression, 0, result);
        if (result.length > 0) {
          return {
            type: "OCMD",
            expression: result
          };
        }
      }
      const optionalContentGroups = optionalContent.get("OCGs");
      if (Array.isArray(optionalContentGroups) || optionalContentGroups instanceof _primitives.Dict) {
        const groupIds = [];
        if (Array.isArray(optionalContentGroups)) {
          for (const ocg of optionalContentGroups) {
            groupIds.push(ocg.toString());
          }
        } else {
          groupIds.push(optionalContentGroups.objId);
        }
        return {
          type: optionalContentType,
          ids: groupIds,
          policy: optionalContent.get("P") instanceof _primitives.Name ? optionalContent.get("P").name : null,
          expression: null
        };
      } else if (optionalContentGroups instanceof _primitives.Ref) {
        return {
          type: optionalContentType,
          id: optionalContentGroups.toString()
        };
      }
    }
    return null;
  }
  getOperatorList({
    stream,
    task,
    resources,
    operatorList,
    initialState = null,
    fallbackFontDict = null
  }) {
    resources = resources || _primitives.Dict.empty;
    initialState = initialState || new EvalState();
    if (!operatorList) {
      throw new Error('getOperatorList: missing "operatorList" parameter');
    }
    const self = this;
    const xref = this.xref;
    let parsingText = false;
    const localImageCache = new _image_utils.LocalImageCache();
    const localColorSpaceCache = new _image_utils.LocalColorSpaceCache();
    const localGStateCache = new _image_utils.LocalGStateCache();
    const localTilingPatternCache = new _image_utils.LocalTilingPatternCache();
    const localShadingPatternCache = new Map();
    const xobjs = resources.get("XObject") || _primitives.Dict.empty;
    const patterns = resources.get("Pattern") || _primitives.Dict.empty;
    const stateManager = new StateManager(initialState);
    const preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
    const timeSlotManager = new TimeSlotManager();
    function closePendingRestoreOPS(argument) {
      for (let i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
        operatorList.addOp(_util.OPS.restore, []);
      }
    }
    return new Promise(function promiseBody(resolve, reject) {
      const next = function (promise) {
        Promise.all([promise, operatorList.ready]).then(function () {
          try {
            promiseBody(resolve, reject);
          } catch (ex) {
            reject(ex);
          }
        }, reject);
      };
      task.ensureNotTerminated();
      timeSlotManager.reset();
      const operation = {};
      let stop, i, ii, cs, name, isValidName;
      while (!(stop = timeSlotManager.check())) {
        operation.args = null;
        if (!preprocessor.read(operation)) {
          break;
        }
        let args = operation.args;
        let fn = operation.fn;
        switch (fn | 0) {
          case _util.OPS.paintXObject:
            isValidName = args[0] instanceof _primitives.Name;
            name = args[0].name;
            if (isValidName) {
              const localImage = localImageCache.getByName(name);
              if (localImage) {
                operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
                incrementCachedImageMaskCount(localImage);
                args = null;
                continue;
              }
            }
            next(new Promise(function (resolveXObject, rejectXObject) {
              if (!isValidName) {
                throw new _util.FormatError("XObject must be referred to by name.");
              }
              let xobj = xobjs.getRaw(name);
              if (xobj instanceof _primitives.Ref) {
                const localImage = localImageCache.getByRef(xobj);
                if (localImage) {
                  operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
                  incrementCachedImageMaskCount(localImage);
                  resolveXObject();
                  return;
                }
                const globalImage = self.globalImageCache.getData(xobj, self.pageIndex);
                if (globalImage) {
                  operatorList.addDependency(globalImage.objId);
                  operatorList.addImageOps(globalImage.fn, globalImage.args, globalImage.optionalContent);
                  resolveXObject();
                  return;
                }
                xobj = xref.fetch(xobj);
              }
              if (!(xobj instanceof _base_stream.BaseStream)) {
                throw new _util.FormatError("XObject should be a stream");
              }
              const type = xobj.dict.get("Subtype");
              if (!(type instanceof _primitives.Name)) {
                throw new _util.FormatError("XObject should have a Name subtype");
              }
              if (type.name === "Form") {
                stateManager.save();
                self.buildFormXObject(resources, xobj, null, operatorList, task, stateManager.state.clone(), localColorSpaceCache).then(function () {
                  stateManager.restore();
                  resolveXObject();
                }, rejectXObject);
                return;
              } else if (type.name === "Image") {
                self.buildPaintImageXObject({
                  resources,
                  image: xobj,
                  operatorList,
                  cacheKey: name,
                  localImageCache,
                  localColorSpaceCache
                }).then(resolveXObject, rejectXObject);
                return;
              } else if (type.name === "PS") {
                (0, _util.info)("Ignored XObject subtype PS");
              } else {
                throw new _util.FormatError(`Unhandled XObject subtype ${type.name}`);
              }
              resolveXObject();
            }).catch(function (reason) {
              if (reason instanceof _util.AbortException) {
                return;
              }
              if (self.options.ignoreErrors) {
                self.handler.send("UnsupportedFeature", {
                  featureId: _util.UNSUPPORTED_FEATURES.errorXObject
                });
                (0, _util.warn)(`getOperatorList - ignoring XObject: "${reason}".`);
                return;
              }
              throw reason;
            }));
            return;
          case _util.OPS.setFont:
            var fontSize = args[1];
            next(self.handleSetFont(resources, args, null, operatorList, task, stateManager.state, fallbackFontDict).then(function (loadedName) {
              operatorList.addDependency(loadedName);
              operatorList.addOp(_util.OPS.setFont, [loadedName, fontSize]);
            }));
            return;
          case _util.OPS.beginText:
            parsingText = true;
            break;
          case _util.OPS.endText:
            parsingText = false;
            break;
          case _util.OPS.endInlineImage:
            var cacheKey = args[0].cacheKey;
            if (cacheKey) {
              const localImage = localImageCache.getByName(cacheKey);
              if (localImage) {
                operatorList.addImageOps(localImage.fn, localImage.args, localImage.optionalContent);
                incrementCachedImageMaskCount(localImage);
                args = null;
                continue;
              }
            }
            next(self.buildPaintImageXObject({
              resources,
              image: args[0],
              isInline: true,
              operatorList,
              cacheKey,
              localImageCache,
              localColorSpaceCache
            }));
            return;
          case _util.OPS.showText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            args[0] = self.handleText(args[0], stateManager.state);
            break;
          case _util.OPS.showSpacedText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            var combinedGlyphs = [];
            var state = stateManager.state;
            for (const arrItem of args[0]) {
              if (typeof arrItem === "string") {
                combinedGlyphs.push(...self.handleText(arrItem, state));
              } else if (typeof arrItem === "number") {
                combinedGlyphs.push(arrItem);
              }
            }
            args[0] = combinedGlyphs;
            fn = _util.OPS.showText;
            break;
          case _util.OPS.nextLineShowText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            operatorList.addOp(_util.OPS.nextLine);
            args[0] = self.handleText(args[0], stateManager.state);
            fn = _util.OPS.showText;
            break;
          case _util.OPS.nextLineSetSpacingShowText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            operatorList.addOp(_util.OPS.nextLine);
            operatorList.addOp(_util.OPS.setWordSpacing, [args.shift()]);
            operatorList.addOp(_util.OPS.setCharSpacing, [args.shift()]);
            args[0] = self.handleText(args[0], stateManager.state);
            fn = _util.OPS.showText;
            break;
          case _util.OPS.setTextRenderingMode:
            stateManager.state.textRenderingMode = args[0];
            break;
          case _util.OPS.setFillColorSpace:
            {
              const cachedColorSpace = _colorspace.ColorSpace.getCached(args[0], xref, localColorSpaceCache);
              if (cachedColorSpace) {
                stateManager.state.fillColorSpace = cachedColorSpace;
                continue;
              }
              next(self.parseColorSpace({
                cs: args[0],
                resources,
                localColorSpaceCache
              }).then(function (colorSpace) {
                if (colorSpace) {
                  stateManager.state.fillColorSpace = colorSpace;
                }
              }));
              return;
            }
          case _util.OPS.setStrokeColorSpace:
            {
              const cachedColorSpace = _colorspace.ColorSpace.getCached(args[0], xref, localColorSpaceCache);
              if (cachedColorSpace) {
                stateManager.state.strokeColorSpace = cachedColorSpace;
                continue;
              }
              next(self.parseColorSpace({
                cs: args[0],
                resources,
                localColorSpaceCache
              }).then(function (colorSpace) {
                if (colorSpace) {
                  stateManager.state.strokeColorSpace = colorSpace;
                }
              }));
              return;
            }
          case _util.OPS.setFillColor:
            cs = stateManager.state.fillColorSpace;
            args = cs.getRgb(args, 0);
            fn = _util.OPS.setFillRGBColor;
            break;
          case _util.OPS.setStrokeColor:
            cs = stateManager.state.strokeColorSpace;
            args = cs.getRgb(args, 0);
            fn = _util.OPS.setStrokeRGBColor;
            break;
          case _util.OPS.setFillGray:
            stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
            args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
            fn = _util.OPS.setFillRGBColor;
            break;
          case _util.OPS.setStrokeGray:
            stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
            args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
            fn = _util.OPS.setStrokeRGBColor;
            break;
          case _util.OPS.setFillCMYKColor:
            stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.cmyk;
            args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
            fn = _util.OPS.setFillRGBColor;
            break;
          case _util.OPS.setStrokeCMYKColor:
            stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.cmyk;
            args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
            fn = _util.OPS.setStrokeRGBColor;
            break;
          case _util.OPS.setFillRGBColor:
            stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.rgb;
            args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
            break;
          case _util.OPS.setStrokeRGBColor:
            stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.rgb;
            args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
            break;
          case _util.OPS.setFillColorN:
            cs = stateManager.state.fillColorSpace;
            if (cs.name === "Pattern") {
              next(self.handleColorN(operatorList, _util.OPS.setFillColorN, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache));
              return;
            }
            args = cs.getRgb(args, 0);
            fn = _util.OPS.setFillRGBColor;
            break;
          case _util.OPS.setStrokeColorN:
            cs = stateManager.state.strokeColorSpace;
            if (cs.name === "Pattern") {
              next(self.handleColorN(operatorList, _util.OPS.setStrokeColorN, args, cs, patterns, resources, task, localColorSpaceCache, localTilingPatternCache, localShadingPatternCache));
              return;
            }
            args = cs.getRgb(args, 0);
            fn = _util.OPS.setStrokeRGBColor;
            break;
          case _util.OPS.shadingFill:
            var shadingRes = resources.get("Shading");
            if (!shadingRes) {
              throw new _util.FormatError("No shading resource found");
            }
            var shading = shadingRes.get(args[0].name);
            if (!shading) {
              throw new _util.FormatError("No shading object found");
            }
            const patternId = self.parseShading({
              shading,
              resources,
              localColorSpaceCache,
              localShadingPatternCache
            });
            args = [patternId];
            fn = _util.OPS.shadingFill;
            break;
          case _util.OPS.setGState:
            isValidName = args[0] instanceof _primitives.Name;
            name = args[0].name;
            if (isValidName) {
              const localGStateObj = localGStateCache.getByName(name);
              if (localGStateObj) {
                if (localGStateObj.length > 0) {
                  operatorList.addOp(_util.OPS.setGState, [localGStateObj]);
                }
                args = null;
                continue;
              }
            }
            next(new Promise(function (resolveGState, rejectGState) {
              if (!isValidName) {
                throw new _util.FormatError("GState must be referred to by name.");
              }
              const extGState = resources.get("ExtGState");
              if (!(extGState instanceof _primitives.Dict)) {
                throw new _util.FormatError("ExtGState should be a dictionary.");
              }
              const gState = extGState.get(name);
              if (!(gState instanceof _primitives.Dict)) {
                throw new _util.FormatError("GState should be a dictionary.");
              }
              self.setGState({
                resources,
                gState,
                operatorList,
                cacheKey: name,
                task,
                stateManager,
                localGStateCache,
                localColorSpaceCache
              }).then(resolveGState, rejectGState);
            }).catch(function (reason) {
              if (reason instanceof _util.AbortException) {
                return;
              }
              if (self.options.ignoreErrors) {
                self.handler.send("UnsupportedFeature", {
                  featureId: _util.UNSUPPORTED_FEATURES.errorExtGState
                });
                (0, _util.warn)(`getOperatorList - ignoring ExtGState: "${reason}".`);
                return;
              }
              throw reason;
            }));
            return;
          case _util.OPS.moveTo:
          case _util.OPS.lineTo:
          case _util.OPS.curveTo:
          case _util.OPS.curveTo2:
          case _util.OPS.curveTo3:
          case _util.OPS.closePath:
          case _util.OPS.rectangle:
            self.buildPath(operatorList, fn, args, parsingText);
            continue;
          case _util.OPS.markPoint:
          case _util.OPS.markPointProps:
          case _util.OPS.beginCompat:
          case _util.OPS.endCompat:
            continue;
          case _util.OPS.beginMarkedContentProps:
            if (!(args[0] instanceof _primitives.Name)) {
              (0, _util.warn)(`Expected name for beginMarkedContentProps arg0=${args[0]}`);
              continue;
            }
            if (args[0].name === "OC") {
              next(self.parseMarkedContentProps(args[1], resources).then(data => {
                operatorList.addOp(_util.OPS.beginMarkedContentProps, ["OC", data]);
              }).catch(reason => {
                if (reason instanceof _util.AbortException) {
                  return;
                }
                if (self.options.ignoreErrors) {
                  self.handler.send("UnsupportedFeature", {
                    featureId: _util.UNSUPPORTED_FEATURES.errorMarkedContent
                  });
                  (0, _util.warn)(`getOperatorList - ignoring beginMarkedContentProps: "${reason}".`);
                  return;
                }
                throw reason;
              }));
              return;
            }
            args = [args[0].name, args[1] instanceof _primitives.Dict ? args[1].get("MCID") : null];
            break;
          case _util.OPS.beginMarkedContent:
          case _util.OPS.endMarkedContent:
          default:
            if (args !== null) {
              for (i = 0, ii = args.length; i < ii; i++) {
                if (args[i] instanceof _primitives.Dict) {
                  break;
                }
              }
              if (i < ii) {
                (0, _util.warn)("getOperatorList - ignoring operator: " + fn);
                continue;
              }
            }
        }
        operatorList.addOp(fn, args);
      }
      if (stop) {
        next(deferred);
        return;
      }
      closePendingRestoreOPS();
      resolve();
    }).catch(reason => {
      if (reason instanceof _util.AbortException) {
        return;
      }
      if (this.options.ignoreErrors) {
        this.handler.send("UnsupportedFeature", {
          featureId: _util.UNSUPPORTED_FEATURES.errorOperatorList
        });
        (0, _util.warn)(`getOperatorList - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
        closePendingRestoreOPS();
        return;
      }
      throw reason;
    });
  }
  getTextContent({
    stream,
    task,
    resources,
    stateManager = null,
    combineTextItems = false,
    includeMarkedContent = false,
    sink,
    seenStyles = new Set(),
    viewBox,
    markedContentData = null
  }) {
    resources = resources || _primitives.Dict.empty;
    stateManager = stateManager || new StateManager(new TextState());
    if (includeMarkedContent) {
      markedContentData = markedContentData || {
        level: 0
      };
    }
    const textContent = {
      items: [],
      styles: Object.create(null)
    };
    const textContentItem = {
      initialized: false,
      str: [],
      totalWidth: 0,
      totalHeight: 0,
      width: 0,
      height: 0,
      vertical: false,
      prevTransform: null,
      textAdvanceScale: 0,
      spaceInFlowMin: 0,
      spaceInFlowMax: 0,
      trackingSpaceMin: Infinity,
      negativeSpaceMax: -Infinity,
      notASpace: -Infinity,
      transform: null,
      fontName: null,
      hasEOL: false
    };
    const twoLastChars = [" ", " "];
    let twoLastCharsPos = 0;
    function saveLastChar(char) {
      const nextPos = (twoLastCharsPos + 1) % 2;
      const ret = twoLastChars[twoLastCharsPos] !== " " && twoLastChars[nextPos] === " ";
      twoLastChars[twoLastCharsPos] = char;
      twoLastCharsPos = nextPos;
      return ret;
    }
    function resetLastChars() {
      twoLastChars[0] = twoLastChars[1] = " ";
      twoLastCharsPos = 0;
    }
    const TRACKING_SPACE_FACTOR = 0.1;
    const NOT_A_SPACE_FACTOR = 0.03;
    const NEGATIVE_SPACE_FACTOR = -0.2;
    const SPACE_IN_FLOW_MIN_FACTOR = 0.1;
    const SPACE_IN_FLOW_MAX_FACTOR = 0.6;
    const self = this;
    const xref = this.xref;
    const showSpacedTextBuffer = [];
    let xobjs = null;
    const emptyXObjectCache = new _image_utils.LocalImageCache();
    const emptyGStateCache = new _image_utils.LocalGStateCache();
    const preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
    let textState;
    function getCurrentTextTransform() {
      const font = textState.font;
      const tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
      if (font.isType3Font && (textState.fontSize <= 1 || font.isCharBBox) && !(0, _util.isArrayEqual)(textState.fontMatrix, _util.FONT_IDENTITY_MATRIX)) {
        const glyphHeight = font.bbox[3] - font.bbox[1];
        if (glyphHeight > 0) {
          tsm[3] *= glyphHeight * textState.fontMatrix[3];
        }
      }
      return _util.Util.transform(textState.ctm, _util.Util.transform(textState.textMatrix, tsm));
    }
    function ensureTextContentItem() {
      if (textContentItem.initialized) {
        return textContentItem;
      }
      const {
        font,
        loadedName
      } = textState;
      if (!seenStyles.has(loadedName)) {
        seenStyles.add(loadedName);
        textContent.styles[loadedName] = {
          fontFamily: font.fallbackName,
          ascent: font.ascent,
          descent: font.descent,
          vertical: font.vertical
        };
      }
      textContentItem.fontName = loadedName;
      const trm = textContentItem.transform = getCurrentTextTransform();
      if (!font.vertical) {
        textContentItem.width = textContentItem.totalWidth = 0;
        textContentItem.height = textContentItem.totalHeight = Math.hypot(trm[2], trm[3]);
        textContentItem.vertical = false;
      } else {
        textContentItem.width = textContentItem.totalWidth = Math.hypot(trm[0], trm[1]);
        textContentItem.height = textContentItem.totalHeight = 0;
        textContentItem.vertical = true;
      }
      const scaleLineX = Math.hypot(textState.textLineMatrix[0], textState.textLineMatrix[1]);
      const scaleCtmX = Math.hypot(textState.ctm[0], textState.ctm[1]);
      textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
      textContentItem.trackingSpaceMin = textState.fontSize * TRACKING_SPACE_FACTOR;
      textContentItem.notASpace = textState.fontSize * NOT_A_SPACE_FACTOR;
      textContentItem.negativeSpaceMax = textState.fontSize * NEGATIVE_SPACE_FACTOR;
      textContentItem.spaceInFlowMin = textState.fontSize * SPACE_IN_FLOW_MIN_FACTOR;
      textContentItem.spaceInFlowMax = textState.fontSize * SPACE_IN_FLOW_MAX_FACTOR;
      textContentItem.hasEOL = false;
      textContentItem.initialized = true;
      return textContentItem;
    }
    function updateAdvanceScale() {
      if (!textContentItem.initialized) {
        return;
      }
      const scaleLineX = Math.hypot(textState.textLineMatrix[0], textState.textLineMatrix[1]);
      const scaleCtmX = Math.hypot(textState.ctm[0], textState.ctm[1]);
      const scaleFactor = scaleCtmX * scaleLineX;
      if (scaleFactor === textContentItem.textAdvanceScale) {
        return;
      }
      if (!textContentItem.vertical) {
        textContentItem.totalWidth += textContentItem.width * textContentItem.textAdvanceScale;
        textContentItem.width = 0;
      } else {
        textContentItem.totalHeight += textContentItem.height * textContentItem.textAdvanceScale;
        textContentItem.height = 0;
      }
      textContentItem.textAdvanceScale = scaleFactor;
    }
    function runBidiTransform(textChunk) {
      const text = textChunk.str.join("");
      const bidiResult = (0, _bidi.bidi)(text, -1, textChunk.vertical);
      return {
        str: bidiResult.str,
        dir: bidiResult.dir,
        width: Math.abs(textChunk.totalWidth),
        height: Math.abs(textChunk.totalHeight),
        transform: textChunk.transform,
        fontName: textChunk.fontName,
        hasEOL: textChunk.hasEOL
      };
    }
    function handleSetFont(fontName, fontRef) {
      return self.loadFont(fontName, fontRef, resources).then(function (translated) {
        if (!translated.font.isType3Font) {
          return translated;
        }
        return translated.loadType3Data(self, resources, task).catch(function () {}).then(function () {
          return translated;
        });
      }).then(function (translated) {
        textState.loadedName = translated.loadedName;
        textState.font = translated.font;
        textState.fontMatrix = translated.font.fontMatrix || _util.FONT_IDENTITY_MATRIX;
      });
    }
    function applyInverseRotation(x, y, matrix) {
      const scale = Math.hypot(matrix[0], matrix[1]);
      return [(matrix[0] * x + matrix[1] * y) / scale, (matrix[2] * x + matrix[3] * y) / scale];
    }
    function compareWithLastPosition() {
      const currentTransform = getCurrentTextTransform();
      let posX = currentTransform[4];
      let posY = currentTransform[5];
      const shiftedX = posX - viewBox[0];
      const shiftedY = posY - viewBox[1];
      if (shiftedX < 0 || shiftedX > viewBox[2] || shiftedY < 0 || shiftedY > viewBox[3]) {
        return false;
      }
      if (!combineTextItems || !textState.font || !textContentItem.prevTransform) {
        return true;
      }
      let lastPosX = textContentItem.prevTransform[4];
      let lastPosY = textContentItem.prevTransform[5];
      if (lastPosX === posX && lastPosY === posY) {
        return true;
      }
      let rotate = -1;
      if (currentTransform[0] && currentTransform[1] === 0 && currentTransform[2] === 0) {
        rotate = currentTransform[0] > 0 ? 0 : 180;
      } else if (currentTransform[1] && currentTransform[0] === 0 && currentTransform[3] === 0) {
        rotate = currentTransform[1] > 0 ? 90 : 270;
      }
      switch (rotate) {
        case 0:
          break;
        case 90:
          [posX, posY] = [posY, posX];
          [lastPosX, lastPosY] = [lastPosY, lastPosX];
          break;
        case 180:
          [posX, posY, lastPosX, lastPosY] = [-posX, -posY, -lastPosX, -lastPosY];
          break;
        case 270:
          [posX, posY] = [-posY, -posX];
          [lastPosX, lastPosY] = [-lastPosY, -lastPosX];
          break;
        default:
          [posX, posY] = applyInverseRotation(posX, posY, currentTransform);
          [lastPosX, lastPosY] = applyInverseRotation(lastPosX, lastPosY, textContentItem.prevTransform);
      }
      if (textState.font.vertical) {
        const advanceY = (lastPosY - posY) / textContentItem.textAdvanceScale;
        const advanceX = posX - lastPosX;
        const textOrientation = Math.sign(textContentItem.height);
        if (advanceY < textOrientation * textContentItem.negativeSpaceMax) {
          if (Math.abs(advanceX) > 0.5 * textContentItem.width) {
            appendEOL();
            return true;
          }
          resetLastChars();
          flushTextContentItem();
          return true;
        }
        if (Math.abs(advanceX) > textContentItem.width) {
          appendEOL();
          return true;
        }
        if (advanceY <= textOrientation * textContentItem.notASpace) {
          resetLastChars();
        }
        if (advanceY <= textOrientation * textContentItem.trackingSpaceMin) {
          textContentItem.height += advanceY;
        } else if (!addFakeSpaces(advanceY, textContentItem.prevTransform, textOrientation)) {
          if (textContentItem.str.length === 0) {
            resetLastChars();
            textContent.items.push({
              str: " ",
              dir: "ltr",
              width: 0,
              height: Math.abs(advanceY),
              transform: textContentItem.prevTransform,
              fontName: textContentItem.fontName,
              hasEOL: false
            });
          } else {
            textContentItem.height += advanceY;
          }
        }
        return true;
      }
      const advanceX = (posX - lastPosX) / textContentItem.textAdvanceScale;
      const advanceY = posY - lastPosY;
      const textOrientation = Math.sign(textContentItem.width);
      if (advanceX < textOrientation * textContentItem.negativeSpaceMax) {
        if (Math.abs(advanceY) > 0.5 * textContentItem.height) {
          appendEOL();
          return true;
        }
        resetLastChars();
        flushTextContentItem();
        return true;
      }
      if (Math.abs(advanceY) > textContentItem.height) {
        appendEOL();
        return true;
      }
      if (advanceX <= textOrientation * textContentItem.notASpace) {
        resetLastChars();
      }
      if (advanceX <= textOrientation * textContentItem.trackingSpaceMin) {
        textContentItem.width += advanceX;
      } else if (!addFakeSpaces(advanceX, textContentItem.prevTransform, textOrientation)) {
        if (textContentItem.str.length === 0) {
          resetLastChars();
          textContent.items.push({
            str: " ",
            dir: "ltr",
            width: Math.abs(advanceX),
            height: 0,
            transform: textContentItem.prevTransform,
            fontName: textContentItem.fontName,
            hasEOL: false
          });
        } else {
          textContentItem.width += advanceX;
        }
      }
      return true;
    }
    function buildTextContentItem({
      chars,
      extraSpacing
    }) {
      const font = textState.font;
      if (!chars) {
        const charSpacing = textState.charSpacing + extraSpacing;
        if (charSpacing) {
          if (!font.vertical) {
            textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
          } else {
            textState.translateTextMatrix(0, -charSpacing);
          }
        }
        return;
      }
      const glyphs = font.charsToGlyphs(chars);
      const scale = textState.fontMatrix[0] * textState.fontSize;
      for (let i = 0, ii = glyphs.length; i < ii; i++) {
        const glyph = glyphs[i];
        const {
          category
        } = glyph;
        if (category.isInvisibleFormatMark) {
          continue;
        }
        let charSpacing = textState.charSpacing + (i + 1 === ii ? extraSpacing : 0);
        let glyphWidth = glyph.width;
        if (font.vertical) {
          glyphWidth = glyph.vmetric ? glyph.vmetric[0] : -glyphWidth;
        }
        let scaledDim = glyphWidth * scale;
        if (category.isWhitespace) {
          if (!font.vertical) {
            charSpacing += scaledDim + textState.wordSpacing;
            textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
          } else {
            charSpacing += -scaledDim + textState.wordSpacing;
            textState.translateTextMatrix(0, -charSpacing);
          }
          saveLastChar(" ");
          continue;
        }
        if (!compareWithLastPosition()) {
          continue;
        }
        const textChunk = ensureTextContentItem();
        if (category.isZeroWidthDiacritic) {
          scaledDim = 0;
        }
        if (!font.vertical) {
          scaledDim *= textState.textHScale;
          textState.translateTextMatrix(scaledDim, 0);
          textChunk.width += scaledDim;
        } else {
          textState.translateTextMatrix(0, scaledDim);
          scaledDim = Math.abs(scaledDim);
          textChunk.height += scaledDim;
        }
        if (scaledDim) {
          textChunk.prevTransform = getCurrentTextTransform();
        }
        const glyphUnicode = glyph.normalizedUnicode;
        if (saveLastChar(glyphUnicode)) {
          textChunk.str.push(" ");
        }
        textChunk.str.push(glyphUnicode);
        if (charSpacing) {
          if (!font.vertical) {
            textState.translateTextMatrix(charSpacing * textState.textHScale, 0);
          } else {
            textState.translateTextMatrix(0, -charSpacing);
          }
        }
      }
    }
    function appendEOL() {
      resetLastChars();
      if (textContentItem.initialized) {
        textContentItem.hasEOL = true;
        flushTextContentItem();
      } else {
        textContent.items.push({
          str: "",
          dir: "ltr",
          width: 0,
          height: 0,
          transform: getCurrentTextTransform(),
          fontName: textState.loadedName,
          hasEOL: true
        });
      }
    }
    function addFakeSpaces(width, transf, textOrientation) {
      if (textOrientation * textContentItem.spaceInFlowMin <= width && width <= textOrientation * textContentItem.spaceInFlowMax) {
        if (textContentItem.initialized) {
          resetLastChars();
          textContentItem.str.push(" ");
        }
        return false;
      }
      const fontName = textContentItem.fontName;
      let height = 0;
      if (textContentItem.vertical) {
        height = width;
        width = 0;
      }
      flushTextContentItem();
      resetLastChars();
      textContent.items.push({
        str: " ",
        dir: "ltr",
        width: Math.abs(width),
        height: Math.abs(height),
        transform: transf || getCurrentTextTransform(),
        fontName,
        hasEOL: false
      });
      return true;
    }
    function flushTextContentItem() {
      if (!textContentItem.initialized || !textContentItem.str) {
        return;
      }
      if (!textContentItem.vertical) {
        textContentItem.totalWidth += textContentItem.width * textContentItem.textAdvanceScale;
      } else {
        textContentItem.totalHeight += textContentItem.height * textContentItem.textAdvanceScale;
      }
      textContent.items.push(runBidiTransform(textContentItem));
      textContentItem.initialized = false;
      textContentItem.str.length = 0;
    }
    function enqueueChunk(batch = false) {
      const length = textContent.items.length;
      if (length === 0) {
        return;
      }
      if (batch && length < TEXT_CHUNK_BATCH_SIZE) {
        return;
      }
      sink.enqueue(textContent, length);
      textContent.items = [];
      textContent.styles = Object.create(null);
    }
    const timeSlotManager = new TimeSlotManager();
    return new Promise(function promiseBody(resolve, reject) {
      const next = function (promise) {
        enqueueChunk(true);
        Promise.all([promise, sink.ready]).then(function () {
          try {
            promiseBody(resolve, reject);
          } catch (ex) {
            reject(ex);
          }
        }, reject);
      };
      task.ensureNotTerminated();
      timeSlotManager.reset();
      const operation = {};
      let stop,
        args = [];
      while (!(stop = timeSlotManager.check())) {
        args.length = 0;
        operation.args = args;
        if (!preprocessor.read(operation)) {
          break;
        }
        textState = stateManager.state;
        const fn = operation.fn;
        args = operation.args;
        switch (fn | 0) {
          case _util.OPS.setFont:
            var fontNameArg = args[0].name,
              fontSizeArg = args[1];
            if (textState.font && fontNameArg === textState.fontName && fontSizeArg === textState.fontSize) {
              break;
            }
            flushTextContentItem();
            textState.fontName = fontNameArg;
            textState.fontSize = fontSizeArg;
            next(handleSetFont(fontNameArg, null));
            return;
          case _util.OPS.setTextRise:
            textState.textRise = args[0];
            break;
          case _util.OPS.setHScale:
            textState.textHScale = args[0] / 100;
            break;
          case _util.OPS.setLeading:
            textState.leading = args[0];
            break;
          case _util.OPS.moveText:
            textState.translateTextLineMatrix(args[0], args[1]);
            textState.textMatrix = textState.textLineMatrix.slice();
            break;
          case _util.OPS.setLeadingMoveText:
            textState.leading = -args[1];
            textState.translateTextLineMatrix(args[0], args[1]);
            textState.textMatrix = textState.textLineMatrix.slice();
            break;
          case _util.OPS.nextLine:
            textState.carriageReturn();
            break;
          case _util.OPS.setTextMatrix:
            textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
            textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
            updateAdvanceScale();
            break;
          case _util.OPS.setCharSpacing:
            textState.charSpacing = args[0];
            break;
          case _util.OPS.setWordSpacing:
            textState.wordSpacing = args[0];
            break;
          case _util.OPS.beginText:
            textState.textMatrix = _util.IDENTITY_MATRIX.slice();
            textState.textLineMatrix = _util.IDENTITY_MATRIX.slice();
            break;
          case _util.OPS.showSpacedText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            const spaceFactor = (textState.font.vertical ? 1 : -1) * textState.fontSize / 1000;
            const elements = args[0];
            for (let i = 0, ii = elements.length; i < ii - 1; i++) {
              const item = elements[i];
              if (typeof item === "string") {
                showSpacedTextBuffer.push(item);
              } else if (typeof item === "number" && item !== 0) {
                const str = showSpacedTextBuffer.join("");
                showSpacedTextBuffer.length = 0;
                buildTextContentItem({
                  chars: str,
                  extraSpacing: item * spaceFactor
                });
              }
            }
            const item = elements.at(-1);
            if (typeof item === "string") {
              showSpacedTextBuffer.push(item);
            }
            if (showSpacedTextBuffer.length > 0) {
              const str = showSpacedTextBuffer.join("");
              showSpacedTextBuffer.length = 0;
              buildTextContentItem({
                chars: str,
                extraSpacing: 0
              });
            }
            break;
          case _util.OPS.showText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            buildTextContentItem({
              chars: args[0],
              extraSpacing: 0
            });
            break;
          case _util.OPS.nextLineShowText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            textState.carriageReturn();
            buildTextContentItem({
              chars: args[0],
              extraSpacing: 0
            });
            break;
          case _util.OPS.nextLineSetSpacingShowText:
            if (!stateManager.state.font) {
              self.ensureStateFont(stateManager.state);
              continue;
            }
            textState.wordSpacing = args[0];
            textState.charSpacing = args[1];
            textState.carriageReturn();
            buildTextContentItem({
              chars: args[2],
              extraSpacing: 0
            });
            break;
          case _util.OPS.paintXObject:
            flushTextContentItem();
            if (!xobjs) {
              xobjs = resources.get("XObject") || _primitives.Dict.empty;
            }
            var isValidName = args[0] instanceof _primitives.Name;
            var name = args[0].name;
            if (isValidName && emptyXObjectCache.getByName(name)) {
              break;
            }
            next(new Promise(function (resolveXObject, rejectXObject) {
              if (!isValidName) {
                throw new _util.FormatError("XObject must be referred to by name.");
              }
              let xobj = xobjs.getRaw(name);
              if (xobj instanceof _primitives.Ref) {
                if (emptyXObjectCache.getByRef(xobj)) {
                  resolveXObject();
                  return;
                }
                const globalImage = self.globalImageCache.getData(xobj, self.pageIndex);
                if (globalImage) {
                  resolveXObject();
                  return;
                }
                xobj = xref.fetch(xobj);
              }
              if (!(xobj instanceof _base_stream.BaseStream)) {
                throw new _util.FormatError("XObject should be a stream");
              }
              const type = xobj.dict.get("Subtype");
              if (!(type instanceof _primitives.Name)) {
                throw new _util.FormatError("XObject should have a Name subtype");
              }
              if (type.name !== "Form") {
                emptyXObjectCache.set(name, xobj.dict.objId, true);
                resolveXObject();
                return;
              }
              const currentState = stateManager.state.clone();
              const xObjStateManager = new StateManager(currentState);
              const matrix = xobj.dict.getArray("Matrix");
              if (Array.isArray(matrix) && matrix.length === 6) {
                xObjStateManager.transform(matrix);
              }
              enqueueChunk();
              const sinkWrapper = {
                enqueueInvoked: false,
                enqueue(chunk, size) {
                  this.enqueueInvoked = true;
                  sink.enqueue(chunk, size);
                },
                get desiredSize() {
                  return sink.desiredSize;
                },
                get ready() {
                  return sink.ready;
                }
              };
              self.getTextContent({
                stream: xobj,
                task,
                resources: xobj.dict.get("Resources") || resources,
                stateManager: xObjStateManager,
                combineTextItems,
                includeMarkedContent,
                sink: sinkWrapper,
                seenStyles,
                viewBox,
                markedContentData
              }).then(function () {
                if (!sinkWrapper.enqueueInvoked) {
                  emptyXObjectCache.set(name, xobj.dict.objId, true);
                }
                resolveXObject();
              }, rejectXObject);
            }).catch(function (reason) {
              if (reason instanceof _util.AbortException) {
                return;
              }
              if (self.options.ignoreErrors) {
                (0, _util.warn)(`getTextContent - ignoring XObject: "${reason}".`);
                return;
              }
              throw reason;
            }));
            return;
          case _util.OPS.setGState:
            isValidName = args[0] instanceof _primitives.Name;
            name = args[0].name;
            if (isValidName && emptyGStateCache.getByName(name)) {
              break;
            }
            next(new Promise(function (resolveGState, rejectGState) {
              if (!isValidName) {
                throw new _util.FormatError("GState must be referred to by name.");
              }
              const extGState = resources.get("ExtGState");
              if (!(extGState instanceof _primitives.Dict)) {
                throw new _util.FormatError("ExtGState should be a dictionary.");
              }
              const gState = extGState.get(name);
              if (!(gState instanceof _primitives.Dict)) {
                throw new _util.FormatError("GState should be a dictionary.");
              }
              const gStateFont = gState.get("Font");
              if (!gStateFont) {
                emptyGStateCache.set(name, gState.objId, true);
                resolveGState();
                return;
              }
              flushTextContentItem();
              textState.fontName = null;
              textState.fontSize = gStateFont[1];
              handleSetFont(null, gStateFont[0]).then(resolveGState, rejectGState);
            }).catch(function (reason) {
              if (reason instanceof _util.AbortException) {
                return;
              }
              if (self.options.ignoreErrors) {
                (0, _util.warn)(`getTextContent - ignoring ExtGState: "${reason}".`);
                return;
              }
              throw reason;
            }));
            return;
          case _util.OPS.beginMarkedContent:
            flushTextContentItem();
            if (includeMarkedContent) {
              markedContentData.level++;
              textContent.items.push({
                type: "beginMarkedContent",
                tag: args[0] instanceof _primitives.Name ? args[0].name : null
              });
            }
            break;
          case _util.OPS.beginMarkedContentProps:
            flushTextContentItem();
            if (includeMarkedContent) {
              markedContentData.level++;
              let mcid = null;
              if (args[1] instanceof _primitives.Dict) {
                mcid = args[1].get("MCID");
              }
              textContent.items.push({
                type: "beginMarkedContentProps",
                id: Number.isInteger(mcid) ? `${self.idFactory.getPageObjId()}_mcid${mcid}` : null,
                tag: args[0] instanceof _primitives.Name ? args[0].name : null
              });
            }
            break;
          case _util.OPS.endMarkedContent:
            flushTextContentItem();
            if (includeMarkedContent) {
              if (markedContentData.level === 0) {
                break;
              }
              markedContentData.level--;
              textContent.items.push({
                type: "endMarkedContent"
              });
            }
            break;
        }
        if (textContent.items.length >= sink.desiredSize) {
          stop = true;
          break;
        }
      }
      if (stop) {
        next(deferred);
        return;
      }
      flushTextContentItem();
      enqueueChunk();
      resolve();
    }).catch(reason => {
      if (reason instanceof _util.AbortException) {
        return;
      }
      if (this.options.ignoreErrors) {
        (0, _util.warn)(`getTextContent - ignoring errors during "${task.name}" ` + `task: "${reason}".`);
        flushTextContentItem();
        enqueueChunk();
        return;
      }
      throw reason;
    });
  }
  extractDataStructures(dict, baseDict, properties) {
    const xref = this.xref;
    let cidToGidBytes;
    const toUnicodePromise = this.readToUnicode(properties.toUnicode || dict.get("ToUnicode") || baseDict.get("ToUnicode"));
    if (properties.composite) {
      const cidSystemInfo = dict.get("CIDSystemInfo");
      if (cidSystemInfo instanceof _primitives.Dict) {
        properties.cidSystemInfo = {
          registry: (0, _util.stringToPDFString)(cidSystemInfo.get("Registry")),
          ordering: (0, _util.stringToPDFString)(cidSystemInfo.get("Ordering")),
          supplement: cidSystemInfo.get("Supplement")
        };
      }
      try {
        const cidToGidMap = dict.get("CIDToGIDMap");
        if (cidToGidMap instanceof _base_stream.BaseStream) {
          cidToGidBytes = cidToGidMap.getBytes();
        }
      } catch (ex) {
        if (!this.options.ignoreErrors) {
          throw ex;
        }
        (0, _util.warn)(`extractDataStructures - ignoring CIDToGIDMap data: "${ex}".`);
      }
    }
    const differences = [];
    let baseEncodingName = null;
    let encoding;
    if (dict.has("Encoding")) {
      encoding = dict.get("Encoding");
      if (encoding instanceof _primitives.Dict) {
        baseEncodingName = encoding.get("BaseEncoding");
        baseEncodingName = baseEncodingName instanceof _primitives.Name ? baseEncodingName.name : null;
        if (encoding.has("Differences")) {
          const diffEncoding = encoding.get("Differences");
          let index = 0;
          for (const entry of diffEncoding) {
            const data = xref.fetchIfRef(entry);
            if (typeof data === "number") {
              index = data;
            } else if (data instanceof _primitives.Name) {
              differences[index++] = data.name;
            } else {
              throw new _util.FormatError(`Invalid entry in 'Differences' array: ${data}`);
            }
          }
        }
      } else if (encoding instanceof _primitives.Name) {
        baseEncodingName = encoding.name;
      } else {
        const msg = "Encoding is not a Name nor a Dict";
        if (!this.options.ignoreErrors) {
          throw new _util.FormatError(msg);
        }
        (0, _util.warn)(msg);
      }
      if (baseEncodingName !== "MacRomanEncoding" && baseEncodingName !== "MacExpertEncoding" && baseEncodingName !== "WinAnsiEncoding") {
        baseEncodingName = null;
      }
    }
    if (baseEncodingName) {
      properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName);
    } else {
      const isSymbolicFont = !!(properties.flags & _fonts_utils.FontFlags.Symbolic);
      const isNonsymbolicFont = !!(properties.flags & _fonts_utils.FontFlags.Nonsymbolic);
      encoding = _encodings.StandardEncoding;
      if (properties.type === "TrueType" && !isNonsymbolicFont) {
        encoding = _encodings.WinAnsiEncoding;
      }
      if (isSymbolicFont) {
        encoding = _encodings.MacRomanEncoding;
        if (!properties.file || properties.isInternalFont) {
          if (/Symbol/i.test(properties.name)) {
            encoding = _encodings.SymbolSetEncoding;
          } else if (/Dingbats|Wingdings/i.test(properties.name)) {
            encoding = _encodings.ZapfDingbatsEncoding;
          }
        }
      }
      properties.defaultEncoding = encoding;
    }
    properties.differences = differences;
    properties.baseEncodingName = baseEncodingName;
    properties.hasEncoding = !!baseEncodingName || differences.length > 0;
    properties.dict = dict;
    return toUnicodePromise.then(readToUnicode => {
      properties.toUnicode = readToUnicode;
      return this.buildToUnicode(properties);
    }).then(builtToUnicode => {
      properties.toUnicode = builtToUnicode;
      if (cidToGidBytes) {
        properties.cidToGidMap = this.readCidToGidMap(cidToGidBytes, builtToUnicode);
      }
      return properties;
    });
  }
  _simpleFontToUnicode(properties, forceGlyphs = false) {
    (0, _util.assert)(!properties.composite, "Must be a simple font.");
    const toUnicode = [];
    const encoding = properties.defaultEncoding.slice();
    const baseEncodingName = properties.baseEncodingName;
    const differences = properties.differences;
    for (const charcode in differences) {
      const glyphName = differences[charcode];
      if (glyphName === ".notdef") {
        continue;
      }
      encoding[charcode] = glyphName;
    }
    const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
    for (const charcode in encoding) {
      let glyphName = encoding[charcode];
      if (glyphName === "") {
        continue;
      }
      let unicode = glyphsUnicodeMap[glyphName];
      if (unicode !== undefined) {
        toUnicode[charcode] = String.fromCharCode(unicode);
        continue;
      }
      let code = 0;
      switch (glyphName[0]) {
        case "G":
          if (glyphName.length === 3) {
            code = parseInt(glyphName.substring(1), 16);
          }
          break;
        case "g":
          if (glyphName.length === 5) {
            code = parseInt(glyphName.substring(1), 16);
          }
          break;
        case "C":
        case "c":
          if (glyphName.length >= 3 && glyphName.length <= 4) {
            const codeStr = glyphName.substring(1);
            if (forceGlyphs) {
              code = parseInt(codeStr, 16);
              break;
            }
            code = +codeStr;
            if (Number.isNaN(code) && Number.isInteger(parseInt(codeStr, 16))) {
              return this._simpleFontToUnicode(properties, true);
            }
          }
          break;
        case "u":
          unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
          if (unicode !== -1) {
            code = unicode;
          }
          break;
      }
      if (code > 0 && code <= 0x10ffff && Number.isInteger(code)) {
        if (baseEncodingName && code === +charcode) {
          const baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
          if (baseEncoding && (glyphName = baseEncoding[charcode])) {
            toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
            continue;
          }
        }
        toUnicode[charcode] = String.fromCodePoint(code);
      }
    }
    return toUnicode;
  }
  async buildToUnicode(properties) {
    properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
    if (properties.hasIncludedToUnicodeMap) {
      if (!properties.composite && properties.hasEncoding) {
        properties.fallbackToUnicode = this._simpleFontToUnicode(properties);
      }
      return properties.toUnicode;
    }
    if (!properties.composite) {
      return new _to_unicode_map.ToUnicodeMap(this._simpleFontToUnicode(properties));
    }
    if (properties.composite && (properties.cMap.builtInCMap && !(properties.cMap instanceof _cmap.IdentityCMap) || properties.cidSystemInfo.registry === "Adobe" && (properties.cidSystemInfo.ordering === "GB1" || properties.cidSystemInfo.ordering === "CNS1" || properties.cidSystemInfo.ordering === "Japan1" || properties.cidSystemInfo.ordering === "Korea1"))) {
      const {
        registry,
        ordering
      } = properties.cidSystemInfo;
      const ucs2CMapName = _primitives.Name.get(`${registry}-${ordering}-UCS2`);
      const ucs2CMap = await _cmap.CMapFactory.create({
        encoding: ucs2CMapName,
        fetchBuiltInCMap: this._fetchBuiltInCMapBound,
        useCMap: null
      });
      const toUnicode = [];
      properties.cMap.forEach(function (charcode, cid) {
        if (cid > 0xffff) {
          throw new _util.FormatError("Max size of CID is 65,535");
        }
        const ucs2 = ucs2CMap.lookup(cid);
        if (ucs2) {
          toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
        }
      });
      return new _to_unicode_map.ToUnicodeMap(toUnicode);
    }
    return new _to_unicode_map.IdentityToUnicodeMap(properties.firstChar, properties.lastChar);
  }
  readToUnicode(cmapObj) {
    if (!cmapObj) {
      return Promise.resolve(null);
    }
    if (cmapObj instanceof _primitives.Name) {
      return _cmap.CMapFactory.create({
        encoding: cmapObj,
        fetchBuiltInCMap: this._fetchBuiltInCMapBound,
        useCMap: null
      }).then(function (cmap) {
        if (cmap instanceof _cmap.IdentityCMap) {
          return new _to_unicode_map.IdentityToUnicodeMap(0, 0xffff);
        }
        return new _to_unicode_map.ToUnicodeMap(cmap.getMap());
      });
    } else if (cmapObj instanceof _base_stream.BaseStream) {
      return _cmap.CMapFactory.create({
        encoding: cmapObj,
        fetchBuiltInCMap: this._fetchBuiltInCMapBound,
        useCMap: null
      }).then(function (cmap) {
        if (cmap instanceof _cmap.IdentityCMap) {
          return new _to_unicode_map.IdentityToUnicodeMap(0, 0xffff);
        }
        const map = new Array(cmap.length);
        cmap.forEach(function (charCode, token) {
          if (typeof token === "number") {
            map[charCode] = String.fromCodePoint(token);
            return;
          }
          const str = [];
          for (let k = 0; k < token.length; k += 2) {
            const w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
            if ((w1 & 0xf800) !== 0xd800) {
              str.push(w1);
              continue;
            }
            k += 2;
            const w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
            str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
          }
          map[charCode] = String.fromCodePoint(...str);
        });
        return new _to_unicode_map.ToUnicodeMap(map);
      }, reason => {
        if (reason instanceof _util.AbortException) {
          return null;
        }
        if (this.options.ignoreErrors) {
          this.handler.send("UnsupportedFeature", {
            featureId: _util.UNSUPPORTED_FEATURES.errorFontToUnicode
          });
          (0, _util.warn)(`readToUnicode - ignoring ToUnicode data: "${reason}".`);
          return null;
        }
        throw reason;
      });
    }
    return Promise.resolve(null);
  }
  readCidToGidMap(glyphsData, toUnicode) {
    const result = [];
    for (let j = 0, jj = glyphsData.length; j < jj; j++) {
      const glyphID = glyphsData[j++] << 8 | glyphsData[j];
      const code = j >> 1;
      if (glyphID === 0 && !toUnicode.has(code)) {
        continue;
      }
      result[code] = glyphID;
    }
    return result;
  }
  extractWidths(dict, descriptor, properties) {
    const xref = this.xref;
    let glyphsWidths = [];
    let defaultWidth = 0;
    const glyphsVMetrics = [];
    let defaultVMetrics;
    let i, ii, j, jj, start, code, widths;
    if (properties.composite) {
      defaultWidth = dict.has("DW") ? dict.get("DW") : 1000;
      widths = dict.get("W");
      if (widths) {
        for (i = 0, ii = widths.length; i < ii; i++) {
          start = xref.fetchIfRef(widths[i++]);
          code = xref.fetchIfRef(widths[i]);
          if (Array.isArray(code)) {
            for (j = 0, jj = code.length; j < jj; j++) {
              glyphsWidths[start++] = xref.fetchIfRef(code[j]);
            }
          } else {
            const width = xref.fetchIfRef(widths[++i]);
            for (j = start; j <= code; j++) {
              glyphsWidths[j] = width;
            }
          }
        }
      }
      if (properties.vertical) {
        let vmetrics = dict.getArray("DW2") || [880, -1000];
        defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
        vmetrics = dict.get("W2");
        if (vmetrics) {
          for (i = 0, ii = vmetrics.length; i < ii; i++) {
            start = xref.fetchIfRef(vmetrics[i++]);
            code = xref.fetchIfRef(vmetrics[i]);
            if (Array.isArray(code)) {
              for (j = 0, jj = code.length; j < jj; j++) {
                glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
              }
            } else {
              const vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
              for (j = start; j <= code; j++) {
                glyphsVMetrics[j] = vmetric;
              }
            }
          }
        }
      }
    } else {
      const firstChar = properties.firstChar;
      widths = dict.get("Widths");
      if (widths) {
        j = firstChar;
        for (i = 0, ii = widths.length; i < ii; i++) {
          glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
        }
        defaultWidth = parseFloat(descriptor.get("MissingWidth")) || 0;
      } else {
        const baseFontName = dict.get("BaseFont");
        if (baseFontName instanceof _primitives.Name) {
          const metrics = this.getBaseFontMetrics(baseFontName.name);
          glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
          defaultWidth = metrics.defaultWidth;
        }
      }
    }
    let isMonospace = true;
    let firstWidth = defaultWidth;
    for (const glyph in glyphsWidths) {
      const glyphWidth = glyphsWidths[glyph];
      if (!glyphWidth) {
        continue;
      }
      if (!firstWidth) {
        firstWidth = glyphWidth;
        continue;
      }
      if (firstWidth !== glyphWidth) {
        isMonospace = false;
        break;
      }
    }
    if (isMonospace) {
      properties.flags |= _fonts_utils.FontFlags.FixedPitch;
    }
    properties.defaultWidth = defaultWidth;
    properties.widths = glyphsWidths;
    properties.defaultVMetrics = defaultVMetrics;
    properties.vmetrics = glyphsVMetrics;
  }
  isSerifFont(baseFontName) {
    const fontNameWoStyle = baseFontName.split("-")[0];
    return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || /serif/gi.test(fontNameWoStyle);
  }
  getBaseFontMetrics(name) {
    let defaultWidth = 0;
    let widths = Object.create(null);
    let monospace = false;
    const stdFontMap = (0, _standard_fonts.getStdFontMap)();
    let lookupName = stdFontMap[name] || name;
    const Metrics = (0, _metrics.getMetrics)();
    if (!(lookupName in Metrics)) {
      if (this.isSerifFont(name)) {
        lookupName = "Times-Roman";
      } else {
        lookupName = "Helvetica";
      }
    }
    const glyphWidths = Metrics[lookupName];
    if (typeof glyphWidths === "number") {
      defaultWidth = glyphWidths;
      monospace = true;
    } else {
      widths = glyphWidths();
    }
    return {
      defaultWidth,
      monospace,
      widths
    };
  }
  buildCharCodeToWidth(widthsByGlyphName, properties) {
    const widths = Object.create(null);
    const differences = properties.differences;
    const encoding = properties.defaultEncoding;
    for (let charCode = 0; charCode < 256; charCode++) {
      if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
        widths[charCode] = widthsByGlyphName[differences[charCode]];
        continue;
      }
      if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
        widths[charCode] = widthsByGlyphName[encoding[charCode]];
        continue;
      }
    }
    return widths;
  }
  preEvaluateFont(dict) {
    const baseDict = dict;
    let type = dict.get("Subtype");
    if (!(type instanceof _primitives.Name)) {
      throw new _util.FormatError("invalid font Subtype");
    }
    let composite = false;
    let hash, toUnicode;
    if (type.name === "Type0") {
      const df = dict.get("DescendantFonts");
      if (!df) {
        throw new _util.FormatError("Descendant fonts are not specified");
      }
      dict = Array.isArray(df) ? this.xref.fetchIfRef(df[0]) : df;
      if (!(dict instanceof _primitives.Dict)) {
        throw new _util.FormatError("Descendant font is not a dictionary.");
      }
      type = dict.get("Subtype");
      if (!(type instanceof _primitives.Name)) {
        throw new _util.FormatError("invalid font Subtype");
      }
      composite = true;
    }
    const firstChar = dict.get("FirstChar") || 0,
      lastChar = dict.get("LastChar") || (composite ? 0xffff : 0xff);
    const descriptor = dict.get("FontDescriptor");
    if (descriptor) {
      hash = new _murmurhash.MurmurHash3_64();
      const encoding = baseDict.getRaw("Encoding");
      if (encoding instanceof _primitives.Name) {
        hash.update(encoding.name);
      } else if (encoding instanceof _primitives.Ref) {
        hash.update(encoding.toString());
      } else if (encoding instanceof _primitives.Dict) {
        for (const entry of encoding.getRawValues()) {
          if (entry instanceof _primitives.Name) {
            hash.update(entry.name);
          } else if (entry instanceof _primitives.Ref) {
            hash.update(entry.toString());
          } else if (Array.isArray(entry)) {
            const diffLength = entry.length,
              diffBuf = new Array(diffLength);
            for (let j = 0; j < diffLength; j++) {
              const diffEntry = entry[j];
              if (diffEntry instanceof _primitives.Name) {
                diffBuf[j] = diffEntry.name;
              } else if (typeof diffEntry === "number" || diffEntry instanceof _primitives.Ref) {
                diffBuf[j] = diffEntry.toString();
              }
            }
            hash.update(diffBuf.join());
          }
        }
      }
      hash.update(`${firstChar}-${lastChar}`);
      toUnicode = dict.get("ToUnicode") || baseDict.get("ToUnicode");
      if (toUnicode instanceof _base_stream.BaseStream) {
        const stream = toUnicode.str || toUnicode;
        const uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
        hash.update(uint8array);
      } else if (toUnicode instanceof _primitives.Name) {
        hash.update(toUnicode.name);
      }
      const widths = dict.get("Widths") || baseDict.get("Widths");
      if (Array.isArray(widths)) {
        const widthsBuf = [];
        for (const entry of widths) {
          if (typeof entry === "number" || entry instanceof _primitives.Ref) {
            widthsBuf.push(entry.toString());
          }
        }
        hash.update(widthsBuf.join());
      }
      if (composite) {
        hash.update("compositeFont");
        const compositeWidths = dict.get("W") || baseDict.get("W");
        if (Array.isArray(compositeWidths)) {
          const widthsBuf = [];
          for (const entry of compositeWidths) {
            if (typeof entry === "number" || entry instanceof _primitives.Ref) {
              widthsBuf.push(entry.toString());
            } else if (Array.isArray(entry)) {
              const subWidthsBuf = [];
              for (const element of entry) {
                if (typeof element === "number" || element instanceof _primitives.Ref) {
                  subWidthsBuf.push(element.toString());
                }
              }
              widthsBuf.push(`[${subWidthsBuf.join()}]`);
            }
          }
          hash.update(widthsBuf.join());
        }
        const cidToGidMap = dict.getRaw("CIDToGIDMap") || baseDict.getRaw("CIDToGIDMap");
        if (cidToGidMap instanceof _primitives.Name) {
          hash.update(cidToGidMap.name);
        } else if (cidToGidMap instanceof _primitives.Ref) {
          hash.update(cidToGidMap.toString());
        } else if (cidToGidMap instanceof _base_stream.BaseStream) {
          hash.update(cidToGidMap.peekBytes());
        }
      }
    }
    return {
      descriptor,
      dict,
      baseDict,
      composite,
      type: type.name,
      firstChar,
      lastChar,
      toUnicode,
      hash: hash ? hash.hexdigest() : ""
    };
  }
  async translateFont({
    descriptor,
    dict,
    baseDict,
    composite,
    type,
    firstChar,
    lastChar,
    toUnicode,
    cssFontInfo
  }) {
    const isType3Font = type === "Type3";
    let properties;
    if (!descriptor) {
      if (isType3Font) {
        descriptor = new _primitives.Dict(null);
        descriptor.set("FontName", _primitives.Name.get(type));
        descriptor.set("FontBBox", dict.getArray("FontBBox") || [0, 0, 0, 0]);
      } else {
        let baseFontName = dict.get("BaseFont");
        if (!(baseFontName instanceof _primitives.Name)) {
          throw new _util.FormatError("Base font is not specified");
        }
        baseFontName = baseFontName.name.replace(/[,_]/g, "-");
        const metrics = this.getBaseFontMetrics(baseFontName);
        const fontNameWoStyle = baseFontName.split("-")[0];
        const flags = (this.isSerifFont(fontNameWoStyle) ? _fonts_utils.FontFlags.Serif : 0) | (metrics.monospace ? _fonts_utils.FontFlags.FixedPitch : 0) | ((0, _standard_fonts.getSymbolsFonts)()[fontNameWoStyle] ? _fonts_utils.FontFlags.Symbolic : _fonts_utils.FontFlags.Nonsymbolic);
        properties = {
          type,
          name: baseFontName,
          loadedName: baseDict.loadedName,
          widths: metrics.widths,
          defaultWidth: metrics.defaultWidth,
          isSimulatedFlags: true,
          flags,
          firstChar,
          lastChar,
          toUnicode,
          xHeight: 0,
          capHeight: 0,
          italicAngle: 0,
          isType3Font
        };
        const widths = dict.get("Widths");
        const standardFontName = (0, _standard_fonts.getStandardFontName)(baseFontName);
        let file = null;
        if (standardFontName) {
          properties.isStandardFont = true;
          file = await this.fetchStandardFontData(standardFontName);
          properties.isInternalFont = !!file;
        }
        return this.extractDataStructures(dict, dict, properties).then(newProperties => {
          if (widths) {
            const glyphWidths = [];
            let j = firstChar;
            for (const width of widths) {
              glyphWidths[j++] = this.xref.fetchIfRef(width);
            }
            newProperties.widths = glyphWidths;
          } else {
            newProperties.widths = this.buildCharCodeToWidth(metrics.widths, newProperties);
          }
          return new _fonts.Font(baseFontName, file, newProperties);
        });
      }
    }
    let fontName = descriptor.get("FontName");
    let baseFont = dict.get("BaseFont");
    if (typeof fontName === "string") {
      fontName = _primitives.Name.get(fontName);
    }
    if (typeof baseFont === "string") {
      baseFont = _primitives.Name.get(baseFont);
    }
    if (!isType3Font) {
      const fontNameStr = fontName && fontName.name;
      const baseFontStr = baseFont && baseFont.name;
      if (fontNameStr !== baseFontStr) {
        (0, _util.info)(`The FontDescriptor's FontName is "${fontNameStr}" but ` + `should be the same as the Font's BaseFont "${baseFontStr}".`);
        if (fontNameStr && baseFontStr && baseFontStr.startsWith(fontNameStr)) {
          fontName = baseFont;
        }
      }
    }
    fontName = fontName || baseFont;
    if (!(fontName instanceof _primitives.Name)) {
      throw new _util.FormatError("invalid font name");
    }
    let fontFile, subtype, length1, length2, length3;
    try {
      fontFile = descriptor.get("FontFile", "FontFile2", "FontFile3");
    } catch (ex) {
      if (!this.options.ignoreErrors) {
        throw ex;
      }
      (0, _util.warn)(`translateFont - fetching "${fontName.name}" font file: "${ex}".`);
      fontFile = new _stream.NullStream();
    }
    let isStandardFont = false;
    let isInternalFont = false;
    let glyphScaleFactors = null;
    if (fontFile) {
      if (fontFile.dict) {
        const subtypeEntry = fontFile.dict.get("Subtype");
        if (subtypeEntry instanceof _primitives.Name) {
          subtype = subtypeEntry.name;
        }
        length1 = fontFile.dict.get("Length1");
        length2 = fontFile.dict.get("Length2");
        length3 = fontFile.dict.get("Length3");
      }
    } else if (cssFontInfo) {
      const standardFontName = (0, _xfa_fonts.getXfaFontName)(fontName.name);
      if (standardFontName) {
        cssFontInfo.fontFamily = `${cssFontInfo.fontFamily}-PdfJS-XFA`;
        cssFontInfo.metrics = standardFontName.metrics || null;
        glyphScaleFactors = standardFontName.factors || null;
        fontFile = await this.fetchStandardFontData(standardFontName.name);
        isInternalFont = !!fontFile;
        baseDict = dict = (0, _xfa_fonts.getXfaFontDict)(fontName.name);
        composite = true;
      }
    } else if (!isType3Font) {
      const standardFontName = (0, _standard_fonts.getStandardFontName)(fontName.name);
      if (standardFontName) {
        isStandardFont = true;
        fontFile = await this.fetchStandardFontData(standardFontName);
        isInternalFont = !!fontFile;
      }
    }
    properties = {
      type,
      name: fontName.name,
      subtype,
      file: fontFile,
      length1,
      length2,
      length3,
      isStandardFont,
      isInternalFont,
      loadedName: baseDict.loadedName,
      composite,
      fixedPitch: false,
      fontMatrix: dict.getArray("FontMatrix") || _util.FONT_IDENTITY_MATRIX,
      firstChar,
      lastChar,
      toUnicode,
      bbox: descriptor.getArray("FontBBox") || dict.getArray("FontBBox"),
      ascent: descriptor.get("Ascent"),
      descent: descriptor.get("Descent"),
      xHeight: descriptor.get("XHeight") || 0,
      capHeight: descriptor.get("CapHeight") || 0,
      flags: descriptor.get("Flags"),
      italicAngle: descriptor.get("ItalicAngle") || 0,
      isType3Font,
      cssFontInfo,
      scaleFactors: glyphScaleFactors
    };
    if (composite) {
      const cidEncoding = baseDict.get("Encoding");
      if (cidEncoding instanceof _primitives.Name) {
        properties.cidEncoding = cidEncoding.name;
      }
      const cMap = await _cmap.CMapFactory.create({
        encoding: cidEncoding,
        fetchBuiltInCMap: this._fetchBuiltInCMapBound,
        useCMap: null
      });
      properties.cMap = cMap;
      properties.vertical = properties.cMap.vertical;
    }
    return this.extractDataStructures(dict, baseDict, properties).then(newProperties => {
      this.extractWidths(dict, descriptor, newProperties);
      return new _fonts.Font(fontName.name, fontFile, newProperties);
    });
  }
  static buildFontPaths(font, glyphs, handler, evaluatorOptions) {
    function buildPath(fontChar) {
      const glyphName = `${font.loadedName}_path_${fontChar}`;
      try {
        if (font.renderer.hasBuiltPath(fontChar)) {
          return;
        }
        handler.send("commonobj", [glyphName, "FontPath", font.renderer.getPathJs(fontChar)]);
      } catch (reason) {
        if (evaluatorOptions.ignoreErrors) {
          handler.send("UnsupportedFeature", {
            featureId: _util.UNSUPPORTED_FEATURES.errorFontBuildPath
          });
          (0, _util.warn)(`buildFontPaths - ignoring ${glyphName} glyph: "${reason}".`);
          return;
        }
        throw reason;
      }
    }
    for (const glyph of glyphs) {
      buildPath(glyph.fontChar);
      const accent = glyph.accent;
      if (accent && accent.fontChar) {
        buildPath(accent.fontChar);
      }
    }
  }
  static get fallbackFontDict() {
    const dict = new _primitives.Dict();
    dict.set("BaseFont", _primitives.Name.get("PDFJS-FallbackFont"));
    dict.set("Type", _primitives.Name.get("FallbackType"));
    dict.set("Subtype", _primitives.Name.get("FallbackType"));
    dict.set("Encoding", _primitives.Name.get("WinAnsiEncoding"));
    return (0, _util.shadow)(this, "fallbackFontDict", dict);
  }
}
exports.PartialEvaluator = PartialEvaluator;
class TranslatedFont {
  constructor({
    loadedName,
    font,
    dict,
    evaluatorOptions
  }) {
    this.loadedName = loadedName;
    this.font = font;
    this.dict = dict;
    this._evaluatorOptions = evaluatorOptions || DefaultPartialEvaluatorOptions;
    this.type3Loaded = null;
    this.type3Dependencies = font.isType3Font ? new Set() : null;
    this.sent = false;
  }
  send(handler) {
    if (this.sent) {
      return;
    }
    this.sent = true;
    handler.send("commonobj", [this.loadedName, "Font", this.font.exportData(this._evaluatorOptions.fontExtraProperties)]);
  }
  fallback(handler) {
    if (!this.font.data) {
      return;
    }
    this.font.disableFontFace = true;
    PartialEvaluator.buildFontPaths(this.font, this.font.glyphCacheValues, handler, this._evaluatorOptions);
  }
  loadType3Data(evaluator, resources, task) {
    if (this.type3Loaded) {
      return this.type3Loaded;
    }
    if (!this.font.isType3Font) {
      throw new Error("Must be a Type3 font.");
    }
    const type3Evaluator = evaluator.clone({
      ignoreErrors: false
    });
    type3Evaluator.parsingType3Font = true;
    const type3FontRefs = new _primitives.RefSet(evaluator.type3FontRefs);
    if (this.dict.objId && !type3FontRefs.has(this.dict.objId)) {
      type3FontRefs.put(this.dict.objId);
    }
    type3Evaluator.type3FontRefs = type3FontRefs;
    const translatedFont = this.font,
      type3Dependencies = this.type3Dependencies;
    let loadCharProcsPromise = Promise.resolve();
    const charProcs = this.dict.get("CharProcs");
    const fontResources = this.dict.get("Resources") || resources;
    const charProcOperatorList = Object.create(null);
    const fontBBox = _util.Util.normalizeRect(translatedFont.bbox || [0, 0, 0, 0]),
      width = fontBBox[2] - fontBBox[0],
      height = fontBBox[3] - fontBBox[1];
    const fontBBoxSize = Math.hypot(width, height);
    for (const key of charProcs.getKeys()) {
      loadCharProcsPromise = loadCharProcsPromise.then(() => {
        const glyphStream = charProcs.get(key);
        const operatorList = new _operator_list.OperatorList();
        return type3Evaluator.getOperatorList({
          stream: glyphStream,
          task,
          resources: fontResources,
          operatorList
        }).then(() => {
          if (operatorList.fnArray[0] === _util.OPS.setCharWidthAndBounds) {
            this._removeType3ColorOperators(operatorList, fontBBoxSize);
          }
          charProcOperatorList[key] = operatorList.getIR();
          for (const dependency of operatorList.dependencies) {
            type3Dependencies.add(dependency);
          }
        }).catch(function (reason) {
          (0, _util.warn)(`Type3 font resource "${key}" is not available.`);
          const dummyOperatorList = new _operator_list.OperatorList();
          charProcOperatorList[key] = dummyOperatorList.getIR();
        });
      });
    }
    this.type3Loaded = loadCharProcsPromise.then(() => {
      translatedFont.charProcOperatorList = charProcOperatorList;
      if (this._bbox) {
        translatedFont.isCharBBox = true;
        translatedFont.bbox = this._bbox;
      }
    });
    return this.type3Loaded;
  }
  _removeType3ColorOperators(operatorList, fontBBoxSize = NaN) {
    const charBBox = _util.Util.normalizeRect(operatorList.argsArray[0].slice(2)),
      width = charBBox[2] - charBBox[0],
      height = charBBox[3] - charBBox[1];
    const charBBoxSize = Math.hypot(width, height);
    if (width === 0 || height === 0) {
      operatorList.fnArray.splice(0, 1);
      operatorList.argsArray.splice(0, 1);
    } else if (fontBBoxSize === 0 || Math.round(charBBoxSize / fontBBoxSize) >= 10) {
      if (!this._bbox) {
        this._bbox = [Infinity, Infinity, -Infinity, -Infinity];
      }
      this._bbox[0] = Math.min(this._bbox[0], charBBox[0]);
      this._bbox[1] = Math.min(this._bbox[1], charBBox[1]);
      this._bbox[2] = Math.max(this._bbox[2], charBBox[2]);
      this._bbox[3] = Math.max(this._bbox[3], charBBox[3]);
    }
    let i = 0,
      ii = operatorList.length;
    while (i < ii) {
      switch (operatorList.fnArray[i]) {
        case _util.OPS.setCharWidthAndBounds:
          break;
        case _util.OPS.setStrokeColorSpace:
        case _util.OPS.setFillColorSpace:
        case _util.OPS.setStrokeColor:
        case _util.OPS.setStrokeColorN:
        case _util.OPS.setFillColor:
        case _util.OPS.setFillColorN:
        case _util.OPS.setStrokeGray:
        case _util.OPS.setFillGray:
        case _util.OPS.setStrokeRGBColor:
        case _util.OPS.setFillRGBColor:
        case _util.OPS.setStrokeCMYKColor:
        case _util.OPS.setFillCMYKColor:
        case _util.OPS.shadingFill:
        case _util.OPS.setRenderingIntent:
          operatorList.fnArray.splice(i, 1);
          operatorList.argsArray.splice(i, 1);
          ii--;
          continue;
        case _util.OPS.setGState:
          const [gStateObj] = operatorList.argsArray[i];
          let j = 0,
            jj = gStateObj.length;
          while (j < jj) {
            const [gStateKey] = gStateObj[j];
            switch (gStateKey) {
              case "TR":
              case "TR2":
              case "HT":
              case "BG":
              case "BG2":
              case "UCR":
              case "UCR2":
                gStateObj.splice(j, 1);
                jj--;
                continue;
            }
            j++;
          }
          break;
      }
      i++;
    }
  }
}
class StateManager {
  constructor(initialState = new EvalState()) {
    this.state = initialState;
    this.stateStack = [];
  }
  save() {
    const old = this.state;
    this.stateStack.push(this.state);
    this.state = old.clone();
  }
  restore() {
    const prev = this.stateStack.pop();
    if (prev) {
      this.state = prev;
    }
  }
  transform(args) {
    this.state.ctm = _util.Util.transform(this.state.ctm, args);
  }
}
class TextState {
  constructor() {
    this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
    this.fontName = null;
    this.fontSize = 0;
    this.loadedName = null;
    this.font = null;
    this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
    this.textMatrix = _util.IDENTITY_MATRIX.slice();
    this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
    this.charSpacing = 0;
    this.wordSpacing = 0;
    this.leading = 0;
    this.textHScale = 1;
    this.textRise = 0;
  }
  setTextMatrix(a, b, c, d, e, f) {
    const m = this.textMatrix;
    m[0] = a;
    m[1] = b;
    m[2] = c;
    m[3] = d;
    m[4] = e;
    m[5] = f;
  }
  setTextLineMatrix(a, b, c, d, e, f) {
    const m = this.textLineMatrix;
    m[0] = a;
    m[1] = b;
    m[2] = c;
    m[3] = d;
    m[4] = e;
    m[5] = f;
  }
  translateTextMatrix(x, y) {
    const m = this.textMatrix;
    m[4] = m[0] * x + m[2] * y + m[4];
    m[5] = m[1] * x + m[3] * y + m[5];
  }
  translateTextLineMatrix(x, y) {
    const m = this.textLineMatrix;
    m[4] = m[0] * x + m[2] * y + m[4];
    m[5] = m[1] * x + m[3] * y + m[5];
  }
  carriageReturn() {
    this.translateTextLineMatrix(0, -this.leading);
    this.textMatrix = this.textLineMatrix.slice();
  }
  clone() {
    const clone = Object.create(this);
    clone.textMatrix = this.textMatrix.slice();
    clone.textLineMatrix = this.textLineMatrix.slice();
    clone.fontMatrix = this.fontMatrix.slice();
    return clone;
  }
}
class EvalState {
  constructor() {
    this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
    this.font = null;
    this.textRenderingMode = _util.TextRenderingMode.FILL;
    this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
    this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  }
  clone() {
    return Object.create(this);
  }
}
class EvaluatorPreprocessor {
  static get opMap() {
    const getOPMap = (0, _core_utils.getLookupTableFactory)(function (t) {
      t.w = {
        id: _util.OPS.setLineWidth,
        numArgs: 1,
        variableArgs: false
      };
      t.J = {
        id: _util.OPS.setLineCap,
        numArgs: 1,
        variableArgs: false
      };
      t.j = {
        id: _util.OPS.setLineJoin,
        numArgs: 1,
        variableArgs: false
      };
      t.M = {
        id: _util.OPS.setMiterLimit,
        numArgs: 1,
        variableArgs: false
      };
      t.d = {
        id: _util.OPS.setDash,
        numArgs: 2,
        variableArgs: false
      };
      t.ri = {
        id: _util.OPS.setRenderingIntent,
        numArgs: 1,
        variableArgs: false
      };
      t.i = {
        id: _util.OPS.setFlatness,
        numArgs: 1,
        variableArgs: false
      };
      t.gs = {
        id: _util.OPS.setGState,
        numArgs: 1,
        variableArgs: false
      };
      t.q = {
        id: _util.OPS.save,
        numArgs: 0,
        variableArgs: false
      };
      t.Q = {
        id: _util.OPS.restore,
        numArgs: 0,
        variableArgs: false
      };
      t.cm = {
        id: _util.OPS.transform,
        numArgs: 6,
        variableArgs: false
      };
      t.m = {
        id: _util.OPS.moveTo,
        numArgs: 2,
        variableArgs: false
      };
      t.l = {
        id: _util.OPS.lineTo,
        numArgs: 2,
        variableArgs: false
      };
      t.c = {
        id: _util.OPS.curveTo,
        numArgs: 6,
        variableArgs: false
      };
      t.v = {
        id: _util.OPS.curveTo2,
        numArgs: 4,
        variableArgs: false
      };
      t.y = {
        id: _util.OPS.curveTo3,
        numArgs: 4,
        variableArgs: false
      };
      t.h = {
        id: _util.OPS.closePath,
        numArgs: 0,
        variableArgs: false
      };
      t.re = {
        id: _util.OPS.rectangle,
        numArgs: 4,
        variableArgs: false
      };
      t.S = {
        id: _util.OPS.stroke,
        numArgs: 0,
        variableArgs: false
      };
      t.s = {
        id: _util.OPS.closeStroke,
        numArgs: 0,
        variableArgs: false
      };
      t.f = {
        id: _util.OPS.fill,
        numArgs: 0,
        variableArgs: false
      };
      t.F = {
        id: _util.OPS.fill,
        numArgs: 0,
        variableArgs: false
      };
      t["f*"] = {
        id: _util.OPS.eoFill,
        numArgs: 0,
        variableArgs: false
      };
      t.B = {
        id: _util.OPS.fillStroke,
        numArgs: 0,
        variableArgs: false
      };
      t["B*"] = {
        id: _util.OPS.eoFillStroke,
        numArgs: 0,
        variableArgs: false
      };
      t.b = {
        id: _util.OPS.closeFillStroke,
        numArgs: 0,
        variableArgs: false
      };
      t["b*"] = {
        id: _util.OPS.closeEOFillStroke,
        numArgs: 0,
        variableArgs: false
      };
      t.n = {
        id: _util.OPS.endPath,
        numArgs: 0,
        variableArgs: false
      };
      t.W = {
        id: _util.OPS.clip,
        numArgs: 0,
        variableArgs: false
      };
      t["W*"] = {
        id: _util.OPS.eoClip,
        numArgs: 0,
        variableArgs: false
      };
      t.BT = {
        id: _util.OPS.beginText,
        numArgs: 0,
        variableArgs: false
      };
      t.ET = {
        id: _util.OPS.endText,
        numArgs: 0,
        variableArgs: false
      };
      t.Tc = {
        id: _util.OPS.setCharSpacing,
        numArgs: 1,
        variableArgs: false
      };
      t.Tw = {
        id: _util.OPS.setWordSpacing,
        numArgs: 1,
        variableArgs: false
      };
      t.Tz = {
        id: _util.OPS.setHScale,
        numArgs: 1,
        variableArgs: false
      };
      t.TL = {
        id: _util.OPS.setLeading,
        numArgs: 1,
        variableArgs: false
      };
      t.Tf = {
        id: _util.OPS.setFont,
        numArgs: 2,
        variableArgs: false
      };
      t.Tr = {
        id: _util.OPS.setTextRenderingMode,
        numArgs: 1,
        variableArgs: false
      };
      t.Ts = {
        id: _util.OPS.setTextRise,
        numArgs: 1,
        variableArgs: false
      };
      t.Td = {
        id: _util.OPS.moveText,
        numArgs: 2,
        variableArgs: false
      };
      t.TD = {
        id: _util.OPS.setLeadingMoveText,
        numArgs: 2,
        variableArgs: false
      };
      t.Tm = {
        id: _util.OPS.setTextMatrix,
        numArgs: 6,
        variableArgs: false
      };
      t["T*"] = {
        id: _util.OPS.nextLine,
        numArgs: 0,
        variableArgs: false
      };
      t.Tj = {
        id: _util.OPS.showText,
        numArgs: 1,
        variableArgs: false
      };
      t.TJ = {
        id: _util.OPS.showSpacedText,
        numArgs: 1,
        variableArgs: false
      };
      t["'"] = {
        id: _util.OPS.nextLineShowText,
        numArgs: 1,
        variableArgs: false
      };
      t['"'] = {
        id: _util.OPS.nextLineSetSpacingShowText,
        numArgs: 3,
        variableArgs: false
      };
      t.d0 = {
        id: _util.OPS.setCharWidth,
        numArgs: 2,
        variableArgs: false
      };
      t.d1 = {
        id: _util.OPS.setCharWidthAndBounds,
        numArgs: 6,
        variableArgs: false
      };
      t.CS = {
        id: _util.OPS.setStrokeColorSpace,
        numArgs: 1,
        variableArgs: false
      };
      t.cs = {
        id: _util.OPS.setFillColorSpace,
        numArgs: 1,
        variableArgs: false
      };
      t.SC = {
        id: _util.OPS.setStrokeColor,
        numArgs: 4,
        variableArgs: true
      };
      t.SCN = {
        id: _util.OPS.setStrokeColorN,
        numArgs: 33,
        variableArgs: true
      };
      t.sc = {
        id: _util.OPS.setFillColor,
        numArgs: 4,
        variableArgs: true
      };
      t.scn = {
        id: _util.OPS.setFillColorN,
        numArgs: 33,
        variableArgs: true
      };
      t.G = {
        id: _util.OPS.setStrokeGray,
        numArgs: 1,
        variableArgs: false
      };
      t.g = {
        id: _util.OPS.setFillGray,
        numArgs: 1,
        variableArgs: false
      };
      t.RG = {
        id: _util.OPS.setStrokeRGBColor,
        numArgs: 3,
        variableArgs: false
      };
      t.rg = {
        id: _util.OPS.setFillRGBColor,
        numArgs: 3,
        variableArgs: false
      };
      t.K = {
        id: _util.OPS.setStrokeCMYKColor,
        numArgs: 4,
        variableArgs: false
      };
      t.k = {
        id: _util.OPS.setFillCMYKColor,
        numArgs: 4,
        variableArgs: false
      };
      t.sh = {
        id: _util.OPS.shadingFill,
        numArgs: 1,
        variableArgs: false
      };
      t.BI = {
        id: _util.OPS.beginInlineImage,
        numArgs: 0,
        variableArgs: false
      };
      t.ID = {
        id: _util.OPS.beginImageData,
        numArgs: 0,
        variableArgs: false
      };
      t.EI = {
        id: _util.OPS.endInlineImage,
        numArgs: 1,
        variableArgs: false
      };
      t.Do = {
        id: _util.OPS.paintXObject,
        numArgs: 1,
        variableArgs: false
      };
      t.MP = {
        id: _util.OPS.markPoint,
        numArgs: 1,
        variableArgs: false
      };
      t.DP = {
        id: _util.OPS.markPointProps,
        numArgs: 2,
        variableArgs: false
      };
      t.BMC = {
        id: _util.OPS.beginMarkedContent,
        numArgs: 1,
        variableArgs: false
      };
      t.BDC = {
        id: _util.OPS.beginMarkedContentProps,
        numArgs: 2,
        variableArgs: false
      };
      t.EMC = {
        id: _util.OPS.endMarkedContent,
        numArgs: 0,
        variableArgs: false
      };
      t.BX = {
        id: _util.OPS.beginCompat,
        numArgs: 0,
        variableArgs: false
      };
      t.EX = {
        id: _util.OPS.endCompat,
        numArgs: 0,
        variableArgs: false
      };
      t.BM = null;
      t.BD = null;
      t.true = null;
      t.fa = null;
      t.fal = null;
      t.fals = null;
      t.false = null;
      t.nu = null;
      t.nul = null;
      t.null = null;
    });
    return (0, _util.shadow)(this, "opMap", getOPMap());
  }
  static get MAX_INVALID_PATH_OPS() {
    return (0, _util.shadow)(this, "MAX_INVALID_PATH_OPS", 10);
  }
  constructor(stream, xref, stateManager = new StateManager()) {
    this.parser = new _parser.Parser({
      lexer: new _parser.Lexer(stream, EvaluatorPreprocessor.opMap),
      xref
    });
    this.stateManager = stateManager;
    this.nonProcessedArgs = [];
    this._isPathOp = false;
    this._numInvalidPathOPS = 0;
  }
  get savedStatesDepth() {
    return this.stateManager.stateStack.length;
  }
  read(operation) {
    let args = operation.args;
    while (true) {
      const obj = this.parser.getObj();
      if (obj instanceof _primitives.Cmd) {
        const cmd = obj.cmd;
        const opSpec = EvaluatorPreprocessor.opMap[cmd];
        if (!opSpec) {
          (0, _util.warn)(`Unknown command "${cmd}".`);
          continue;
        }
        const fn = opSpec.id;
        const numArgs = opSpec.numArgs;
        let argsLength = args !== null ? args.length : 0;
        if (!this._isPathOp) {
          this._numInvalidPathOPS = 0;
        }
        this._isPathOp = fn >= _util.OPS.moveTo && fn <= _util.OPS.endPath;
        if (!opSpec.variableArgs) {
          if (argsLength !== numArgs) {
            const nonProcessedArgs = this.nonProcessedArgs;
            while (argsLength > numArgs) {
              nonProcessedArgs.push(args.shift());
              argsLength--;
            }
            while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
              if (args === null) {
                args = [];
              }
              args.unshift(nonProcessedArgs.pop());
              argsLength++;
            }
          }
          if (argsLength < numArgs) {
            const partialMsg = `command ${cmd}: expected ${numArgs} args, ` + `but received ${argsLength} args.`;
            if (this._isPathOp && ++this._numInvalidPathOPS > EvaluatorPreprocessor.MAX_INVALID_PATH_OPS) {
              throw new _util.FormatError(`Invalid ${partialMsg}`);
            }
            (0, _util.warn)(`Skipping ${partialMsg}`);
            if (args !== null) {
              args.length = 0;
            }
            continue;
          }
        } else if (argsLength > numArgs) {
          (0, _util.info)(`Command ${cmd}: expected [0, ${numArgs}] args, ` + `but received ${argsLength} args.`);
        }
        this.preprocessCommand(fn, args);
        operation.fn = fn;
        operation.args = args;
        return true;
      }
      if (obj === _primitives.EOF) {
        return false;
      }
      if (obj !== null) {
        if (args === null) {
          args = [];
        }
        args.push(obj);
        if (args.length > 33) {
          throw new _util.FormatError("Too many arguments");
        }
      }
    }
  }
  preprocessCommand(fn, args) {
    switch (fn | 0) {
      case _util.OPS.save:
        this.stateManager.save();
        break;
      case _util.OPS.restore:
        this.stateManager.restore();
        break;
      case _util.OPS.transform:
        this.stateManager.transform(args);
        break;
    }
  }
}
exports.EvaluatorPreprocessor = EvaluatorPreprocessor;

/***/ }),
/* 14 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.IdentityCMap = exports.CMapFactory = exports.CMap = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _base_stream = __w_pdfjs_require__(5);
var _parser = __w_pdfjs_require__(15);
var _core_utils = __w_pdfjs_require__(4);
var _stream = __w_pdfjs_require__(8);
const BUILT_IN_CMAPS = ["Adobe-GB1-UCS2", "Adobe-CNS1-UCS2", "Adobe-Japan1-UCS2", "Adobe-Korea1-UCS2", "78-EUC-H", "78-EUC-V", "78-H", "78-RKSJ-H", "78-RKSJ-V", "78-V", "78ms-RKSJ-H", "78ms-RKSJ-V", "83pv-RKSJ-H", "90ms-RKSJ-H", "90ms-RKSJ-V", "90msp-RKSJ-H", "90msp-RKSJ-V", "90pv-RKSJ-H", "90pv-RKSJ-V", "Add-H", "Add-RKSJ-H", "Add-RKSJ-V", "Add-V", "Adobe-CNS1-0", "Adobe-CNS1-1", "Adobe-CNS1-2", "Adobe-CNS1-3", "Adobe-CNS1-4", "Adobe-CNS1-5", "Adobe-CNS1-6", "Adobe-GB1-0", "Adobe-GB1-1", "Adobe-GB1-2", "Adobe-GB1-3", "Adobe-GB1-4", "Adobe-GB1-5", "Adobe-Japan1-0", "Adobe-Japan1-1", "Adobe-Japan1-2", "Adobe-Japan1-3", "Adobe-Japan1-4", "Adobe-Japan1-5", "Adobe-Japan1-6", "Adobe-Korea1-0", "Adobe-Korea1-1", "Adobe-Korea1-2", "B5-H", "B5-V", "B5pc-H", "B5pc-V", "CNS-EUC-H", "CNS-EUC-V", "CNS1-H", "CNS1-V", "CNS2-H", "CNS2-V", "ETHK-B5-H", "ETHK-B5-V", "ETen-B5-H", "ETen-B5-V", "ETenms-B5-H", "ETenms-B5-V", "EUC-H", "EUC-V", "Ext-H", "Ext-RKSJ-H", "Ext-RKSJ-V", "Ext-V", "GB-EUC-H", "GB-EUC-V", "GB-H", "GB-V", "GBK-EUC-H", "GBK-EUC-V", "GBK2K-H", "GBK2K-V", "GBKp-EUC-H", "GBKp-EUC-V", "GBT-EUC-H", "GBT-EUC-V", "GBT-H", "GBT-V", "GBTpc-EUC-H", "GBTpc-EUC-V", "GBpc-EUC-H", "GBpc-EUC-V", "H", "HKdla-B5-H", "HKdla-B5-V", "HKdlb-B5-H", "HKdlb-B5-V", "HKgccs-B5-H", "HKgccs-B5-V", "HKm314-B5-H", "HKm314-B5-V", "HKm471-B5-H", "HKm471-B5-V", "HKscs-B5-H", "HKscs-B5-V", "Hankaku", "Hiragana", "KSC-EUC-H", "KSC-EUC-V", "KSC-H", "KSC-Johab-H", "KSC-Johab-V", "KSC-V", "KSCms-UHC-H", "KSCms-UHC-HW-H", "KSCms-UHC-HW-V", "KSCms-UHC-V", "KSCpc-EUC-H", "KSCpc-EUC-V", "Katakana", "NWP-H", "NWP-V", "RKSJ-H", "RKSJ-V", "Roman", "UniCNS-UCS2-H", "UniCNS-UCS2-V", "UniCNS-UTF16-H", "UniCNS-UTF16-V", "UniCNS-UTF32-H", "UniCNS-UTF32-V", "UniCNS-UTF8-H", "UniCNS-UTF8-V", "UniGB-UCS2-H", "UniGB-UCS2-V", "UniGB-UTF16-H", "UniGB-UTF16-V", "UniGB-UTF32-H", "UniGB-UTF32-V", "UniGB-UTF8-H", "UniGB-UTF8-V", "UniJIS-UCS2-H", "UniJIS-UCS2-HW-H", "UniJIS-UCS2-HW-V", "UniJIS-UCS2-V", "UniJIS-UTF16-H", "UniJIS-UTF16-V", "UniJIS-UTF32-H", "UniJIS-UTF32-V", "UniJIS-UTF8-H", "UniJIS-UTF8-V", "UniJIS2004-UTF16-H", "UniJIS2004-UTF16-V", "UniJIS2004-UTF32-H", "UniJIS2004-UTF32-V", "UniJIS2004-UTF8-H", "UniJIS2004-UTF8-V", "UniJISPro-UCS2-HW-V", "UniJISPro-UCS2-V", "UniJISPro-UTF8-V", "UniJISX0213-UTF32-H", "UniJISX0213-UTF32-V", "UniJISX02132004-UTF32-H", "UniJISX02132004-UTF32-V", "UniKS-UCS2-H", "UniKS-UCS2-V", "UniKS-UTF16-H", "UniKS-UTF16-V", "UniKS-UTF32-H", "UniKS-UTF32-V", "UniKS-UTF8-H", "UniKS-UTF8-V", "V", "WP-Symbol"];
const MAX_MAP_RANGE = 2 ** 24 - 1;
class CMap {
  constructor(builtInCMap = false) {
    this.codespaceRanges = [[], [], [], []];
    this.numCodespaceRanges = 0;
    this._map = [];
    this.name = "";
    this.vertical = false;
    this.useCMap = null;
    this.builtInCMap = builtInCMap;
  }
  addCodespaceRange(n, low, high) {
    this.codespaceRanges[n - 1].push(low, high);
    this.numCodespaceRanges++;
  }
  mapCidRange(low, high, dstLow) {
    if (high - low > MAX_MAP_RANGE) {
      throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");
    }
    while (low <= high) {
      this._map[low++] = dstLow++;
    }
  }
  mapBfRange(low, high, dstLow) {
    if (high - low > MAX_MAP_RANGE) {
      throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");
    }
    const lastByte = dstLow.length - 1;
    while (low <= high) {
      this._map[low++] = dstLow;
      const nextCharCode = dstLow.charCodeAt(lastByte) + 1;
      if (nextCharCode > 0xff) {
        dstLow = dstLow.substring(0, lastByte - 1) + String.fromCharCode(dstLow.charCodeAt(lastByte - 1) + 1) + "\x00";
        continue;
      }
      dstLow = dstLow.substring(0, lastByte) + String.fromCharCode(nextCharCode);
    }
  }
  mapBfRangeToArray(low, high, array) {
    if (high - low > MAX_MAP_RANGE) {
      throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");
    }
    const ii = array.length;
    let i = 0;
    while (low <= high && i < ii) {
      this._map[low] = array[i++];
      ++low;
    }
  }
  mapOne(src, dst) {
    this._map[src] = dst;
  }
  lookup(code) {
    return this._map[code];
  }
  contains(code) {
    return this._map[code] !== undefined;
  }
  forEach(callback) {
    const map = this._map;
    const length = map.length;
    if (length <= 0x10000) {
      for (let i = 0; i < length; i++) {
        if (map[i] !== undefined) {
          callback(i, map[i]);
        }
      }
    } else {
      for (const i in map) {
        callback(i, map[i]);
      }
    }
  }
  charCodeOf(value) {
    const map = this._map;
    if (map.length <= 0x10000) {
      return map.indexOf(value);
    }
    for (const charCode in map) {
      if (map[charCode] === value) {
        return charCode | 0;
      }
    }
    return -1;
  }
  getMap() {
    return this._map;
  }
  readCharCode(str, offset, out) {
    let c = 0;
    const codespaceRanges = this.codespaceRanges;
    for (let n = 0, nn = codespaceRanges.length; n < nn; n++) {
      c = (c << 8 | str.charCodeAt(offset + n)) >>> 0;
      const codespaceRange = codespaceRanges[n];
      for (let k = 0, kk = codespaceRange.length; k < kk;) {
        const low = codespaceRange[k++];
        const high = codespaceRange[k++];
        if (c >= low && c <= high) {
          out.charcode = c;
          out.length = n + 1;
          return;
        }
      }
    }
    out.charcode = 0;
    out.length = 1;
  }
  getCharCodeLength(charCode) {
    const codespaceRanges = this.codespaceRanges;
    for (let n = 0, nn = codespaceRanges.length; n < nn; n++) {
      const codespaceRange = codespaceRanges[n];
      for (let k = 0, kk = codespaceRange.length; k < kk;) {
        const low = codespaceRange[k++];
        const high = codespaceRange[k++];
        if (charCode >= low && charCode <= high) {
          return n + 1;
        }
      }
    }
    return 1;
  }
  get length() {
    return this._map.length;
  }
  get isIdentityCMap() {
    if (!(this.name === "Identity-H" || this.name === "Identity-V")) {
      return false;
    }
    if (this._map.length !== 0x10000) {
      return false;
    }
    for (let i = 0; i < 0x10000; i++) {
      if (this._map[i] !== i) {
        return false;
      }
    }
    return true;
  }
}
exports.CMap = CMap;
class IdentityCMap extends CMap {
  constructor(vertical, n) {
    super();
    this.vertical = vertical;
    this.addCodespaceRange(n, 0, 0xffff);
  }
  mapCidRange(low, high, dstLow) {
    (0, _util.unreachable)("should not call mapCidRange");
  }
  mapBfRange(low, high, dstLow) {
    (0, _util.unreachable)("should not call mapBfRange");
  }
  mapBfRangeToArray(low, high, array) {
    (0, _util.unreachable)("should not call mapBfRangeToArray");
  }
  mapOne(src, dst) {
    (0, _util.unreachable)("should not call mapCidOne");
  }
  lookup(code) {
    return Number.isInteger(code) && code <= 0xffff ? code : undefined;
  }
  contains(code) {
    return Number.isInteger(code) && code <= 0xffff;
  }
  forEach(callback) {
    for (let i = 0; i <= 0xffff; i++) {
      callback(i, i);
    }
  }
  charCodeOf(value) {
    return Number.isInteger(value) && value <= 0xffff ? value : -1;
  }
  getMap() {
    const map = new Array(0x10000);
    for (let i = 0; i <= 0xffff; i++) {
      map[i] = i;
    }
    return map;
  }
  get length() {
    return 0x10000;
  }
  get isIdentityCMap() {
    (0, _util.unreachable)("should not access .isIdentityCMap");
  }
}
exports.IdentityCMap = IdentityCMap;
const BinaryCMapReader = function BinaryCMapReaderClosure() {
  function hexToInt(a, size) {
    let n = 0;
    for (let i = 0; i <= size; i++) {
      n = n << 8 | a[i];
    }
    return n >>> 0;
  }
  function hexToStr(a, size) {
    if (size === 1) {
      return String.fromCharCode(a[0], a[1]);
    }
    if (size === 3) {
      return String.fromCharCode(a[0], a[1], a[2], a[3]);
    }
    return String.fromCharCode.apply(null, a.subarray(0, size + 1));
  }
  function addHex(a, b, size) {
    let c = 0;
    for (let i = size; i >= 0; i--) {
      c += a[i] + b[i];
      a[i] = c & 255;
      c >>= 8;
    }
  }
  function incHex(a, size) {
    let c = 1;
    for (let i = size; i >= 0 && c > 0; i--) {
      c += a[i];
      a[i] = c & 255;
      c >>= 8;
    }
  }
  const MAX_NUM_SIZE = 16;
  const MAX_ENCODED_NUM_SIZE = 19;
  class BinaryCMapStream {
    constructor(data) {
      this.buffer = data;
      this.pos = 0;
      this.end = data.length;
      this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
    }
    readByte() {
      if (this.pos >= this.end) {
        return -1;
      }
      return this.buffer[this.pos++];
    }
    readNumber() {
      let n = 0;
      let last;
      do {
        const b = this.readByte();
        if (b < 0) {
          throw new _util.FormatError("unexpected EOF in bcmap");
        }
        last = !(b & 0x80);
        n = n << 7 | b & 0x7f;
      } while (!last);
      return n;
    }
    readSigned() {
      const n = this.readNumber();
      return n & 1 ? ~(n >>> 1) : n >>> 1;
    }
    readHex(num, size) {
      num.set(this.buffer.subarray(this.pos, this.pos + size + 1));
      this.pos += size + 1;
    }
    readHexNumber(num, size) {
      let last;
      const stack = this.tmpBuf;
      let sp = 0;
      do {
        const b = this.readByte();
        if (b < 0) {
          throw new _util.FormatError("unexpected EOF in bcmap");
        }
        last = !(b & 0x80);
        stack[sp++] = b & 0x7f;
      } while (!last);
      let i = size,
        buffer = 0,
        bufferSize = 0;
      while (i >= 0) {
        while (bufferSize < 8 && stack.length > 0) {
          buffer |= stack[--sp] << bufferSize;
          bufferSize += 7;
        }
        num[i] = buffer & 255;
        i--;
        buffer >>= 8;
        bufferSize -= 8;
      }
    }
    readHexSigned(num, size) {
      this.readHexNumber(num, size);
      const sign = num[size] & 1 ? 255 : 0;
      let c = 0;
      for (let i = 0; i <= size; i++) {
        c = (c & 1) << 8 | num[i];
        num[i] = c >> 1 ^ sign;
      }
    }
    readString() {
      const len = this.readNumber();
      let s = "";
      for (let i = 0; i < len; i++) {
        s += String.fromCharCode(this.readNumber());
      }
      return s;
    }
  }
  class BinaryCMapReader {
    async process(data, cMap, extend) {
      const stream = new BinaryCMapStream(data);
      const header = stream.readByte();
      cMap.vertical = !!(header & 1);
      let useCMap = null;
      const start = new Uint8Array(MAX_NUM_SIZE);
      const end = new Uint8Array(MAX_NUM_SIZE);
      const char = new Uint8Array(MAX_NUM_SIZE);
      const charCode = new Uint8Array(MAX_NUM_SIZE);
      const tmp = new Uint8Array(MAX_NUM_SIZE);
      let code;
      let b;
      while ((b = stream.readByte()) >= 0) {
        const type = b >> 5;
        if (type === 7) {
          switch (b & 0x1f) {
            case 0:
              stream.readString();
              break;
            case 1:
              useCMap = stream.readString();
              break;
          }
          continue;
        }
        const sequence = !!(b & 0x10);
        const dataSize = b & 15;
        if (dataSize + 1 > MAX_NUM_SIZE) {
          throw new Error("BinaryCMapReader.process: Invalid dataSize.");
        }
        const ucs2DataSize = 1;
        const subitemsCount = stream.readNumber();
        switch (type) {
          case 0:
            stream.readHex(start, dataSize);
            stream.readHexNumber(end, dataSize);
            addHex(end, start, dataSize);
            cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize), hexToInt(end, dataSize));
            for (let i = 1; i < subitemsCount; i++) {
              incHex(end, dataSize);
              stream.readHexNumber(start, dataSize);
              addHex(start, end, dataSize);
              stream.readHexNumber(end, dataSize);
              addHex(end, start, dataSize);
              cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize), hexToInt(end, dataSize));
            }
            break;
          case 1:
            stream.readHex(start, dataSize);
            stream.readHexNumber(end, dataSize);
            addHex(end, start, dataSize);
            stream.readNumber();
            for (let i = 1; i < subitemsCount; i++) {
              incHex(end, dataSize);
              stream.readHexNumber(start, dataSize);
              addHex(start, end, dataSize);
              stream.readHexNumber(end, dataSize);
              addHex(end, start, dataSize);
              stream.readNumber();
            }
            break;
          case 2:
            stream.readHex(char, dataSize);
            code = stream.readNumber();
            cMap.mapOne(hexToInt(char, dataSize), code);
            for (let i = 1; i < subitemsCount; i++) {
              incHex(char, dataSize);
              if (!sequence) {
                stream.readHexNumber(tmp, dataSize);
                addHex(char, tmp, dataSize);
              }
              code = stream.readSigned() + (code + 1);
              cMap.mapOne(hexToInt(char, dataSize), code);
            }
            break;
          case 3:
            stream.readHex(start, dataSize);
            stream.readHexNumber(end, dataSize);
            addHex(end, start, dataSize);
            code = stream.readNumber();
            cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize), code);
            for (let i = 1; i < subitemsCount; i++) {
              incHex(end, dataSize);
              if (!sequence) {
                stream.readHexNumber(start, dataSize);
                addHex(start, end, dataSize);
              } else {
                start.set(end);
              }
              stream.readHexNumber(end, dataSize);
              addHex(end, start, dataSize);
              code = stream.readNumber();
              cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize), code);
            }
            break;
          case 4:
            stream.readHex(char, ucs2DataSize);
            stream.readHex(charCode, dataSize);
            cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
            for (let i = 1; i < subitemsCount; i++) {
              incHex(char, ucs2DataSize);
              if (!sequence) {
                stream.readHexNumber(tmp, ucs2DataSize);
                addHex(char, tmp, ucs2DataSize);
              }
              incHex(charCode, dataSize);
              stream.readHexSigned(tmp, dataSize);
              addHex(charCode, tmp, dataSize);
              cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
            }
            break;
          case 5:
            stream.readHex(start, ucs2DataSize);
            stream.readHexNumber(end, ucs2DataSize);
            addHex(end, start, ucs2DataSize);
            stream.readHex(charCode, dataSize);
            cMap.mapBfRange(hexToInt(start, ucs2DataSize), hexToInt(end, ucs2DataSize), hexToStr(charCode, dataSize));
            for (let i = 1; i < subitemsCount; i++) {
              incHex(end, ucs2DataSize);
              if (!sequence) {
                stream.readHexNumber(start, ucs2DataSize);
                addHex(start, end, ucs2DataSize);
              } else {
                start.set(end);
              }
              stream.readHexNumber(end, ucs2DataSize);
              addHex(end, start, ucs2DataSize);
              stream.readHex(charCode, dataSize);
              cMap.mapBfRange(hexToInt(start, ucs2DataSize), hexToInt(end, ucs2DataSize), hexToStr(charCode, dataSize));
            }
            break;
          default:
            throw new Error(`BinaryCMapReader.process - unknown type: ${type}`);
        }
      }
      if (useCMap) {
        return extend(useCMap);
      }
      return cMap;
    }
  }
  return BinaryCMapReader;
}();
const CMapFactory = function CMapFactoryClosure() {
  function strToInt(str) {
    let a = 0;
    for (let i = 0; i < str.length; i++) {
      a = a << 8 | str.charCodeAt(i);
    }
    return a >>> 0;
  }
  function expectString(obj) {
    if (typeof obj !== "string") {
      throw new _util.FormatError("Malformed CMap: expected string.");
    }
  }
  function expectInt(obj) {
    if (!Number.isInteger(obj)) {
      throw new _util.FormatError("Malformed CMap: expected int.");
    }
  }
  function parseBfChar(cMap, lexer) {
    while (true) {
      let obj = lexer.getObj();
      if (obj === _primitives.EOF) {
        break;
      }
      if ((0, _primitives.isCmd)(obj, "endbfchar")) {
        return;
      }
      expectString(obj);
      const src = strToInt(obj);
      obj = lexer.getObj();
      expectString(obj);
      const dst = obj;
      cMap.mapOne(src, dst);
    }
  }
  function parseBfRange(cMap, lexer) {
    while (true) {
      let obj = lexer.getObj();
      if (obj === _primitives.EOF) {
        break;
      }
      if ((0, _primitives.isCmd)(obj, "endbfrange")) {
        return;
      }
      expectString(obj);
      const low = strToInt(obj);
      obj = lexer.getObj();
      expectString(obj);
      const high = strToInt(obj);
      obj = lexer.getObj();
      if (Number.isInteger(obj) || typeof obj === "string") {
        const dstLow = Number.isInteger(obj) ? String.fromCharCode(obj) : obj;
        cMap.mapBfRange(low, high, dstLow);
      } else if ((0, _primitives.isCmd)(obj, "[")) {
        obj = lexer.getObj();
        const array = [];
        while (!(0, _primitives.isCmd)(obj, "]") && obj !== _primitives.EOF) {
          array.push(obj);
          obj = lexer.getObj();
        }
        cMap.mapBfRangeToArray(low, high, array);
      } else {
        break;
      }
    }
    throw new _util.FormatError("Invalid bf range.");
  }
  function parseCidChar(cMap, lexer) {
    while (true) {
      let obj = lexer.getObj();
      if (obj === _primitives.EOF) {
        break;
      }
      if ((0, _primitives.isCmd)(obj, "endcidchar")) {
        return;
      }
      expectString(obj);
      const src = strToInt(obj);
      obj = lexer.getObj();
      expectInt(obj);
      const dst = obj;
      cMap.mapOne(src, dst);
    }
  }
  function parseCidRange(cMap, lexer) {
    while (true) {
      let obj = lexer.getObj();
      if (obj === _primitives.EOF) {
        break;
      }
      if ((0, _primitives.isCmd)(obj, "endcidrange")) {
        return;
      }
      expectString(obj);
      const low = strToInt(obj);
      obj = lexer.getObj();
      expectString(obj);
      const high = strToInt(obj);
      obj = lexer.getObj();
      expectInt(obj);
      const dstLow = obj;
      cMap.mapCidRange(low, high, dstLow);
    }
  }
  function parseCodespaceRange(cMap, lexer) {
    while (true) {
      let obj = lexer.getObj();
      if (obj === _primitives.EOF) {
        break;
      }
      if ((0, _primitives.isCmd)(obj, "endcodespacerange")) {
        return;
      }
      if (typeof obj !== "string") {
        break;
      }
      const low = strToInt(obj);
      obj = lexer.getObj();
      if (typeof obj !== "string") {
        break;
      }
      const high = strToInt(obj);
      cMap.addCodespaceRange(obj.length, low, high);
    }
    throw new _util.FormatError("Invalid codespace range.");
  }
  function parseWMode(cMap, lexer) {
    const obj = lexer.getObj();
    if (Number.isInteger(obj)) {
      cMap.vertical = !!obj;
    }
  }
  function parseCMapName(cMap, lexer) {
    const obj = lexer.getObj();
    if (obj instanceof _primitives.Name) {
      cMap.name = obj.name;
    }
  }
  async function parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap) {
    let previous, embeddedUseCMap;
    objLoop: while (true) {
      try {
        const obj = lexer.getObj();
        if (obj === _primitives.EOF) {
          break;
        } else if (obj instanceof _primitives.Name) {
          if (obj.name === "WMode") {
            parseWMode(cMap, lexer);
          } else if (obj.name === "CMapName") {
            parseCMapName(cMap, lexer);
          }
          previous = obj;
        } else if (obj instanceof _primitives.Cmd) {
          switch (obj.cmd) {
            case "endcmap":
              break objLoop;
            case "usecmap":
              if (previous instanceof _primitives.Name) {
                embeddedUseCMap = previous.name;
              }
              break;
            case "begincodespacerange":
              parseCodespaceRange(cMap, lexer);
              break;
            case "beginbfchar":
              parseBfChar(cMap, lexer);
              break;
            case "begincidchar":
              parseCidChar(cMap, lexer);
              break;
            case "beginbfrange":
              parseBfRange(cMap, lexer);
              break;
            case "begincidrange":
              parseCidRange(cMap, lexer);
              break;
          }
        }
      } catch (ex) {
        if (ex instanceof _core_utils.MissingDataException) {
          throw ex;
        }
        (0, _util.warn)("Invalid cMap data: " + ex);
        continue;
      }
    }
    if (!useCMap && embeddedUseCMap) {
      useCMap = embeddedUseCMap;
    }
    if (useCMap) {
      return extendCMap(cMap, fetchBuiltInCMap, useCMap);
    }
    return cMap;
  }
  async function extendCMap(cMap, fetchBuiltInCMap, useCMap) {
    cMap.useCMap = await createBuiltInCMap(useCMap, fetchBuiltInCMap);
    if (cMap.numCodespaceRanges === 0) {
      const useCodespaceRanges = cMap.useCMap.codespaceRanges;
      for (let i = 0; i < useCodespaceRanges.length; i++) {
        cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
      }
      cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
    }
    cMap.useCMap.forEach(function (key, value) {
      if (!cMap.contains(key)) {
        cMap.mapOne(key, cMap.useCMap.lookup(key));
      }
    });
    return cMap;
  }
  async function createBuiltInCMap(name, fetchBuiltInCMap) {
    if (name === "Identity-H") {
      return new IdentityCMap(false, 2);
    } else if (name === "Identity-V") {
      return new IdentityCMap(true, 2);
    }
    if (!BUILT_IN_CMAPS.includes(name)) {
      throw new Error("Unknown CMap name: " + name);
    }
    if (!fetchBuiltInCMap) {
      throw new Error("Built-in CMap parameters are not provided.");
    }
    const {
      cMapData,
      compressionType
    } = await fetchBuiltInCMap(name);
    const cMap = new CMap(true);
    if (compressionType === _util.CMapCompressionType.BINARY) {
      return new BinaryCMapReader().process(cMapData, cMap, useCMap => {
        return extendCMap(cMap, fetchBuiltInCMap, useCMap);
      });
    }
    if (compressionType === _util.CMapCompressionType.NONE) {
      const lexer = new _parser.Lexer(new _stream.Stream(cMapData));
      return parseCMap(cMap, lexer, fetchBuiltInCMap, null);
    }
    throw new Error(`Invalid CMap "compressionType" value: ${compressionType}`);
  }
  return {
    async create(params) {
      const encoding = params.encoding;
      const fetchBuiltInCMap = params.fetchBuiltInCMap;
      const useCMap = params.useCMap;
      if (encoding instanceof _primitives.Name) {
        return createBuiltInCMap(encoding.name, fetchBuiltInCMap);
      } else if (encoding instanceof _base_stream.BaseStream) {
        const parsedCMap = await parseCMap(new CMap(), new _parser.Lexer(encoding), fetchBuiltInCMap, useCMap);
        if (parsedCMap.isIdentityCMap) {
          return createBuiltInCMap(parsedCMap.name, fetchBuiltInCMap);
        }
        return parsedCMap;
      }
      throw new Error("Encoding required.");
    }
  };
}();
exports.CMapFactory = CMapFactory;

/***/ }),
/* 15 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Parser = exports.Linearization = exports.Lexer = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _core_utils = __w_pdfjs_require__(4);
var _ascii_85_stream = __w_pdfjs_require__(16);
var _ascii_hex_stream = __w_pdfjs_require__(18);
var _ccitt_stream = __w_pdfjs_require__(19);
var _flate_stream = __w_pdfjs_require__(21);
var _jbig2_stream = __w_pdfjs_require__(22);
var _jpeg_stream = __w_pdfjs_require__(25);
var _jpx_stream = __w_pdfjs_require__(27);
var _lzw_stream = __w_pdfjs_require__(29);
var _stream = __w_pdfjs_require__(8);
var _predictor_stream = __w_pdfjs_require__(30);
var _run_length_stream = __w_pdfjs_require__(31);
const MAX_LENGTH_TO_CACHE = 1000;
function getInlineImageCacheKey(bytes) {
  const strBuf = [],
    ii = bytes.length;
  let i = 0;
  while (i < ii - 1) {
    strBuf.push(bytes[i++] << 8 | bytes[i++]);
  }
  if (i < ii) {
    strBuf.push(bytes[i]);
  }
  return ii + "_" + String.fromCharCode.apply(null, strBuf);
}
class Parser {
  constructor({
    lexer,
    xref,
    allowStreams = false,
    recoveryMode = false
  }) {
    this.lexer = lexer;
    this.xref = xref;
    this.allowStreams = allowStreams;
    this.recoveryMode = recoveryMode;
    this.imageCache = Object.create(null);
    this._imageId = 0;
    this.refill();
  }
  refill() {
    this.buf1 = this.lexer.getObj();
    this.buf2 = this.lexer.getObj();
  }
  shift() {
    if (this.buf2 instanceof _primitives.Cmd && this.buf2.cmd === "ID") {
      this.buf1 = this.buf2;
      this.buf2 = null;
    } else {
      this.buf1 = this.buf2;
      this.buf2 = this.lexer.getObj();
    }
  }
  tryShift() {
    try {
      this.shift();
      return true;
    } catch (e) {
      if (e instanceof _core_utils.MissingDataException) {
        throw e;
      }
      return false;
    }
  }
  getObj(cipherTransform = null) {
    const buf1 = this.buf1;
    this.shift();
    if (buf1 instanceof _primitives.Cmd) {
      switch (buf1.cmd) {
        case "BI":
          return this.makeInlineImage(cipherTransform);
        case "[":
          const array = [];
          while (!(0, _primitives.isCmd)(this.buf1, "]") && this.buf1 !== _primitives.EOF) {
            array.push(this.getObj(cipherTransform));
          }
          if (this.buf1 === _primitives.EOF) {
            if (this.recoveryMode) {
              return array;
            }
            throw new _core_utils.ParserEOFException("End of file inside array.");
          }
          this.shift();
          return array;
        case "<<":
          const dict = new _primitives.Dict(this.xref);
          while (!(0, _primitives.isCmd)(this.buf1, ">>") && this.buf1 !== _primitives.EOF) {
            if (!(this.buf1 instanceof _primitives.Name)) {
              (0, _util.info)("Malformed dictionary: key must be a name object");
              this.shift();
              continue;
            }
            const key = this.buf1.name;
            this.shift();
            if (this.buf1 === _primitives.EOF) {
              break;
            }
            dict.set(key, this.getObj(cipherTransform));
          }
          if (this.buf1 === _primitives.EOF) {
            if (this.recoveryMode) {
              return dict;
            }
            throw new _core_utils.ParserEOFException("End of file inside dictionary.");
          }
          if ((0, _primitives.isCmd)(this.buf2, "stream")) {
            return this.allowStreams ? this.makeStream(dict, cipherTransform) : dict;
          }
          this.shift();
          return dict;
        default:
          return buf1;
      }
    }
    if (Number.isInteger(buf1)) {
      if (Number.isInteger(this.buf1) && (0, _primitives.isCmd)(this.buf2, "R")) {
        const ref = _primitives.Ref.get(buf1, this.buf1);
        this.shift();
        this.shift();
        return ref;
      }
      return buf1;
    }
    if (typeof buf1 === "string") {
      if (cipherTransform) {
        return cipherTransform.decryptString(buf1);
      }
      return buf1;
    }
    return buf1;
  }
  findDefaultInlineStreamEnd(stream) {
    const E = 0x45,
      I = 0x49,
      SPACE = 0x20,
      LF = 0xa,
      CR = 0xd,
      NUL = 0x0;
    const lexer = this.lexer,
      startPos = stream.pos,
      n = 10;
    let state = 0,
      ch,
      maybeEIPos;
    while ((ch = stream.getByte()) !== -1) {
      if (state === 0) {
        state = ch === E ? 1 : 0;
      } else if (state === 1) {
        state = ch === I ? 2 : 0;
      } else {
        if (ch === SPACE || ch === LF || ch === CR) {
          maybeEIPos = stream.pos;
          const followingBytes = stream.peekBytes(n);
          for (let i = 0, ii = followingBytes.length; i < ii; i++) {
            ch = followingBytes[i];
            if (ch === NUL && followingBytes[i + 1] !== NUL) {
              continue;
            }
            if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7f)) {
              state = 0;
              break;
            }
          }
          if (state !== 2) {
            continue;
          }
          if (lexer.knownCommands) {
            const nextObj = lexer.peekObj();
            if (nextObj instanceof _primitives.Cmd && !lexer.knownCommands[nextObj.cmd]) {
              state = 0;
            }
          } else {
            (0, _util.warn)("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");
          }
          if (state === 2) {
            break;
          }
        } else {
          state = 0;
        }
      }
    }
    if (ch === -1) {
      (0, _util.warn)("findDefaultInlineStreamEnd: " + "Reached the end of the stream without finding a valid EI marker");
      if (maybeEIPos) {
        (0, _util.warn)('... trying to recover by using the last "EI" occurrence.');
        stream.skip(-(stream.pos - maybeEIPos));
      }
    }
    let endOffset = 4;
    stream.skip(-endOffset);
    ch = stream.peekByte();
    stream.skip(endOffset);
    if (!(0, _core_utils.isWhiteSpace)(ch)) {
      endOffset--;
    }
    return stream.pos - endOffset - startPos;
  }
  findDCTDecodeInlineStreamEnd(stream) {
    const startPos = stream.pos;
    let foundEOI = false,
      b,
      markerLength;
    while ((b = stream.getByte()) !== -1) {
      if (b !== 0xff) {
        continue;
      }
      switch (stream.getByte()) {
        case 0x00:
          break;
        case 0xff:
          stream.skip(-1);
          break;
        case 0xd9:
          foundEOI = true;
          break;
        case 0xc0:
        case 0xc1:
        case 0xc2:
        case 0xc3:
        case 0xc5:
        case 0xc6:
        case 0xc7:
        case 0xc9:
        case 0xca:
        case 0xcb:
        case 0xcd:
        case 0xce:
        case 0xcf:
        case 0xc4:
        case 0xcc:
        case 0xda:
        case 0xdb:
        case 0xdc:
        case 0xdd:
        case 0xde:
        case 0xdf:
        case 0xe0:
        case 0xe1:
        case 0xe2:
        case 0xe3:
        case 0xe4:
        case 0xe5:
        case 0xe6:
        case 0xe7:
        case 0xe8:
        case 0xe9:
        case 0xea:
        case 0xeb:
        case 0xec:
        case 0xed:
        case 0xee:
        case 0xef:
        case 0xfe:
          markerLength = stream.getUint16();
          if (markerLength > 2) {
            stream.skip(markerLength - 2);
          } else {
            stream.skip(-2);
          }
          break;
      }
      if (foundEOI) {
        break;
      }
    }
    const length = stream.pos - startPos;
    if (b === -1) {
      (0, _util.warn)("Inline DCTDecode image stream: " + "EOI marker not found, searching for /EI/ instead.");
      stream.skip(-length);
      return this.findDefaultInlineStreamEnd(stream);
    }
    this.inlineStreamSkipEI(stream);
    return length;
  }
  findASCII85DecodeInlineStreamEnd(stream) {
    const TILDE = 0x7e,
      GT = 0x3e;
    const startPos = stream.pos;
    let ch;
    while ((ch = stream.getByte()) !== -1) {
      if (ch === TILDE) {
        const tildePos = stream.pos;
        ch = stream.peekByte();
        while ((0, _core_utils.isWhiteSpace)(ch)) {
          stream.skip();
          ch = stream.peekByte();
        }
        if (ch === GT) {
          stream.skip();
          break;
        }
        if (stream.pos > tildePos) {
          const maybeEI = stream.peekBytes(2);
          if (maybeEI[0] === 0x45 && maybeEI[1] === 0x49) {
            break;
          }
        }
      }
    }
    const length = stream.pos - startPos;
    if (ch === -1) {
      (0, _util.warn)("Inline ASCII85Decode image stream: " + "EOD marker not found, searching for /EI/ instead.");
      stream.skip(-length);
      return this.findDefaultInlineStreamEnd(stream);
    }
    this.inlineStreamSkipEI(stream);
    return length;
  }
  findASCIIHexDecodeInlineStreamEnd(stream) {
    const GT = 0x3e;
    const startPos = stream.pos;
    let ch;
    while ((ch = stream.getByte()) !== -1) {
      if (ch === GT) {
        break;
      }
    }
    const length = stream.pos - startPos;
    if (ch === -1) {
      (0, _util.warn)("Inline ASCIIHexDecode image stream: " + "EOD marker not found, searching for /EI/ instead.");
      stream.skip(-length);
      return this.findDefaultInlineStreamEnd(stream);
    }
    this.inlineStreamSkipEI(stream);
    return length;
  }
  inlineStreamSkipEI(stream) {
    const E = 0x45,
      I = 0x49;
    let state = 0,
      ch;
    while ((ch = stream.getByte()) !== -1) {
      if (state === 0) {
        state = ch === E ? 1 : 0;
      } else if (state === 1) {
        state = ch === I ? 2 : 0;
      } else if (state === 2) {
        break;
      }
    }
  }
  makeInlineImage(cipherTransform) {
    const lexer = this.lexer;
    const stream = lexer.stream;
    const dictMap = Object.create(null);
    let dictLength;
    while (!(0, _primitives.isCmd)(this.buf1, "ID") && this.buf1 !== _primitives.EOF) {
      if (!(this.buf1 instanceof _primitives.Name)) {
        throw new _util.FormatError("Dictionary key must be a name object");
      }
      const key = this.buf1.name;
      this.shift();
      if (this.buf1 === _primitives.EOF) {
        break;
      }
      dictMap[key] = this.getObj(cipherTransform);
    }
    if (lexer.beginInlineImagePos !== -1) {
      dictLength = stream.pos - lexer.beginInlineImagePos;
    }
    const filter = this.xref.fetchIfRef(dictMap.F || dictMap.Filter);
    let filterName;
    if (filter instanceof _primitives.Name) {
      filterName = filter.name;
    } else if (Array.isArray(filter)) {
      const filterZero = this.xref.fetchIfRef(filter[0]);
      if (filterZero instanceof _primitives.Name) {
        filterName = filterZero.name;
      }
    }
    const startPos = stream.pos;
    let length;
    switch (filterName) {
      case "DCT":
      case "DCTDecode":
        length = this.findDCTDecodeInlineStreamEnd(stream);
        break;
      case "A85":
      case "ASCII85Decode":
        length = this.findASCII85DecodeInlineStreamEnd(stream);
        break;
      case "AHx":
      case "ASCIIHexDecode":
        length = this.findASCIIHexDecodeInlineStreamEnd(stream);
        break;
      default:
        length = this.findDefaultInlineStreamEnd(stream);
    }
    let cacheKey;
    if (length < MAX_LENGTH_TO_CACHE && dictLength > 0) {
      const initialStreamPos = stream.pos;
      stream.pos = lexer.beginInlineImagePos;
      cacheKey = getInlineImageCacheKey(stream.getBytes(dictLength + length));
      stream.pos = initialStreamPos;
      const cacheEntry = this.imageCache[cacheKey];
      if (cacheEntry !== undefined) {
        this.buf2 = _primitives.Cmd.get("EI");
        this.shift();
        cacheEntry.reset();
        return cacheEntry;
      }
    }
    const dict = new _primitives.Dict(this.xref);
    for (const key in dictMap) {
      dict.set(key, dictMap[key]);
    }
    let imageStream = stream.makeSubStream(startPos, length, dict);
    if (cipherTransform) {
      imageStream = cipherTransform.createStream(imageStream, length);
    }
    imageStream = this.filter(imageStream, dict, length);
    imageStream.dict = dict;
    if (cacheKey !== undefined) {
      imageStream.cacheKey = `inline_img_${++this._imageId}`;
      this.imageCache[cacheKey] = imageStream;
    }
    this.buf2 = _primitives.Cmd.get("EI");
    this.shift();
    return imageStream;
  }
  _findStreamLength(startPos, signature) {
    const {
      stream
    } = this.lexer;
    stream.pos = startPos;
    const SCAN_BLOCK_LENGTH = 2048;
    const signatureLength = signature.length;
    while (stream.pos < stream.end) {
      const scanBytes = stream.peekBytes(SCAN_BLOCK_LENGTH);
      const scanLength = scanBytes.length - signatureLength;
      if (scanLength <= 0) {
        break;
      }
      let pos = 0;
      while (pos < scanLength) {
        let j = 0;
        while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
          j++;
        }
        if (j >= signatureLength) {
          stream.pos += pos;
          return stream.pos - startPos;
        }
        pos++;
      }
      stream.pos += scanLength;
    }
    return -1;
  }
  makeStream(dict, cipherTransform) {
    const lexer = this.lexer;
    let stream = lexer.stream;
    lexer.skipToNextLine();
    const startPos = stream.pos - 1;
    let length = dict.get("Length");
    if (!Number.isInteger(length)) {
      (0, _util.info)(`Bad length "${length && length.toString()}" in stream.`);
      length = 0;
    }
    stream.pos = startPos + length;
    lexer.nextChar();
    if (this.tryShift() && (0, _primitives.isCmd)(this.buf2, "endstream")) {
      this.shift();
    } else {
      const ENDSTREAM_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d]);
      let actualLength = this._findStreamLength(startPos, ENDSTREAM_SIGNATURE);
      if (actualLength < 0) {
        const MAX_TRUNCATION = 1;
        for (let i = 1; i <= MAX_TRUNCATION; i++) {
          const end = ENDSTREAM_SIGNATURE.length - i;
          const TRUNCATED_SIGNATURE = ENDSTREAM_SIGNATURE.slice(0, end);
          const maybeLength = this._findStreamLength(startPos, TRUNCATED_SIGNATURE);
          if (maybeLength >= 0) {
            const lastByte = stream.peekBytes(end + 1)[end];
            if (!(0, _core_utils.isWhiteSpace)(lastByte)) {
              break;
            }
            (0, _util.info)(`Found "${(0, _util.bytesToString)(TRUNCATED_SIGNATURE)}" when ` + "searching for endstream command.");
            actualLength = maybeLength;
            break;
          }
        }
        if (actualLength < 0) {
          throw new _util.FormatError("Missing endstream command.");
        }
      }
      length = actualLength;
      lexer.nextChar();
      this.shift();
      this.shift();
    }
    this.shift();
    stream = stream.makeSubStream(startPos, length, dict);
    if (cipherTransform) {
      stream = cipherTransform.createStream(stream, length);
    }
    stream = this.filter(stream, dict, length);
    stream.dict = dict;
    return stream;
  }
  filter(stream, dict, length) {
    let filter = dict.get("F", "Filter");
    let params = dict.get("DP", "DecodeParms");
    if (filter instanceof _primitives.Name) {
      if (Array.isArray(params)) {
        (0, _util.warn)("/DecodeParms should not be an Array, when /Filter is a Name.");
      }
      return this.makeFilter(stream, filter.name, length, params);
    }
    let maybeLength = length;
    if (Array.isArray(filter)) {
      const filterArray = filter;
      const paramsArray = params;
      for (let i = 0, ii = filterArray.length; i < ii; ++i) {
        filter = this.xref.fetchIfRef(filterArray[i]);
        if (!(filter instanceof _primitives.Name)) {
          throw new _util.FormatError(`Bad filter name "${filter}"`);
        }
        params = null;
        if (Array.isArray(paramsArray) && i in paramsArray) {
          params = this.xref.fetchIfRef(paramsArray[i]);
        }
        stream = this.makeFilter(stream, filter.name, maybeLength, params);
        maybeLength = null;
      }
    }
    return stream;
  }
  makeFilter(stream, name, maybeLength, params) {
    if (maybeLength === 0) {
      (0, _util.warn)(`Empty "${name}" stream.`);
      return new _stream.NullStream();
    }
    try {
      switch (name) {
        case "Fl":
        case "FlateDecode":
          if (params) {
            return new _predictor_stream.PredictorStream(new _flate_stream.FlateStream(stream, maybeLength), maybeLength, params);
          }
          return new _flate_stream.FlateStream(stream, maybeLength);
        case "LZW":
        case "LZWDecode":
          let earlyChange = 1;
          if (params) {
            if (params.has("EarlyChange")) {
              earlyChange = params.get("EarlyChange");
            }
            return new _predictor_stream.PredictorStream(new _lzw_stream.LZWStream(stream, maybeLength, earlyChange), maybeLength, params);
          }
          return new _lzw_stream.LZWStream(stream, maybeLength, earlyChange);
        case "DCT":
        case "DCTDecode":
          return new _jpeg_stream.JpegStream(stream, maybeLength, params);
        case "JPX":
        case "JPXDecode":
          return new _jpx_stream.JpxStream(stream, maybeLength, params);
        case "A85":
        case "ASCII85Decode":
          return new _ascii_85_stream.Ascii85Stream(stream, maybeLength);
        case "AHx":
        case "ASCIIHexDecode":
          return new _ascii_hex_stream.AsciiHexStream(stream, maybeLength);
        case "CCF":
        case "CCITTFaxDecode":
          return new _ccitt_stream.CCITTFaxStream(stream, maybeLength, params);
        case "RL":
        case "RunLengthDecode":
          return new _run_length_stream.RunLengthStream(stream, maybeLength);
        case "JBIG2Decode":
          return new _jbig2_stream.Jbig2Stream(stream, maybeLength, params);
      }
      (0, _util.warn)(`Filter "${name}" is not supported.`);
      return stream;
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`Invalid stream: "${ex}"`);
      return new _stream.NullStream();
    }
  }
}
exports.Parser = Parser;
const specialChars = [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function toHexDigit(ch) {
  if (ch >= 0x30 && ch <= 0x39) {
    return ch & 0x0f;
  }
  if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
    return (ch & 0x0f) + 9;
  }
  return -1;
}
class Lexer {
  constructor(stream, knownCommands = null) {
    this.stream = stream;
    this.nextChar();
    this.strBuf = [];
    this.knownCommands = knownCommands;
    this._hexStringNumWarn = 0;
    this.beginInlineImagePos = -1;
  }
  nextChar() {
    return this.currentChar = this.stream.getByte();
  }
  peekChar() {
    return this.stream.peekByte();
  }
  getNumber() {
    let ch = this.currentChar;
    let eNotation = false;
    let divideBy = 0;
    let sign = 0;
    if (ch === 0x2d) {
      sign = -1;
      ch = this.nextChar();
      if (ch === 0x2d) {
        ch = this.nextChar();
      }
    } else if (ch === 0x2b) {
      sign = 1;
      ch = this.nextChar();
    }
    if (ch === 0x0a || ch === 0x0d) {
      do {
        ch = this.nextChar();
      } while (ch === 0x0a || ch === 0x0d);
    }
    if (ch === 0x2e) {
      divideBy = 10;
      ch = this.nextChar();
    }
    if (ch < 0x30 || ch > 0x39) {
      const msg = `Invalid number: ${String.fromCharCode(ch)} (charCode ${ch})`;
      if ((0, _core_utils.isWhiteSpace)(ch) || ch === -1) {
        (0, _util.info)(`Lexer.getNumber - "${msg}".`);
        return 0;
      }
      throw new _util.FormatError(msg);
    }
    sign = sign || 1;
    let baseValue = ch - 0x30;
    let powerValue = 0;
    let powerValueSign = 1;
    while ((ch = this.nextChar()) >= 0) {
      if (ch >= 0x30 && ch <= 0x39) {
        const currentDigit = ch - 0x30;
        if (eNotation) {
          powerValue = powerValue * 10 + currentDigit;
        } else {
          if (divideBy !== 0) {
            divideBy *= 10;
          }
          baseValue = baseValue * 10 + currentDigit;
        }
      } else if (ch === 0x2e) {
        if (divideBy === 0) {
          divideBy = 1;
        } else {
          break;
        }
      } else if (ch === 0x2d) {
        (0, _util.warn)("Badly formatted number: minus sign in the middle");
      } else if (ch === 0x45 || ch === 0x65) {
        ch = this.peekChar();
        if (ch === 0x2b || ch === 0x2d) {
          powerValueSign = ch === 0x2d ? -1 : 1;
          this.nextChar();
        } else if (ch < 0x30 || ch > 0x39) {
          break;
        }
        eNotation = true;
      } else {
        break;
      }
    }
    if (divideBy !== 0) {
      baseValue /= divideBy;
    }
    if (eNotation) {
      baseValue *= 10 ** (powerValueSign * powerValue);
    }
    return sign * baseValue;
  }
  getString() {
    let numParen = 1;
    let done = false;
    const strBuf = this.strBuf;
    strBuf.length = 0;
    let ch = this.nextChar();
    while (true) {
      let charBuffered = false;
      switch (ch | 0) {
        case -1:
          (0, _util.warn)("Unterminated string");
          done = true;
          break;
        case 0x28:
          ++numParen;
          strBuf.push("(");
          break;
        case 0x29:
          if (--numParen === 0) {
            this.nextChar();
            done = true;
          } else {
            strBuf.push(")");
          }
          break;
        case 0x5c:
          ch = this.nextChar();
          switch (ch) {
            case -1:
              (0, _util.warn)("Unterminated string");
              done = true;
              break;
            case 0x6e:
              strBuf.push("\n");
              break;
            case 0x72:
              strBuf.push("\r");
              break;
            case 0x74:
              strBuf.push("\t");
              break;
            case 0x62:
              strBuf.push("\b");
              break;
            case 0x66:
              strBuf.push("\f");
              break;
            case 0x5c:
            case 0x28:
            case 0x29:
              strBuf.push(String.fromCharCode(ch));
              break;
            case 0x30:
            case 0x31:
            case 0x32:
            case 0x33:
            case 0x34:
            case 0x35:
            case 0x36:
            case 0x37:
              let x = ch & 0x0f;
              ch = this.nextChar();
              charBuffered = true;
              if (ch >= 0x30 && ch <= 0x37) {
                x = (x << 3) + (ch & 0x0f);
                ch = this.nextChar();
                if (ch >= 0x30 && ch <= 0x37) {
                  charBuffered = false;
                  x = (x << 3) + (ch & 0x0f);
                }
              }
              strBuf.push(String.fromCharCode(x));
              break;
            case 0x0d:
              if (this.peekChar() === 0x0a) {
                this.nextChar();
              }
              break;
            case 0x0a:
              break;
            default:
              strBuf.push(String.fromCharCode(ch));
              break;
          }
          break;
        default:
          strBuf.push(String.fromCharCode(ch));
          break;
      }
      if (done) {
        break;
      }
      if (!charBuffered) {
        ch = this.nextChar();
      }
    }
    return strBuf.join("");
  }
  getName() {
    let ch, previousCh;
    const strBuf = this.strBuf;
    strBuf.length = 0;
    while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
      if (ch === 0x23) {
        ch = this.nextChar();
        if (specialChars[ch]) {
          (0, _util.warn)("Lexer_getName: " + "NUMBER SIGN (#) should be followed by a hexadecimal number.");
          strBuf.push("#");
          break;
        }
        const x = toHexDigit(ch);
        if (x !== -1) {
          previousCh = ch;
          ch = this.nextChar();
          const x2 = toHexDigit(ch);
          if (x2 === -1) {
            (0, _util.warn)(`Lexer_getName: Illegal digit (${String.fromCharCode(ch)}) ` + "in hexadecimal number.");
            strBuf.push("#", String.fromCharCode(previousCh));
            if (specialChars[ch]) {
              break;
            }
            strBuf.push(String.fromCharCode(ch));
            continue;
          }
          strBuf.push(String.fromCharCode(x << 4 | x2));
        } else {
          strBuf.push("#", String.fromCharCode(ch));
        }
      } else {
        strBuf.push(String.fromCharCode(ch));
      }
    }
    if (strBuf.length > 127) {
      (0, _util.warn)(`Name token is longer than allowed by the spec: ${strBuf.length}`);
    }
    return _primitives.Name.get(strBuf.join(""));
  }
  _hexStringWarn(ch) {
    const MAX_HEX_STRING_NUM_WARN = 5;
    if (this._hexStringNumWarn++ === MAX_HEX_STRING_NUM_WARN) {
      (0, _util.warn)("getHexString - ignoring additional invalid characters.");
      return;
    }
    if (this._hexStringNumWarn > MAX_HEX_STRING_NUM_WARN) {
      return;
    }
    (0, _util.warn)(`getHexString - ignoring invalid character: ${ch}`);
  }
  getHexString() {
    const strBuf = this.strBuf;
    strBuf.length = 0;
    let ch = this.currentChar;
    let isFirstHex = true;
    let firstDigit, secondDigit;
    this._hexStringNumWarn = 0;
    while (true) {
      if (ch < 0) {
        (0, _util.warn)("Unterminated hex string");
        break;
      } else if (ch === 0x3e) {
        this.nextChar();
        break;
      } else if (specialChars[ch] === 1) {
        ch = this.nextChar();
        continue;
      } else {
        if (isFirstHex) {
          firstDigit = toHexDigit(ch);
          if (firstDigit === -1) {
            this._hexStringWarn(ch);
            ch = this.nextChar();
            continue;
          }
        } else {
          secondDigit = toHexDigit(ch);
          if (secondDigit === -1) {
            this._hexStringWarn(ch);
            ch = this.nextChar();
            continue;
          }
          strBuf.push(String.fromCharCode(firstDigit << 4 | secondDigit));
        }
        isFirstHex = !isFirstHex;
        ch = this.nextChar();
      }
    }
    return strBuf.join("");
  }
  getObj() {
    let comment = false;
    let ch = this.currentChar;
    while (true) {
      if (ch < 0) {
        return _primitives.EOF;
      }
      if (comment) {
        if (ch === 0x0a || ch === 0x0d) {
          comment = false;
        }
      } else if (ch === 0x25) {
        comment = true;
      } else if (specialChars[ch] !== 1) {
        break;
      }
      ch = this.nextChar();
    }
    switch (ch | 0) {
      case 0x30:
      case 0x31:
      case 0x32:
      case 0x33:
      case 0x34:
      case 0x35:
      case 0x36:
      case 0x37:
      case 0x38:
      case 0x39:
      case 0x2b:
      case 0x2d:
      case 0x2e:
        return this.getNumber();
      case 0x28:
        return this.getString();
      case 0x2f:
        return this.getName();
      case 0x5b:
        this.nextChar();
        return _primitives.Cmd.get("[");
      case 0x5d:
        this.nextChar();
        return _primitives.Cmd.get("]");
      case 0x3c:
        ch = this.nextChar();
        if (ch === 0x3c) {
          this.nextChar();
          return _primitives.Cmd.get("<<");
        }
        return this.getHexString();
      case 0x3e:
        ch = this.nextChar();
        if (ch === 0x3e) {
          this.nextChar();
          return _primitives.Cmd.get(">>");
        }
        return _primitives.Cmd.get(">");
      case 0x7b:
        this.nextChar();
        return _primitives.Cmd.get("{");
      case 0x7d:
        this.nextChar();
        return _primitives.Cmd.get("}");
      case 0x29:
        this.nextChar();
        throw new _util.FormatError(`Illegal character: ${ch}`);
    }
    let str = String.fromCharCode(ch);
    if (ch < 0x20 || ch > 0x7f) {
      const nextCh = this.peekChar();
      if (nextCh >= 0x20 && nextCh <= 0x7f) {
        this.nextChar();
        return _primitives.Cmd.get(str);
      }
    }
    const knownCommands = this.knownCommands;
    let knownCommandFound = knownCommands && knownCommands[str] !== undefined;
    while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {
      const possibleCommand = str + String.fromCharCode(ch);
      if (knownCommandFound && knownCommands[possibleCommand] === undefined) {
        break;
      }
      if (str.length === 128) {
        throw new _util.FormatError(`Command token too long: ${str.length}`);
      }
      str = possibleCommand;
      knownCommandFound = knownCommands && knownCommands[str] !== undefined;
    }
    if (str === "true") {
      return true;
    }
    if (str === "false") {
      return false;
    }
    if (str === "null") {
      return null;
    }
    if (str === "BI") {
      this.beginInlineImagePos = this.stream.pos;
    }
    return _primitives.Cmd.get(str);
  }
  peekObj() {
    const streamPos = this.stream.pos,
      currentChar = this.currentChar,
      beginInlineImagePos = this.beginInlineImagePos;
    let nextObj;
    try {
      nextObj = this.getObj();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`peekObj: ${ex}`);
    }
    this.stream.pos = streamPos;
    this.currentChar = currentChar;
    this.beginInlineImagePos = beginInlineImagePos;
    return nextObj;
  }
  skipToNextLine() {
    let ch = this.currentChar;
    while (ch >= 0) {
      if (ch === 0x0d) {
        ch = this.nextChar();
        if (ch === 0x0a) {
          this.nextChar();
        }
        break;
      } else if (ch === 0x0a) {
        this.nextChar();
        break;
      }
      ch = this.nextChar();
    }
  }
}
exports.Lexer = Lexer;
class Linearization {
  static create(stream) {
    function getInt(linDict, name, allowZeroValue = false) {
      const obj = linDict.get(name);
      if (Number.isInteger(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
        return obj;
      }
      throw new Error(`The "${name}" parameter in the linearization ` + "dictionary is invalid.");
    }
    function getHints(linDict) {
      const hints = linDict.get("H");
      let hintsLength;
      if (Array.isArray(hints) && ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
        for (let index = 0; index < hintsLength; index++) {
          const hint = hints[index];
          if (!(Number.isInteger(hint) && hint > 0)) {
            throw new Error(`Hint (${index}) in the linearization dictionary is invalid.`);
          }
        }
        return hints;
      }
      throw new Error("Hint array in the linearization dictionary is invalid.");
    }
    const parser = new Parser({
      lexer: new Lexer(stream),
      xref: null
    });
    const obj1 = parser.getObj();
    const obj2 = parser.getObj();
    const obj3 = parser.getObj();
    const linDict = parser.getObj();
    let obj, length;
    if (!(Number.isInteger(obj1) && Number.isInteger(obj2) && (0, _primitives.isCmd)(obj3, "obj") && linDict instanceof _primitives.Dict && typeof (obj = linDict.get("Linearized")) === "number" && obj > 0)) {
      return null;
    } else if ((length = getInt(linDict, "L")) !== stream.length) {
      throw new Error('The "L" parameter in the linearization dictionary ' + "does not equal the stream length.");
    }
    return {
      length,
      hints: getHints(linDict),
      objectNumberFirst: getInt(linDict, "O"),
      endFirst: getInt(linDict, "E"),
      numPages: getInt(linDict, "N"),
      mainXRefEntriesOffset: getInt(linDict, "T"),
      pageFirst: linDict.has("P") ? getInt(linDict, "P", true) : 0
    };
  }
}
exports.Linearization = Linearization;

/***/ }),
/* 16 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Ascii85Stream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
var _core_utils = __w_pdfjs_require__(4);
class Ascii85Stream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength) {
    if (maybeLength) {
      maybeLength *= 0.8;
    }
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    this.input = new Uint8Array(5);
  }
  readBlock() {
    const TILDA_CHAR = 0x7e;
    const Z_LOWER_CHAR = 0x7a;
    const EOF = -1;
    const str = this.str;
    let c = str.getByte();
    while ((0, _core_utils.isWhiteSpace)(c)) {
      c = str.getByte();
    }
    if (c === EOF || c === TILDA_CHAR) {
      this.eof = true;
      return;
    }
    const bufferLength = this.bufferLength;
    let buffer, i;
    if (c === Z_LOWER_CHAR) {
      buffer = this.ensureBuffer(bufferLength + 4);
      for (i = 0; i < 4; ++i) {
        buffer[bufferLength + i] = 0;
      }
      this.bufferLength += 4;
    } else {
      const input = this.input;
      input[0] = c;
      for (i = 1; i < 5; ++i) {
        c = str.getByte();
        while ((0, _core_utils.isWhiteSpace)(c)) {
          c = str.getByte();
        }
        input[i] = c;
        if (c === EOF || c === TILDA_CHAR) {
          break;
        }
      }
      buffer = this.ensureBuffer(bufferLength + i - 1);
      this.bufferLength += i - 1;
      if (i < 5) {
        for (; i < 5; ++i) {
          input[i] = 0x21 + 84;
        }
        this.eof = true;
      }
      let t = 0;
      for (i = 0; i < 5; ++i) {
        t = t * 85 + (input[i] - 0x21);
      }
      for (i = 3; i >= 0; --i) {
        buffer[bufferLength + i] = t & 0xff;
        t >>= 8;
      }
    }
  }
}
exports.Ascii85Stream = Ascii85Stream;

/***/ }),
/* 17 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.StreamsSequenceStream = exports.DecodeStream = void 0;
var _base_stream = __w_pdfjs_require__(5);
var _stream = __w_pdfjs_require__(8);
const emptyBuffer = new Uint8Array(0);
class DecodeStream extends _base_stream.BaseStream {
  constructor(maybeMinBufferLength) {
    super();
    this._rawMinBufferLength = maybeMinBufferLength || 0;
    this.pos = 0;
    this.bufferLength = 0;
    this.eof = false;
    this.buffer = emptyBuffer;
    this.minBufferLength = 512;
    if (maybeMinBufferLength) {
      while (this.minBufferLength < maybeMinBufferLength) {
        this.minBufferLength *= 2;
      }
    }
  }
  get isEmpty() {
    while (!this.eof && this.bufferLength === 0) {
      this.readBlock();
    }
    return this.bufferLength === 0;
  }
  ensureBuffer(requested) {
    const buffer = this.buffer;
    if (requested <= buffer.byteLength) {
      return buffer;
    }
    let size = this.minBufferLength;
    while (size < requested) {
      size *= 2;
    }
    const buffer2 = new Uint8Array(size);
    buffer2.set(buffer);
    return this.buffer = buffer2;
  }
  getByte() {
    const pos = this.pos;
    while (this.bufferLength <= pos) {
      if (this.eof) {
        return -1;
      }
      this.readBlock();
    }
    return this.buffer[this.pos++];
  }
  getBytes(length) {
    const pos = this.pos;
    let end;
    if (length) {
      this.ensureBuffer(pos + length);
      end = pos + length;
      while (!this.eof && this.bufferLength < end) {
        this.readBlock();
      }
      const bufEnd = this.bufferLength;
      if (end > bufEnd) {
        end = bufEnd;
      }
    } else {
      while (!this.eof) {
        this.readBlock();
      }
      end = this.bufferLength;
    }
    this.pos = end;
    return this.buffer.subarray(pos, end);
  }
  reset() {
    this.pos = 0;
  }
  makeSubStream(start, length, dict = null) {
    if (length === undefined) {
      while (!this.eof) {
        this.readBlock();
      }
    } else {
      const end = start + length;
      while (this.bufferLength <= end && !this.eof) {
        this.readBlock();
      }
    }
    return new _stream.Stream(this.buffer, start, length, dict);
  }
  getBaseStreams() {
    return this.str ? this.str.getBaseStreams() : null;
  }
}
exports.DecodeStream = DecodeStream;
class StreamsSequenceStream extends DecodeStream {
  constructor(streams, onError = null) {
    let maybeLength = 0;
    for (const stream of streams) {
      maybeLength += stream instanceof DecodeStream ? stream._rawMinBufferLength : stream.length;
    }
    super(maybeLength);
    this.streams = streams;
    this._onError = onError;
  }
  readBlock() {
    const streams = this.streams;
    if (streams.length === 0) {
      this.eof = true;
      return;
    }
    const stream = streams.shift();
    let chunk;
    try {
      chunk = stream.getBytes();
    } catch (reason) {
      if (this._onError) {
        this._onError(reason, stream.dict && stream.dict.objId);
        return;
      }
      throw reason;
    }
    const bufferLength = this.bufferLength;
    const newLength = bufferLength + chunk.length;
    const buffer = this.ensureBuffer(newLength);
    buffer.set(chunk, bufferLength);
    this.bufferLength = newLength;
  }
  getBaseStreams() {
    const baseStreamsBuf = [];
    for (const stream of this.streams) {
      const baseStreams = stream.getBaseStreams();
      if (baseStreams) {
        baseStreamsBuf.push(...baseStreams);
      }
    }
    return baseStreamsBuf.length > 0 ? baseStreamsBuf : null;
  }
}
exports.StreamsSequenceStream = StreamsSequenceStream;

/***/ }),
/* 18 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.AsciiHexStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
class AsciiHexStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength) {
    if (maybeLength) {
      maybeLength *= 0.5;
    }
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    this.firstDigit = -1;
  }
  readBlock() {
    const UPSTREAM_BLOCK_SIZE = 8000;
    const bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
    if (!bytes.length) {
      this.eof = true;
      return;
    }
    const maxDecodeLength = bytes.length + 1 >> 1;
    const buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
    let bufferLength = this.bufferLength;
    let firstDigit = this.firstDigit;
    for (const ch of bytes) {
      let digit;
      if (ch >= 0x30 && ch <= 0x39) {
        digit = ch & 0x0f;
      } else if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
        digit = (ch & 0x0f) + 9;
      } else if (ch === 0x3e) {
        this.eof = true;
        break;
      } else {
        continue;
      }
      if (firstDigit < 0) {
        firstDigit = digit;
      } else {
        buffer[bufferLength++] = firstDigit << 4 | digit;
        firstDigit = -1;
      }
    }
    if (firstDigit >= 0 && this.eof) {
      buffer[bufferLength++] = firstDigit << 4;
      firstDigit = -1;
    }
    this.firstDigit = firstDigit;
    this.bufferLength = bufferLength;
  }
}
exports.AsciiHexStream = AsciiHexStream;

/***/ }),
/* 19 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CCITTFaxStream = void 0;
var _ccitt = __w_pdfjs_require__(20);
var _decode_stream = __w_pdfjs_require__(17);
var _primitives = __w_pdfjs_require__(3);
class CCITTFaxStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength, params) {
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    if (!(params instanceof _primitives.Dict)) {
      params = _primitives.Dict.empty;
    }
    const source = {
      next() {
        return str.getByte();
      }
    };
    this.ccittFaxDecoder = new _ccitt.CCITTFaxDecoder(source, {
      K: params.get("K"),
      EndOfLine: params.get("EndOfLine"),
      EncodedByteAlign: params.get("EncodedByteAlign"),
      Columns: params.get("Columns"),
      Rows: params.get("Rows"),
      EndOfBlock: params.get("EndOfBlock"),
      BlackIs1: params.get("BlackIs1")
    });
  }
  readBlock() {
    while (!this.eof) {
      const c = this.ccittFaxDecoder.readNextChar();
      if (c === -1) {
        this.eof = true;
        return;
      }
      this.ensureBuffer(this.bufferLength + 1);
      this.buffer[this.bufferLength++] = c;
    }
  }
}
exports.CCITTFaxStream = CCITTFaxStream;

/***/ }),
/* 20 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CCITTFaxDecoder = void 0;
var _util = __w_pdfjs_require__(2);
const ccittEOL = -2;
const ccittEOF = -1;
const twoDimPass = 0;
const twoDimHoriz = 1;
const twoDimVert0 = 2;
const twoDimVertR1 = 3;
const twoDimVertL1 = 4;
const twoDimVertR2 = 5;
const twoDimVertL2 = 6;
const twoDimVertR3 = 7;
const twoDimVertL3 = 8;
const twoDimTable = [[-1, -1], [-1, -1], [7, twoDimVertL3], [7, twoDimVertR3], [6, twoDimVertL2], [6, twoDimVertL2], [6, twoDimVertR2], [6, twoDimVertR2], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0]];
const whiteTable1 = [[-1, -1], [12, ccittEOL], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [11, 1792], [11, 1792], [12, 1984], [12, 2048], [12, 2112], [12, 2176], [12, 2240], [12, 2304], [11, 1856], [11, 1856], [11, 1920], [11, 1920], [12, 2368], [12, 2432], [12, 2496], [12, 2560]];
const whiteTable2 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [8, 29], [8, 29], [8, 30], [8, 30], [8, 45], [8, 45], [8, 46], [8, 46], [7, 22], [7, 22], [7, 22], [7, 22], [7, 23], [7, 23], [7, 23], [7, 23], [8, 47], [8, 47], [8, 48], [8, 48], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [7, 20], [7, 20], [7, 20], [7, 20], [8, 33], [8, 33], [8, 34], [8, 34], [8, 35], [8, 35], [8, 36], [8, 36], [8, 37], [8, 37], [8, 38], [8, 38], [7, 19], [7, 19], [7, 19], [7, 19], [8, 31], [8, 31], [8, 32], [8, 32], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [8, 53], [8, 53], [8, 54], [8, 54], [7, 26], [7, 26], [7, 26], [7, 26], [8, 39], [8, 39], [8, 40], [8, 40], [8, 41], [8, 41], [8, 42], [8, 42], [8, 43], [8, 43], [8, 44], [8, 44], [7, 21], [7, 21], [7, 21], [7, 21], [7, 28], [7, 28], [7, 28], [7, 28], [8, 61], [8, 61], [8, 62], [8, 62], [8, 63], [8, 63], [8, 0], [8, 0], [8, 320], [8, 320], [8, 384], [8, 384], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [7, 27], [7, 27], [7, 27], [7, 27], [8, 59], [8, 59], [8, 60], [8, 60], [9, 1472], [9, 1536], [9, 1600], [9, 1728], [7, 18], [7, 18], [7, 18], [7, 18], [7, 24], [7, 24], [7, 24], [7, 24], [8, 49], [8, 49], [8, 50], [8, 50], [8, 51], [8, 51], [8, 52], [8, 52], [7, 25], [7, 25], [7, 25], [7, 25], [8, 55], [8, 55], [8, 56], [8, 56], [8, 57], [8, 57], [8, 58], [8, 58], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [8, 448], [8, 448], [8, 512], [8, 512], [9, 704], [9, 768], [8, 640], [8, 640], [8, 576], [8, 576], [9, 832], [9, 896], [9, 960], [9, 1024], [9, 1088], [9, 1152], [9, 1216], [9, 1280], [9, 1344], [9, 1408], [7, 256], [7, 256], [7, 256], [7, 256], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7]];
const blackTable1 = [[-1, -1], [-1, -1], [12, ccittEOL], [12, ccittEOL], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [11, 1792], [11, 1792], [11, 1792], [11, 1792], [12, 1984], [12, 1984], [12, 2048], [12, 2048], [12, 2112], [12, 2112], [12, 2176], [12, 2176], [12, 2240], [12, 2240], [12, 2304], [12, 2304], [11, 1856], [11, 1856], [11, 1856], [11, 1856], [11, 1920], [11, 1920], [11, 1920], [11, 1920], [12, 2368], [12, 2368], [12, 2432], [12, 2432], [12, 2496], [12, 2496], [12, 2560], [12, 2560], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [12, 52], [12, 52], [13, 640], [13, 704], [13, 768], [13, 832], [12, 55], [12, 55], [12, 56], [12, 56], [13, 1280], [13, 1344], [13, 1408], [13, 1472], [12, 59], [12, 59], [12, 60], [12, 60], [13, 1536], [13, 1600], [11, 24], [11, 24], [11, 24], [11, 24], [11, 25], [11, 25], [11, 25], [11, 25], [13, 1664], [13, 1728], [12, 320], [12, 320], [12, 384], [12, 384], [12, 448], [12, 448], [13, 512], [13, 576], [12, 53], [12, 53], [12, 54], [12, 54], [13, 896], [13, 960], [13, 1024], [13, 1088], [13, 1152], [13, 1216], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64]];
const blackTable2 = [[8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [11, 23], [11, 23], [12, 50], [12, 51], [12, 44], [12, 45], [12, 46], [12, 47], [12, 57], [12, 58], [12, 61], [12, 256], [10, 16], [10, 16], [10, 16], [10, 16], [10, 17], [10, 17], [10, 17], [10, 17], [12, 48], [12, 49], [12, 62], [12, 63], [12, 30], [12, 31], [12, 32], [12, 33], [12, 40], [12, 41], [11, 22], [11, 22], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [12, 128], [12, 192], [12, 26], [12, 27], [12, 28], [12, 29], [11, 19], [11, 19], [11, 20], [11, 20], [12, 34], [12, 35], [12, 36], [12, 37], [12, 38], [12, 39], [11, 21], [11, 21], [12, 42], [12, 43], [10, 0], [10, 0], [10, 0], [10, 0], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12]];
const blackTable3 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [6, 9], [6, 8], [5, 7], [5, 7], [4, 6], [4, 6], [4, 6], [4, 6], [4, 5], [4, 5], [4, 5], [4, 5], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]];
class CCITTFaxDecoder {
  constructor(source, options = {}) {
    if (!source || typeof source.next !== "function") {
      throw new Error('CCITTFaxDecoder - invalid "source" parameter.');
    }
    this.source = source;
    this.eof = false;
    this.encoding = options.K || 0;
    this.eoline = options.EndOfLine || false;
    this.byteAlign = options.EncodedByteAlign || false;
    this.columns = options.Columns || 1728;
    this.rows = options.Rows || 0;
    let eoblock = options.EndOfBlock;
    if (eoblock === null || eoblock === undefined) {
      eoblock = true;
    }
    this.eoblock = eoblock;
    this.black = options.BlackIs1 || false;
    this.codingLine = new Uint32Array(this.columns + 1);
    this.refLine = new Uint32Array(this.columns + 2);
    this.codingLine[0] = this.columns;
    this.codingPos = 0;
    this.row = 0;
    this.nextLine2D = this.encoding < 0;
    this.inputBits = 0;
    this.inputBuf = 0;
    this.outputBits = 0;
    this.rowsDone = false;
    let code1;
    while ((code1 = this._lookBits(12)) === 0) {
      this._eatBits(1);
    }
    if (code1 === 1) {
      this._eatBits(12);
    }
    if (this.encoding > 0) {
      this.nextLine2D = !this._lookBits(1);
      this._eatBits(1);
    }
  }
  readNextChar() {
    if (this.eof) {
      return -1;
    }
    const refLine = this.refLine;
    const codingLine = this.codingLine;
    const columns = this.columns;
    let refPos, blackPixels, bits, i;
    if (this.outputBits === 0) {
      if (this.rowsDone) {
        this.eof = true;
      }
      if (this.eof) {
        return -1;
      }
      this.err = false;
      let code1, code2, code3;
      if (this.nextLine2D) {
        for (i = 0; codingLine[i] < columns; ++i) {
          refLine[i] = codingLine[i];
        }
        refLine[i++] = columns;
        refLine[i] = columns;
        codingLine[0] = 0;
        this.codingPos = 0;
        refPos = 0;
        blackPixels = 0;
        while (codingLine[this.codingPos] < columns) {
          code1 = this._getTwoDimCode();
          switch (code1) {
            case twoDimPass:
              this._addPixels(refLine[refPos + 1], blackPixels);
              if (refLine[refPos + 1] < columns) {
                refPos += 2;
              }
              break;
            case twoDimHoriz:
              code1 = code2 = 0;
              if (blackPixels) {
                do {
                  code1 += code3 = this._getBlackCode();
                } while (code3 >= 64);
                do {
                  code2 += code3 = this._getWhiteCode();
                } while (code3 >= 64);
              } else {
                do {
                  code1 += code3 = this._getWhiteCode();
                } while (code3 >= 64);
                do {
                  code2 += code3 = this._getBlackCode();
                } while (code3 >= 64);
              }
              this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
              if (codingLine[this.codingPos] < columns) {
                this._addPixels(codingLine[this.codingPos] + code2, blackPixels ^ 1);
              }
              while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                refPos += 2;
              }
              break;
            case twoDimVertR3:
              this._addPixels(refLine[refPos] + 3, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                ++refPos;
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVertR2:
              this._addPixels(refLine[refPos] + 2, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                ++refPos;
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVertR1:
              this._addPixels(refLine[refPos] + 1, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                ++refPos;
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVert0:
              this._addPixels(refLine[refPos], blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                ++refPos;
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVertL3:
              this._addPixelsNeg(refLine[refPos] - 3, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                if (refPos > 0) {
                  --refPos;
                } else {
                  ++refPos;
                }
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVertL2:
              this._addPixelsNeg(refLine[refPos] - 2, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                if (refPos > 0) {
                  --refPos;
                } else {
                  ++refPos;
                }
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case twoDimVertL1:
              this._addPixelsNeg(refLine[refPos] - 1, blackPixels);
              blackPixels ^= 1;
              if (codingLine[this.codingPos] < columns) {
                if (refPos > 0) {
                  --refPos;
                } else {
                  ++refPos;
                }
                while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
                  refPos += 2;
                }
              }
              break;
            case ccittEOF:
              this._addPixels(columns, 0);
              this.eof = true;
              break;
            default:
              (0, _util.info)("bad 2d code");
              this._addPixels(columns, 0);
              this.err = true;
          }
        }
      } else {
        codingLine[0] = 0;
        this.codingPos = 0;
        blackPixels = 0;
        while (codingLine[this.codingPos] < columns) {
          code1 = 0;
          if (blackPixels) {
            do {
              code1 += code3 = this._getBlackCode();
            } while (code3 >= 64);
          } else {
            do {
              code1 += code3 = this._getWhiteCode();
            } while (code3 >= 64);
          }
          this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
          blackPixels ^= 1;
        }
      }
      let gotEOL = false;
      if (this.byteAlign) {
        this.inputBits &= ~7;
      }
      if (!this.eoblock && this.row === this.rows - 1) {
        this.rowsDone = true;
      } else {
        code1 = this._lookBits(12);
        if (this.eoline) {
          while (code1 !== ccittEOF && code1 !== 1) {
            this._eatBits(1);
            code1 = this._lookBits(12);
          }
        } else {
          while (code1 === 0) {
            this._eatBits(1);
            code1 = this._lookBits(12);
          }
        }
        if (code1 === 1) {
          this._eatBits(12);
          gotEOL = true;
        } else if (code1 === ccittEOF) {
          this.eof = true;
        }
      }
      if (!this.eof && this.encoding > 0 && !this.rowsDone) {
        this.nextLine2D = !this._lookBits(1);
        this._eatBits(1);
      }
      if (this.eoblock && gotEOL && this.byteAlign) {
        code1 = this._lookBits(12);
        if (code1 === 1) {
          this._eatBits(12);
          if (this.encoding > 0) {
            this._lookBits(1);
            this._eatBits(1);
          }
          if (this.encoding >= 0) {
            for (i = 0; i < 4; ++i) {
              code1 = this._lookBits(12);
              if (code1 !== 1) {
                (0, _util.info)("bad rtc code: " + code1);
              }
              this._eatBits(12);
              if (this.encoding > 0) {
                this._lookBits(1);
                this._eatBits(1);
              }
            }
          }
          this.eof = true;
        }
      } else if (this.err && this.eoline) {
        while (true) {
          code1 = this._lookBits(13);
          if (code1 === ccittEOF) {
            this.eof = true;
            return -1;
          }
          if (code1 >> 1 === 1) {
            break;
          }
          this._eatBits(1);
        }
        this._eatBits(12);
        if (this.encoding > 0) {
          this._eatBits(1);
          this.nextLine2D = !(code1 & 1);
        }
      }
      if (codingLine[0] > 0) {
        this.outputBits = codingLine[this.codingPos = 0];
      } else {
        this.outputBits = codingLine[this.codingPos = 1];
      }
      this.row++;
    }
    let c;
    if (this.outputBits >= 8) {
      c = this.codingPos & 1 ? 0 : 0xff;
      this.outputBits -= 8;
      if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
        this.codingPos++;
        this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
      }
    } else {
      bits = 8;
      c = 0;
      do {
        if (typeof this.outputBits !== "number") {
          throw new _util.FormatError('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');
        }
        if (this.outputBits > bits) {
          c <<= bits;
          if (!(this.codingPos & 1)) {
            c |= 0xff >> 8 - bits;
          }
          this.outputBits -= bits;
          bits = 0;
        } else {
          c <<= this.outputBits;
          if (!(this.codingPos & 1)) {
            c |= 0xff >> 8 - this.outputBits;
          }
          bits -= this.outputBits;
          this.outputBits = 0;
          if (codingLine[this.codingPos] < columns) {
            this.codingPos++;
            this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
          } else if (bits > 0) {
            c <<= bits;
            bits = 0;
          }
        }
      } while (bits);
    }
    if (this.black) {
      c ^= 0xff;
    }
    return c;
  }
  _addPixels(a1, blackPixels) {
    const codingLine = this.codingLine;
    let codingPos = this.codingPos;
    if (a1 > codingLine[codingPos]) {
      if (a1 > this.columns) {
        (0, _util.info)("row is wrong length");
        this.err = true;
        a1 = this.columns;
      }
      if (codingPos & 1 ^ blackPixels) {
        ++codingPos;
      }
      codingLine[codingPos] = a1;
    }
    this.codingPos = codingPos;
  }
  _addPixelsNeg(a1, blackPixels) {
    const codingLine = this.codingLine;
    let codingPos = this.codingPos;
    if (a1 > codingLine[codingPos]) {
      if (a1 > this.columns) {
        (0, _util.info)("row is wrong length");
        this.err = true;
        a1 = this.columns;
      }
      if (codingPos & 1 ^ blackPixels) {
        ++codingPos;
      }
      codingLine[codingPos] = a1;
    } else if (a1 < codingLine[codingPos]) {
      if (a1 < 0) {
        (0, _util.info)("invalid code");
        this.err = true;
        a1 = 0;
      }
      while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
        --codingPos;
      }
      codingLine[codingPos] = a1;
    }
    this.codingPos = codingPos;
  }
  _findTableCode(start, end, table, limit) {
    const limitValue = limit || 0;
    for (let i = start; i <= end; ++i) {
      let code = this._lookBits(i);
      if (code === ccittEOF) {
        return [true, 1, false];
      }
      if (i < end) {
        code <<= end - i;
      }
      if (!limitValue || code >= limitValue) {
        const p = table[code - limitValue];
        if (p[0] === i) {
          this._eatBits(i);
          return [true, p[1], true];
        }
      }
    }
    return [false, 0, false];
  }
  _getTwoDimCode() {
    let code = 0;
    let p;
    if (this.eoblock) {
      code = this._lookBits(7);
      p = twoDimTable[code];
      if (p && p[0] > 0) {
        this._eatBits(p[0]);
        return p[1];
      }
    } else {
      const result = this._findTableCode(1, 7, twoDimTable);
      if (result[0] && result[2]) {
        return result[1];
      }
    }
    (0, _util.info)("Bad two dim code");
    return ccittEOF;
  }
  _getWhiteCode() {
    let code = 0;
    let p;
    if (this.eoblock) {
      code = this._lookBits(12);
      if (code === ccittEOF) {
        return 1;
      }
      if (code >> 5 === 0) {
        p = whiteTable1[code];
      } else {
        p = whiteTable2[code >> 3];
      }
      if (p[0] > 0) {
        this._eatBits(p[0]);
        return p[1];
      }
    } else {
      let result = this._findTableCode(1, 9, whiteTable2);
      if (result[0]) {
        return result[1];
      }
      result = this._findTableCode(11, 12, whiteTable1);
      if (result[0]) {
        return result[1];
      }
    }
    (0, _util.info)("bad white code");
    this._eatBits(1);
    return 1;
  }
  _getBlackCode() {
    let code, p;
    if (this.eoblock) {
      code = this._lookBits(13);
      if (code === ccittEOF) {
        return 1;
      }
      if (code >> 7 === 0) {
        p = blackTable1[code];
      } else if (code >> 9 === 0 && code >> 7 !== 0) {
        p = blackTable2[(code >> 1) - 64];
      } else {
        p = blackTable3[code >> 7];
      }
      if (p[0] > 0) {
        this._eatBits(p[0]);
        return p[1];
      }
    } else {
      let result = this._findTableCode(2, 6, blackTable3);
      if (result[0]) {
        return result[1];
      }
      result = this._findTableCode(7, 12, blackTable2, 64);
      if (result[0]) {
        return result[1];
      }
      result = this._findTableCode(10, 13, blackTable1);
      if (result[0]) {
        return result[1];
      }
    }
    (0, _util.info)("bad black code");
    this._eatBits(1);
    return 1;
  }
  _lookBits(n) {
    let c;
    while (this.inputBits < n) {
      if ((c = this.source.next()) === -1) {
        if (this.inputBits === 0) {
          return ccittEOF;
        }
        return this.inputBuf << n - this.inputBits & 0xffff >> 16 - n;
      }
      this.inputBuf = this.inputBuf << 8 | c;
      this.inputBits += 8;
    }
    return this.inputBuf >> this.inputBits - n & 0xffff >> 16 - n;
  }
  _eatBits(n) {
    if ((this.inputBits -= n) < 0) {
      this.inputBits = 0;
    }
  }
}
exports.CCITTFaxDecoder = CCITTFaxDecoder;

/***/ }),
/* 21 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FlateStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
var _util = __w_pdfjs_require__(2);
const codeLenCodeMap = new Int32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
const lengthDecode = new Int32Array([0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102]);
const distDecode = new Int32Array([0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001]);
const fixedLitCodeTab = [new Int32Array([0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8, 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8, 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8, 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4, 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec, 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc, 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2, 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2, 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da, 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6, 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6, 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6, 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe, 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1, 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1, 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1, 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5, 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5, 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5, 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd, 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3, 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3, 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb, 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb, 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7, 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf, 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef, 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df, 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff]), 9];
const fixedDistCodeTab = [new Int32Array([0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000]), 5];
class FlateStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength) {
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    const cmf = str.getByte();
    const flg = str.getByte();
    if (cmf === -1 || flg === -1) {
      throw new _util.FormatError(`Invalid header in flate stream: ${cmf}, ${flg}`);
    }
    if ((cmf & 0x0f) !== 0x08) {
      throw new _util.FormatError(`Unknown compression method in flate stream: ${cmf}, ${flg}`);
    }
    if (((cmf << 8) + flg) % 31 !== 0) {
      throw new _util.FormatError(`Bad FCHECK in flate stream: ${cmf}, ${flg}`);
    }
    if (flg & 0x20) {
      throw new _util.FormatError(`FDICT bit set in flate stream: ${cmf}, ${flg}`);
    }
    this.codeSize = 0;
    this.codeBuf = 0;
  }
  getBits(bits) {
    const str = this.str;
    let codeSize = this.codeSize;
    let codeBuf = this.codeBuf;
    let b;
    while (codeSize < bits) {
      if ((b = str.getByte()) === -1) {
        throw new _util.FormatError("Bad encoding in flate stream");
      }
      codeBuf |= b << codeSize;
      codeSize += 8;
    }
    b = codeBuf & (1 << bits) - 1;
    this.codeBuf = codeBuf >> bits;
    this.codeSize = codeSize -= bits;
    return b;
  }
  getCode(table) {
    const str = this.str;
    const codes = table[0];
    const maxLen = table[1];
    let codeSize = this.codeSize;
    let codeBuf = this.codeBuf;
    let b;
    while (codeSize < maxLen) {
      if ((b = str.getByte()) === -1) {
        break;
      }
      codeBuf |= b << codeSize;
      codeSize += 8;
    }
    const code = codes[codeBuf & (1 << maxLen) - 1];
    const codeLen = code >> 16;
    const codeVal = code & 0xffff;
    if (codeLen < 1 || codeSize < codeLen) {
      throw new _util.FormatError("Bad encoding in flate stream");
    }
    this.codeBuf = codeBuf >> codeLen;
    this.codeSize = codeSize - codeLen;
    return codeVal;
  }
  generateHuffmanTable(lengths) {
    const n = lengths.length;
    let maxLen = 0;
    let i;
    for (i = 0; i < n; ++i) {
      if (lengths[i] > maxLen) {
        maxLen = lengths[i];
      }
    }
    const size = 1 << maxLen;
    const codes = new Int32Array(size);
    for (let len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) {
      for (let val = 0; val < n; ++val) {
        if (lengths[val] === len) {
          let code2 = 0;
          let t = code;
          for (i = 0; i < len; ++i) {
            code2 = code2 << 1 | t & 1;
            t >>= 1;
          }
          for (i = code2; i < size; i += skip) {
            codes[i] = len << 16 | val;
          }
          ++code;
        }
      }
    }
    return [codes, maxLen];
  }
  readBlock() {
    let buffer, len;
    const str = this.str;
    let hdr = this.getBits(3);
    if (hdr & 1) {
      this.eof = true;
    }
    hdr >>= 1;
    if (hdr === 0) {
      let b;
      if ((b = str.getByte()) === -1) {
        throw new _util.FormatError("Bad block header in flate stream");
      }
      let blockLen = b;
      if ((b = str.getByte()) === -1) {
        throw new _util.FormatError("Bad block header in flate stream");
      }
      blockLen |= b << 8;
      if ((b = str.getByte()) === -1) {
        throw new _util.FormatError("Bad block header in flate stream");
      }
      let check = b;
      if ((b = str.getByte()) === -1) {
        throw new _util.FormatError("Bad block header in flate stream");
      }
      check |= b << 8;
      if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) {
        throw new _util.FormatError("Bad uncompressed block length in flate stream");
      }
      this.codeBuf = 0;
      this.codeSize = 0;
      const bufferLength = this.bufferLength,
        end = bufferLength + blockLen;
      buffer = this.ensureBuffer(end);
      this.bufferLength = end;
      if (blockLen === 0) {
        if (str.peekByte() === -1) {
          this.eof = true;
        }
      } else {
        const block = str.getBytes(blockLen);
        buffer.set(block, bufferLength);
        if (block.length < blockLen) {
          this.eof = true;
        }
      }
      return;
    }
    let litCodeTable;
    let distCodeTable;
    if (hdr === 1) {
      litCodeTable = fixedLitCodeTab;
      distCodeTable = fixedDistCodeTab;
    } else if (hdr === 2) {
      const numLitCodes = this.getBits(5) + 257;
      const numDistCodes = this.getBits(5) + 1;
      const numCodeLenCodes = this.getBits(4) + 4;
      const codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
      let i;
      for (i = 0; i < numCodeLenCodes; ++i) {
        codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
      }
      const codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
      len = 0;
      i = 0;
      const codes = numLitCodes + numDistCodes;
      const codeLengths = new Uint8Array(codes);
      let bitsLength, bitsOffset, what;
      while (i < codes) {
        const code = this.getCode(codeLenCodeTab);
        if (code === 16) {
          bitsLength = 2;
          bitsOffset = 3;
          what = len;
        } else if (code === 17) {
          bitsLength = 3;
          bitsOffset = 3;
          what = len = 0;
        } else if (code === 18) {
          bitsLength = 7;
          bitsOffset = 11;
          what = len = 0;
        } else {
          codeLengths[i++] = len = code;
          continue;
        }
        let repeatLength = this.getBits(bitsLength) + bitsOffset;
        while (repeatLength-- > 0) {
          codeLengths[i++] = what;
        }
      }
      litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
      distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
    } else {
      throw new _util.FormatError("Unknown block type in flate stream");
    }
    buffer = this.buffer;
    let limit = buffer ? buffer.length : 0;
    let pos = this.bufferLength;
    while (true) {
      let code1 = this.getCode(litCodeTable);
      if (code1 < 256) {
        if (pos + 1 >= limit) {
          buffer = this.ensureBuffer(pos + 1);
          limit = buffer.length;
        }
        buffer[pos++] = code1;
        continue;
      }
      if (code1 === 256) {
        this.bufferLength = pos;
        return;
      }
      code1 -= 257;
      code1 = lengthDecode[code1];
      let code2 = code1 >> 16;
      if (code2 > 0) {
        code2 = this.getBits(code2);
      }
      len = (code1 & 0xffff) + code2;
      code1 = this.getCode(distCodeTable);
      code1 = distDecode[code1];
      code2 = code1 >> 16;
      if (code2 > 0) {
        code2 = this.getBits(code2);
      }
      const dist = (code1 & 0xffff) + code2;
      if (pos + len >= limit) {
        buffer = this.ensureBuffer(pos + len);
        limit = buffer.length;
      }
      for (let k = 0; k < len; ++k, ++pos) {
        buffer[pos] = buffer[pos - dist];
      }
    }
  }
}
exports.FlateStream = FlateStream;

/***/ }),
/* 22 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Jbig2Stream = void 0;
var _base_stream = __w_pdfjs_require__(5);
var _decode_stream = __w_pdfjs_require__(17);
var _primitives = __w_pdfjs_require__(3);
var _jbig = __w_pdfjs_require__(23);
var _util = __w_pdfjs_require__(2);
class Jbig2Stream extends _decode_stream.DecodeStream {
  constructor(stream, maybeLength, params) {
    super(maybeLength);
    this.stream = stream;
    this.dict = stream.dict;
    this.maybeLength = maybeLength;
    this.params = params;
  }
  get bytes() {
    return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
  }
  ensureBuffer(requested) {}
  readBlock() {
    if (this.eof) {
      return;
    }
    const jbig2Image = new _jbig.Jbig2Image();
    const chunks = [];
    if (this.params instanceof _primitives.Dict) {
      const globalsStream = this.params.get("JBIG2Globals");
      if (globalsStream instanceof _base_stream.BaseStream) {
        const globals = globalsStream.getBytes();
        chunks.push({
          data: globals,
          start: 0,
          end: globals.length
        });
      }
    }
    chunks.push({
      data: this.bytes,
      start: 0,
      end: this.bytes.length
    });
    const data = jbig2Image.parseChunks(chunks);
    const dataLength = data.length;
    for (let i = 0; i < dataLength; i++) {
      data[i] ^= 0xff;
    }
    this.buffer = data;
    this.bufferLength = dataLength;
    this.eof = true;
  }
}
exports.Jbig2Stream = Jbig2Stream;

/***/ }),
/* 23 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Jbig2Image = void 0;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _arithmetic_decoder = __w_pdfjs_require__(24);
var _ccitt = __w_pdfjs_require__(20);
class Jbig2Error extends _util.BaseException {
  constructor(msg) {
    super(`JBIG2 error: ${msg}`, "Jbig2Error");
  }
}
class ContextCache {
  getContexts(id) {
    if (id in this) {
      return this[id];
    }
    return this[id] = new Int8Array(1 << 16);
  }
}
class DecodingContext {
  constructor(data, start, end) {
    this.data = data;
    this.start = start;
    this.end = end;
  }
  get decoder() {
    const decoder = new _arithmetic_decoder.ArithmeticDecoder(this.data, this.start, this.end);
    return (0, _util.shadow)(this, "decoder", decoder);
  }
  get contextCache() {
    const cache = new ContextCache();
    return (0, _util.shadow)(this, "contextCache", cache);
  }
}
const MAX_INT_32 = 2 ** 31 - 1;
const MIN_INT_32 = -(2 ** 31);
function decodeInteger(contextCache, procedure, decoder) {
  const contexts = contextCache.getContexts(procedure);
  let prev = 1;
  function readBits(length) {
    let v = 0;
    for (let i = 0; i < length; i++) {
      const bit = decoder.readBit(contexts, prev);
      prev = prev < 256 ? prev << 1 | bit : (prev << 1 | bit) & 511 | 256;
      v = v << 1 | bit;
    }
    return v >>> 0;
  }
  const sign = readBits(1);
  const value = readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(32) + 4436 : readBits(12) + 340 : readBits(8) + 84 : readBits(6) + 20 : readBits(4) + 4 : readBits(2);
  let signedValue;
  if (sign === 0) {
    signedValue = value;
  } else if (value > 0) {
    signedValue = -value;
  }
  if (signedValue >= MIN_INT_32 && signedValue <= MAX_INT_32) {
    return signedValue;
  }
  return null;
}
function decodeIAID(contextCache, decoder, codeLength) {
  const contexts = contextCache.getContexts("IAID");
  let prev = 1;
  for (let i = 0; i < codeLength; i++) {
    const bit = decoder.readBit(contexts, prev);
    prev = prev << 1 | bit;
  }
  if (codeLength < 31) {
    return prev & (1 << codeLength) - 1;
  }
  return prev & 0x7fffffff;
}
const SegmentTypes = ["SymbolDictionary", null, null, null, "IntermediateTextRegion", null, "ImmediateTextRegion", "ImmediateLosslessTextRegion", null, null, null, null, null, null, null, null, "PatternDictionary", null, null, null, "IntermediateHalftoneRegion", null, "ImmediateHalftoneRegion", "ImmediateLosslessHalftoneRegion", null, null, null, null, null, null, null, null, null, null, null, null, "IntermediateGenericRegion", null, "ImmediateGenericRegion", "ImmediateLosslessGenericRegion", "IntermediateGenericRefinementRegion", null, "ImmediateGenericRefinementRegion", "ImmediateLosslessGenericRefinementRegion", null, null, null, null, "PageInformation", "EndOfPage", "EndOfStripe", "EndOfFile", "Profiles", "Tables", null, null, null, null, null, null, null, null, "Extension"];
const CodingTemplates = [[{
  x: -1,
  y: -2
}, {
  x: 0,
  y: -2
}, {
  x: 1,
  y: -2
}, {
  x: -2,
  y: -1
}, {
  x: -1,
  y: -1
}, {
  x: 0,
  y: -1
}, {
  x: 1,
  y: -1
}, {
  x: 2,
  y: -1
}, {
  x: -4,
  y: 0
}, {
  x: -3,
  y: 0
}, {
  x: -2,
  y: 0
}, {
  x: -1,
  y: 0
}], [{
  x: -1,
  y: -2
}, {
  x: 0,
  y: -2
}, {
  x: 1,
  y: -2
}, {
  x: 2,
  y: -2
}, {
  x: -2,
  y: -1
}, {
  x: -1,
  y: -1
}, {
  x: 0,
  y: -1
}, {
  x: 1,
  y: -1
}, {
  x: 2,
  y: -1
}, {
  x: -3,
  y: 0
}, {
  x: -2,
  y: 0
}, {
  x: -1,
  y: 0
}], [{
  x: -1,
  y: -2
}, {
  x: 0,
  y: -2
}, {
  x: 1,
  y: -2
}, {
  x: -2,
  y: -1
}, {
  x: -1,
  y: -1
}, {
  x: 0,
  y: -1
}, {
  x: 1,
  y: -1
}, {
  x: -2,
  y: 0
}, {
  x: -1,
  y: 0
}], [{
  x: -3,
  y: -1
}, {
  x: -2,
  y: -1
}, {
  x: -1,
  y: -1
}, {
  x: 0,
  y: -1
}, {
  x: 1,
  y: -1
}, {
  x: -4,
  y: 0
}, {
  x: -3,
  y: 0
}, {
  x: -2,
  y: 0
}, {
  x: -1,
  y: 0
}]];
const RefinementTemplates = [{
  coding: [{
    x: 0,
    y: -1
  }, {
    x: 1,
    y: -1
  }, {
    x: -1,
    y: 0
  }],
  reference: [{
    x: 0,
    y: -1
  }, {
    x: 1,
    y: -1
  }, {
    x: -1,
    y: 0
  }, {
    x: 0,
    y: 0
  }, {
    x: 1,
    y: 0
  }, {
    x: -1,
    y: 1
  }, {
    x: 0,
    y: 1
  }, {
    x: 1,
    y: 1
  }]
}, {
  coding: [{
    x: -1,
    y: -1
  }, {
    x: 0,
    y: -1
  }, {
    x: 1,
    y: -1
  }, {
    x: -1,
    y: 0
  }],
  reference: [{
    x: 0,
    y: -1
  }, {
    x: -1,
    y: 0
  }, {
    x: 0,
    y: 0
  }, {
    x: 1,
    y: 0
  }, {
    x: 0,
    y: 1
  }, {
    x: 1,
    y: 1
  }]
}];
const ReusedContexts = [0x9b25, 0x0795, 0x00e5, 0x0195];
const RefinementReusedContexts = [0x0020, 0x0008];
function decodeBitmapTemplate0(width, height, decodingContext) {
  const decoder = decodingContext.decoder;
  const contexts = decodingContext.contextCache.getContexts("GB");
  const bitmap = [];
  let contextLabel, i, j, pixel, row, row1, row2;
  const OLD_PIXEL_MASK = 0x7bf7;
  for (i = 0; i < height; i++) {
    row = bitmap[i] = new Uint8Array(width);
    row1 = i < 1 ? row : bitmap[i - 1];
    row2 = i < 2 ? row : bitmap[i - 2];
    contextLabel = row2[0] << 13 | row2[1] << 12 | row2[2] << 11 | row1[0] << 7 | row1[1] << 6 | row1[2] << 5 | row1[3] << 4;
    for (j = 0; j < width; j++) {
      row[j] = pixel = decoder.readBit(contexts, contextLabel);
      contextLabel = (contextLabel & OLD_PIXEL_MASK) << 1 | (j + 3 < width ? row2[j + 3] << 11 : 0) | (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
    }
  }
  return bitmap;
}
function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) {
  if (mmr) {
    const input = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
    return decodeMMRBitmap(input, width, height, false);
  }
  if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
    return decodeBitmapTemplate0(width, height, decodingContext);
  }
  const useskip = !!skip;
  const template = CodingTemplates[templateIndex].concat(at);
  template.sort(function (a, b) {
    return a.y - b.y || a.x - b.x;
  });
  const templateLength = template.length;
  const templateX = new Int8Array(templateLength);
  const templateY = new Int8Array(templateLength);
  const changingTemplateEntries = [];
  let reuseMask = 0,
    minX = 0,
    maxX = 0,
    minY = 0;
  let c, k;
  for (k = 0; k < templateLength; k++) {
    templateX[k] = template[k].x;
    templateY[k] = template[k].y;
    minX = Math.min(minX, template[k].x);
    maxX = Math.max(maxX, template[k].x);
    minY = Math.min(minY, template[k].y);
    if (k < templateLength - 1 && template[k].y === template[k + 1].y && template[k].x === template[k + 1].x - 1) {
      reuseMask |= 1 << templateLength - 1 - k;
    } else {
      changingTemplateEntries.push(k);
    }
  }
  const changingEntriesLength = changingTemplateEntries.length;
  const changingTemplateX = new Int8Array(changingEntriesLength);
  const changingTemplateY = new Int8Array(changingEntriesLength);
  const changingTemplateBit = new Uint16Array(changingEntriesLength);
  for (c = 0; c < changingEntriesLength; c++) {
    k = changingTemplateEntries[c];
    changingTemplateX[c] = template[k].x;
    changingTemplateY[c] = template[k].y;
    changingTemplateBit[c] = 1 << templateLength - 1 - k;
  }
  const sbb_left = -minX;
  const sbb_top = -minY;
  const sbb_right = width - maxX;
  const pseudoPixelContext = ReusedContexts[templateIndex];
  let row = new Uint8Array(width);
  const bitmap = [];
  const decoder = decodingContext.decoder;
  const contexts = decodingContext.contextCache.getContexts("GB");
  let ltp = 0,
    j,
    i0,
    j0,
    contextLabel = 0,
    bit,
    shift;
  for (let i = 0; i < height; i++) {
    if (prediction) {
      const sltp = decoder.readBit(contexts, pseudoPixelContext);
      ltp ^= sltp;
      if (ltp) {
        bitmap.push(row);
        continue;
      }
    }
    row = new Uint8Array(row);
    bitmap.push(row);
    for (j = 0; j < width; j++) {
      if (useskip && skip[i][j]) {
        row[j] = 0;
        continue;
      }
      if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
        contextLabel = contextLabel << 1 & reuseMask;
        for (k = 0; k < changingEntriesLength; k++) {
          i0 = i + changingTemplateY[k];
          j0 = j + changingTemplateX[k];
          bit = bitmap[i0][j0];
          if (bit) {
            bit = changingTemplateBit[k];
            contextLabel |= bit;
          }
        }
      } else {
        contextLabel = 0;
        shift = templateLength - 1;
        for (k = 0; k < templateLength; k++, shift--) {
          j0 = j + templateX[k];
          if (j0 >= 0 && j0 < width) {
            i0 = i + templateY[k];
            if (i0 >= 0) {
              bit = bitmap[i0][j0];
              if (bit) {
                contextLabel |= bit << shift;
              }
            }
          }
        }
      }
      const pixel = decoder.readBit(contexts, contextLabel);
      row[j] = pixel;
    }
  }
  return bitmap;
}
function decodeRefinement(width, height, templateIndex, referenceBitmap, offsetX, offsetY, prediction, at, decodingContext) {
  let codingTemplate = RefinementTemplates[templateIndex].coding;
  if (templateIndex === 0) {
    codingTemplate = codingTemplate.concat([at[0]]);
  }
  const codingTemplateLength = codingTemplate.length;
  const codingTemplateX = new Int32Array(codingTemplateLength);
  const codingTemplateY = new Int32Array(codingTemplateLength);
  let k;
  for (k = 0; k < codingTemplateLength; k++) {
    codingTemplateX[k] = codingTemplate[k].x;
    codingTemplateY[k] = codingTemplate[k].y;
  }
  let referenceTemplate = RefinementTemplates[templateIndex].reference;
  if (templateIndex === 0) {
    referenceTemplate = referenceTemplate.concat([at[1]]);
  }
  const referenceTemplateLength = referenceTemplate.length;
  const referenceTemplateX = new Int32Array(referenceTemplateLength);
  const referenceTemplateY = new Int32Array(referenceTemplateLength);
  for (k = 0; k < referenceTemplateLength; k++) {
    referenceTemplateX[k] = referenceTemplate[k].x;
    referenceTemplateY[k] = referenceTemplate[k].y;
  }
  const referenceWidth = referenceBitmap[0].length;
  const referenceHeight = referenceBitmap.length;
  const pseudoPixelContext = RefinementReusedContexts[templateIndex];
  const bitmap = [];
  const decoder = decodingContext.decoder;
  const contexts = decodingContext.contextCache.getContexts("GR");
  let ltp = 0;
  for (let i = 0; i < height; i++) {
    if (prediction) {
      const sltp = decoder.readBit(contexts, pseudoPixelContext);
      ltp ^= sltp;
      if (ltp) {
        throw new Jbig2Error("prediction is not supported");
      }
    }
    const row = new Uint8Array(width);
    bitmap.push(row);
    for (let j = 0; j < width; j++) {
      let i0, j0;
      let contextLabel = 0;
      for (k = 0; k < codingTemplateLength; k++) {
        i0 = i + codingTemplateY[k];
        j0 = j + codingTemplateX[k];
        if (i0 < 0 || j0 < 0 || j0 >= width) {
          contextLabel <<= 1;
        } else {
          contextLabel = contextLabel << 1 | bitmap[i0][j0];
        }
      }
      for (k = 0; k < referenceTemplateLength; k++) {
        i0 = i + referenceTemplateY[k] - offsetY;
        j0 = j + referenceTemplateX[k] - offsetX;
        if (i0 < 0 || i0 >= referenceHeight || j0 < 0 || j0 >= referenceWidth) {
          contextLabel <<= 1;
        } else {
          contextLabel = contextLabel << 1 | referenceBitmap[i0][j0];
        }
      }
      const pixel = decoder.readBit(contexts, contextLabel);
      row[j] = pixel;
    }
  }
  return bitmap;
}
function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext, huffmanInput) {
  if (huffman && refinement) {
    throw new Jbig2Error("symbol refinement with Huffman is not supported");
  }
  const newSymbols = [];
  let currentHeight = 0;
  let symbolCodeLength = (0, _core_utils.log2)(symbols.length + numberOfNewSymbols);
  const decoder = decodingContext.decoder;
  const contextCache = decodingContext.contextCache;
  let tableB1, symbolWidths;
  if (huffman) {
    tableB1 = getStandardTable(1);
    symbolWidths = [];
    symbolCodeLength = Math.max(symbolCodeLength, 1);
  }
  while (newSymbols.length < numberOfNewSymbols) {
    const deltaHeight = huffman ? huffmanTables.tableDeltaHeight.decode(huffmanInput) : decodeInteger(contextCache, "IADH", decoder);
    currentHeight += deltaHeight;
    let currentWidth = 0,
      totalWidth = 0;
    const firstSymbol = huffman ? symbolWidths.length : 0;
    while (true) {
      const deltaWidth = huffman ? huffmanTables.tableDeltaWidth.decode(huffmanInput) : decodeInteger(contextCache, "IADW", decoder);
      if (deltaWidth === null) {
        break;
      }
      currentWidth += deltaWidth;
      totalWidth += currentWidth;
      let bitmap;
      if (refinement) {
        const numberOfInstances = decodeInteger(contextCache, "IAAI", decoder);
        if (numberOfInstances > 1) {
          bitmap = decodeTextRegion(huffman, refinement, currentWidth, currentHeight, 0, numberOfInstances, 1, symbols.concat(newSymbols), symbolCodeLength, 0, 0, 1, 0, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, 0, huffmanInput);
        } else {
          const symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
          const rdx = decodeInteger(contextCache, "IARDX", decoder);
          const rdy = decodeInteger(contextCache, "IARDY", decoder);
          const symbol = symbolId < symbols.length ? symbols[symbolId] : newSymbols[symbolId - symbols.length];
          bitmap = decodeRefinement(currentWidth, currentHeight, refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt, decodingContext);
        }
        newSymbols.push(bitmap);
      } else if (huffman) {
        symbolWidths.push(currentWidth);
      } else {
        bitmap = decodeBitmap(false, currentWidth, currentHeight, templateIndex, false, null, at, decodingContext);
        newSymbols.push(bitmap);
      }
    }
    if (huffman && !refinement) {
      const bitmapSize = huffmanTables.tableBitmapSize.decode(huffmanInput);
      huffmanInput.byteAlign();
      let collectiveBitmap;
      if (bitmapSize === 0) {
        collectiveBitmap = readUncompressedBitmap(huffmanInput, totalWidth, currentHeight);
      } else {
        const originalEnd = huffmanInput.end;
        const bitmapEnd = huffmanInput.position + bitmapSize;
        huffmanInput.end = bitmapEnd;
        collectiveBitmap = decodeMMRBitmap(huffmanInput, totalWidth, currentHeight, false);
        huffmanInput.end = originalEnd;
        huffmanInput.position = bitmapEnd;
      }
      const numberOfSymbolsDecoded = symbolWidths.length;
      if (firstSymbol === numberOfSymbolsDecoded - 1) {
        newSymbols.push(collectiveBitmap);
      } else {
        let i,
          y,
          xMin = 0,
          xMax,
          bitmapWidth,
          symbolBitmap;
        for (i = firstSymbol; i < numberOfSymbolsDecoded; i++) {
          bitmapWidth = symbolWidths[i];
          xMax = xMin + bitmapWidth;
          symbolBitmap = [];
          for (y = 0; y < currentHeight; y++) {
            symbolBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
          }
          newSymbols.push(symbolBitmap);
          xMin = xMax;
        }
      }
    }
  }
  const exportedSymbols = [],
    flags = [];
  let currentFlag = false,
    i,
    ii;
  const totalSymbolsLength = symbols.length + numberOfNewSymbols;
  while (flags.length < totalSymbolsLength) {
    let runLength = huffman ? tableB1.decode(huffmanInput) : decodeInteger(contextCache, "IAEX", decoder);
    while (runLength--) {
      flags.push(currentFlag);
    }
    currentFlag = !currentFlag;
  }
  for (i = 0, ii = symbols.length; i < ii; i++) {
    if (flags[i]) {
      exportedSymbols.push(symbols[i]);
    }
  }
  for (let j = 0; j < numberOfNewSymbols; i++, j++) {
    if (flags[i]) {
      exportedSymbols.push(newSymbols[j]);
    }
  }
  return exportedSymbols;
}
function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, logStripSize, huffmanInput) {
  if (huffman && refinement) {
    throw new Jbig2Error("refinement with Huffman is not supported");
  }
  const bitmap = [];
  let i, row;
  for (i = 0; i < height; i++) {
    row = new Uint8Array(width);
    if (defaultPixelValue) {
      for (let j = 0; j < width; j++) {
        row[j] = defaultPixelValue;
      }
    }
    bitmap.push(row);
  }
  const decoder = decodingContext.decoder;
  const contextCache = decodingContext.contextCache;
  let stripT = huffman ? -huffmanTables.tableDeltaT.decode(huffmanInput) : -decodeInteger(contextCache, "IADT", decoder);
  let firstS = 0;
  i = 0;
  while (i < numberOfSymbolInstances) {
    const deltaT = huffman ? huffmanTables.tableDeltaT.decode(huffmanInput) : decodeInteger(contextCache, "IADT", decoder);
    stripT += deltaT;
    const deltaFirstS = huffman ? huffmanTables.tableFirstS.decode(huffmanInput) : decodeInteger(contextCache, "IAFS", decoder);
    firstS += deltaFirstS;
    let currentS = firstS;
    do {
      let currentT = 0;
      if (stripSize > 1) {
        currentT = huffman ? huffmanInput.readBits(logStripSize) : decodeInteger(contextCache, "IAIT", decoder);
      }
      const t = stripSize * stripT + currentT;
      const symbolId = huffman ? huffmanTables.symbolIDTable.decode(huffmanInput) : decodeIAID(contextCache, decoder, symbolCodeLength);
      const applyRefinement = refinement && (huffman ? huffmanInput.readBit() : decodeInteger(contextCache, "IARI", decoder));
      let symbolBitmap = inputSymbols[symbolId];
      let symbolWidth = symbolBitmap[0].length;
      let symbolHeight = symbolBitmap.length;
      if (applyRefinement) {
        const rdw = decodeInteger(contextCache, "IARDW", decoder);
        const rdh = decodeInteger(contextCache, "IARDH", decoder);
        const rdx = decodeInteger(contextCache, "IARDX", decoder);
        const rdy = decodeInteger(contextCache, "IARDY", decoder);
        symbolWidth += rdw;
        symbolHeight += rdh;
        symbolBitmap = decodeRefinement(symbolWidth, symbolHeight, refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx, (rdh >> 1) + rdy, false, refinementAt, decodingContext);
      }
      const offsetT = t - (referenceCorner & 1 ? 0 : symbolHeight - 1);
      const offsetS = currentS - (referenceCorner & 2 ? symbolWidth - 1 : 0);
      let s2, t2, symbolRow;
      if (transposed) {
        for (s2 = 0; s2 < symbolHeight; s2++) {
          row = bitmap[offsetS + s2];
          if (!row) {
            continue;
          }
          symbolRow = symbolBitmap[s2];
          const maxWidth = Math.min(width - offsetT, symbolWidth);
          switch (combinationOperator) {
            case 0:
              for (t2 = 0; t2 < maxWidth; t2++) {
                row[offsetT + t2] |= symbolRow[t2];
              }
              break;
            case 2:
              for (t2 = 0; t2 < maxWidth; t2++) {
                row[offsetT + t2] ^= symbolRow[t2];
              }
              break;
            default:
              throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
          }
        }
        currentS += symbolHeight - 1;
      } else {
        for (t2 = 0; t2 < symbolHeight; t2++) {
          row = bitmap[offsetT + t2];
          if (!row) {
            continue;
          }
          symbolRow = symbolBitmap[t2];
          switch (combinationOperator) {
            case 0:
              for (s2 = 0; s2 < symbolWidth; s2++) {
                row[offsetS + s2] |= symbolRow[s2];
              }
              break;
            case 2:
              for (s2 = 0; s2 < symbolWidth; s2++) {
                row[offsetS + s2] ^= symbolRow[s2];
              }
              break;
            default:
              throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
          }
        }
        currentS += symbolWidth - 1;
      }
      i++;
      const deltaS = huffman ? huffmanTables.tableDeltaS.decode(huffmanInput) : decodeInteger(contextCache, "IADS", decoder);
      if (deltaS === null) {
        break;
      }
      currentS += deltaS + dsOffset;
    } while (true);
  }
  return bitmap;
}
function decodePatternDictionary(mmr, patternWidth, patternHeight, maxPatternIndex, template, decodingContext) {
  const at = [];
  if (!mmr) {
    at.push({
      x: -patternWidth,
      y: 0
    });
    if (template === 0) {
      at.push({
        x: -3,
        y: -1
      }, {
        x: 2,
        y: -2
      }, {
        x: -2,
        y: -2
      });
    }
  }
  const collectiveWidth = (maxPatternIndex + 1) * patternWidth;
  const collectiveBitmap = decodeBitmap(mmr, collectiveWidth, patternHeight, template, false, null, at, decodingContext);
  const patterns = [];
  for (let i = 0; i <= maxPatternIndex; i++) {
    const patternBitmap = [];
    const xMin = patternWidth * i;
    const xMax = xMin + patternWidth;
    for (let y = 0; y < patternHeight; y++) {
      patternBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
    }
    patterns.push(patternBitmap);
  }
  return patterns;
}
function decodeHalftoneRegion(mmr, patterns, template, regionWidth, regionHeight, defaultPixelValue, enableSkip, combinationOperator, gridWidth, gridHeight, gridOffsetX, gridOffsetY, gridVectorX, gridVectorY, decodingContext) {
  const skip = null;
  if (enableSkip) {
    throw new Jbig2Error("skip is not supported");
  }
  if (combinationOperator !== 0) {
    throw new Jbig2Error(`operator "${combinationOperator}" is not supported in halftone region`);
  }
  const regionBitmap = [];
  let i, j, row;
  for (i = 0; i < regionHeight; i++) {
    row = new Uint8Array(regionWidth);
    if (defaultPixelValue) {
      for (j = 0; j < regionWidth; j++) {
        row[j] = defaultPixelValue;
      }
    }
    regionBitmap.push(row);
  }
  const numberOfPatterns = patterns.length;
  const pattern0 = patterns[0];
  const patternWidth = pattern0[0].length,
    patternHeight = pattern0.length;
  const bitsPerValue = (0, _core_utils.log2)(numberOfPatterns);
  const at = [];
  if (!mmr) {
    at.push({
      x: template <= 1 ? 3 : 2,
      y: -1
    });
    if (template === 0) {
      at.push({
        x: -3,
        y: -1
      }, {
        x: 2,
        y: -2
      }, {
        x: -2,
        y: -2
      });
    }
  }
  const grayScaleBitPlanes = [];
  let mmrInput, bitmap;
  if (mmr) {
    mmrInput = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
  }
  for (i = bitsPerValue - 1; i >= 0; i--) {
    if (mmr) {
      bitmap = decodeMMRBitmap(mmrInput, gridWidth, gridHeight, true);
    } else {
      bitmap = decodeBitmap(false, gridWidth, gridHeight, template, false, skip, at, decodingContext);
    }
    grayScaleBitPlanes[i] = bitmap;
  }
  let mg, ng, bit, patternIndex, patternBitmap, x, y, patternRow, regionRow;
  for (mg = 0; mg < gridHeight; mg++) {
    for (ng = 0; ng < gridWidth; ng++) {
      bit = 0;
      patternIndex = 0;
      for (j = bitsPerValue - 1; j >= 0; j--) {
        bit ^= grayScaleBitPlanes[j][mg][ng];
        patternIndex |= bit << j;
      }
      patternBitmap = patterns[patternIndex];
      x = gridOffsetX + mg * gridVectorY + ng * gridVectorX >> 8;
      y = gridOffsetY + mg * gridVectorX - ng * gridVectorY >> 8;
      if (x >= 0 && x + patternWidth <= regionWidth && y >= 0 && y + patternHeight <= regionHeight) {
        for (i = 0; i < patternHeight; i++) {
          regionRow = regionBitmap[y + i];
          patternRow = patternBitmap[i];
          for (j = 0; j < patternWidth; j++) {
            regionRow[x + j] |= patternRow[j];
          }
        }
      } else {
        let regionX, regionY;
        for (i = 0; i < patternHeight; i++) {
          regionY = y + i;
          if (regionY < 0 || regionY >= regionHeight) {
            continue;
          }
          regionRow = regionBitmap[regionY];
          patternRow = patternBitmap[i];
          for (j = 0; j < patternWidth; j++) {
            regionX = x + j;
            if (regionX >= 0 && regionX < regionWidth) {
              regionRow[regionX] |= patternRow[j];
            }
          }
        }
      }
    }
  }
  return regionBitmap;
}
function readSegmentHeader(data, start) {
  const segmentHeader = {};
  segmentHeader.number = (0, _core_utils.readUint32)(data, start);
  const flags = data[start + 4];
  const segmentType = flags & 0x3f;
  if (!SegmentTypes[segmentType]) {
    throw new Jbig2Error("invalid segment type: " + segmentType);
  }
  segmentHeader.type = segmentType;
  segmentHeader.typeName = SegmentTypes[segmentType];
  segmentHeader.deferredNonRetain = !!(flags & 0x80);
  const pageAssociationFieldSize = !!(flags & 0x40);
  const referredFlags = data[start + 5];
  let referredToCount = referredFlags >> 5 & 7;
  const retainBits = [referredFlags & 31];
  let position = start + 6;
  if (referredFlags === 7) {
    referredToCount = (0, _core_utils.readUint32)(data, position - 1) & 0x1fffffff;
    position += 3;
    let bytes = referredToCount + 7 >> 3;
    retainBits[0] = data[position++];
    while (--bytes > 0) {
      retainBits.push(data[position++]);
    }
  } else if (referredFlags === 5 || referredFlags === 6) {
    throw new Jbig2Error("invalid referred-to flags");
  }
  segmentHeader.retainBits = retainBits;
  let referredToSegmentNumberSize = 4;
  if (segmentHeader.number <= 256) {
    referredToSegmentNumberSize = 1;
  } else if (segmentHeader.number <= 65536) {
    referredToSegmentNumberSize = 2;
  }
  const referredTo = [];
  let i, ii;
  for (i = 0; i < referredToCount; i++) {
    let number;
    if (referredToSegmentNumberSize === 1) {
      number = data[position];
    } else if (referredToSegmentNumberSize === 2) {
      number = (0, _core_utils.readUint16)(data, position);
    } else {
      number = (0, _core_utils.readUint32)(data, position);
    }
    referredTo.push(number);
    position += referredToSegmentNumberSize;
  }
  segmentHeader.referredTo = referredTo;
  if (!pageAssociationFieldSize) {
    segmentHeader.pageAssociation = data[position++];
  } else {
    segmentHeader.pageAssociation = (0, _core_utils.readUint32)(data, position);
    position += 4;
  }
  segmentHeader.length = (0, _core_utils.readUint32)(data, position);
  position += 4;
  if (segmentHeader.length === 0xffffffff) {
    if (segmentType === 38) {
      const genericRegionInfo = readRegionSegmentInformation(data, position);
      const genericRegionSegmentFlags = data[position + RegionSegmentInformationFieldLength];
      const genericRegionMmr = !!(genericRegionSegmentFlags & 1);
      const searchPatternLength = 6;
      const searchPattern = new Uint8Array(searchPatternLength);
      if (!genericRegionMmr) {
        searchPattern[0] = 0xff;
        searchPattern[1] = 0xac;
      }
      searchPattern[2] = genericRegionInfo.height >>> 24 & 0xff;
      searchPattern[3] = genericRegionInfo.height >> 16 & 0xff;
      searchPattern[4] = genericRegionInfo.height >> 8 & 0xff;
      searchPattern[5] = genericRegionInfo.height & 0xff;
      for (i = position, ii = data.length; i < ii; i++) {
        let j = 0;
        while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
          j++;
        }
        if (j === searchPatternLength) {
          segmentHeader.length = i + searchPatternLength;
          break;
        }
      }
      if (segmentHeader.length === 0xffffffff) {
        throw new Jbig2Error("segment end was not found");
      }
    } else {
      throw new Jbig2Error("invalid unknown segment length");
    }
  }
  segmentHeader.headerEnd = position;
  return segmentHeader;
}
function readSegments(header, data, start, end) {
  const segments = [];
  let position = start;
  while (position < end) {
    const segmentHeader = readSegmentHeader(data, position);
    position = segmentHeader.headerEnd;
    const segment = {
      header: segmentHeader,
      data
    };
    if (!header.randomAccess) {
      segment.start = position;
      position += segmentHeader.length;
      segment.end = position;
    }
    segments.push(segment);
    if (segmentHeader.type === 51) {
      break;
    }
  }
  if (header.randomAccess) {
    for (let i = 0, ii = segments.length; i < ii; i++) {
      segments[i].start = position;
      position += segments[i].header.length;
      segments[i].end = position;
    }
  }
  return segments;
}
function readRegionSegmentInformation(data, start) {
  return {
    width: (0, _core_utils.readUint32)(data, start),
    height: (0, _core_utils.readUint32)(data, start + 4),
    x: (0, _core_utils.readUint32)(data, start + 8),
    y: (0, _core_utils.readUint32)(data, start + 12),
    combinationOperator: data[start + 16] & 7
  };
}
const RegionSegmentInformationFieldLength = 17;
function processSegment(segment, visitor) {
  const header = segment.header;
  const data = segment.data,
    end = segment.end;
  let position = segment.start;
  let args, at, i, atLength;
  switch (header.type) {
    case 0:
      const dictionary = {};
      const dictionaryFlags = (0, _core_utils.readUint16)(data, position);
      dictionary.huffman = !!(dictionaryFlags & 1);
      dictionary.refinement = !!(dictionaryFlags & 2);
      dictionary.huffmanDHSelector = dictionaryFlags >> 2 & 3;
      dictionary.huffmanDWSelector = dictionaryFlags >> 4 & 3;
      dictionary.bitmapSizeSelector = dictionaryFlags >> 6 & 1;
      dictionary.aggregationInstancesSelector = dictionaryFlags >> 7 & 1;
      dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
      dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
      dictionary.template = dictionaryFlags >> 10 & 3;
      dictionary.refinementTemplate = dictionaryFlags >> 12 & 1;
      position += 2;
      if (!dictionary.huffman) {
        atLength = dictionary.template === 0 ? 4 : 1;
        at = [];
        for (i = 0; i < atLength; i++) {
          at.push({
            x: (0, _core_utils.readInt8)(data, position),
            y: (0, _core_utils.readInt8)(data, position + 1)
          });
          position += 2;
        }
        dictionary.at = at;
      }
      if (dictionary.refinement && !dictionary.refinementTemplate) {
        at = [];
        for (i = 0; i < 2; i++) {
          at.push({
            x: (0, _core_utils.readInt8)(data, position),
            y: (0, _core_utils.readInt8)(data, position + 1)
          });
          position += 2;
        }
        dictionary.refinementAt = at;
      }
      dictionary.numberOfExportedSymbols = (0, _core_utils.readUint32)(data, position);
      position += 4;
      dictionary.numberOfNewSymbols = (0, _core_utils.readUint32)(data, position);
      position += 4;
      args = [dictionary, header.number, header.referredTo, data, position, end];
      break;
    case 6:
    case 7:
      const textRegion = {};
      textRegion.info = readRegionSegmentInformation(data, position);
      position += RegionSegmentInformationFieldLength;
      const textRegionSegmentFlags = (0, _core_utils.readUint16)(data, position);
      position += 2;
      textRegion.huffman = !!(textRegionSegmentFlags & 1);
      textRegion.refinement = !!(textRegionSegmentFlags & 2);
      textRegion.logStripSize = textRegionSegmentFlags >> 2 & 3;
      textRegion.stripSize = 1 << textRegion.logStripSize;
      textRegion.referenceCorner = textRegionSegmentFlags >> 4 & 3;
      textRegion.transposed = !!(textRegionSegmentFlags & 64);
      textRegion.combinationOperator = textRegionSegmentFlags >> 7 & 3;
      textRegion.defaultPixelValue = textRegionSegmentFlags >> 9 & 1;
      textRegion.dsOffset = textRegionSegmentFlags << 17 >> 27;
      textRegion.refinementTemplate = textRegionSegmentFlags >> 15 & 1;
      if (textRegion.huffman) {
        const textRegionHuffmanFlags = (0, _core_utils.readUint16)(data, position);
        position += 2;
        textRegion.huffmanFS = textRegionHuffmanFlags & 3;
        textRegion.huffmanDS = textRegionHuffmanFlags >> 2 & 3;
        textRegion.huffmanDT = textRegionHuffmanFlags >> 4 & 3;
        textRegion.huffmanRefinementDW = textRegionHuffmanFlags >> 6 & 3;
        textRegion.huffmanRefinementDH = textRegionHuffmanFlags >> 8 & 3;
        textRegion.huffmanRefinementDX = textRegionHuffmanFlags >> 10 & 3;
        textRegion.huffmanRefinementDY = textRegionHuffmanFlags >> 12 & 3;
        textRegion.huffmanRefinementSizeSelector = !!(textRegionHuffmanFlags & 0x4000);
      }
      if (textRegion.refinement && !textRegion.refinementTemplate) {
        at = [];
        for (i = 0; i < 2; i++) {
          at.push({
            x: (0, _core_utils.readInt8)(data, position),
            y: (0, _core_utils.readInt8)(data, position + 1)
          });
          position += 2;
        }
        textRegion.refinementAt = at;
      }
      textRegion.numberOfSymbolInstances = (0, _core_utils.readUint32)(data, position);
      position += 4;
      args = [textRegion, header.referredTo, data, position, end];
      break;
    case 16:
      const patternDictionary = {};
      const patternDictionaryFlags = data[position++];
      patternDictionary.mmr = !!(patternDictionaryFlags & 1);
      patternDictionary.template = patternDictionaryFlags >> 1 & 3;
      patternDictionary.patternWidth = data[position++];
      patternDictionary.patternHeight = data[position++];
      patternDictionary.maxPatternIndex = (0, _core_utils.readUint32)(data, position);
      position += 4;
      args = [patternDictionary, header.number, data, position, end];
      break;
    case 22:
    case 23:
      const halftoneRegion = {};
      halftoneRegion.info = readRegionSegmentInformation(data, position);
      position += RegionSegmentInformationFieldLength;
      const halftoneRegionFlags = data[position++];
      halftoneRegion.mmr = !!(halftoneRegionFlags & 1);
      halftoneRegion.template = halftoneRegionFlags >> 1 & 3;
      halftoneRegion.enableSkip = !!(halftoneRegionFlags & 8);
      halftoneRegion.combinationOperator = halftoneRegionFlags >> 4 & 7;
      halftoneRegion.defaultPixelValue = halftoneRegionFlags >> 7 & 1;
      halftoneRegion.gridWidth = (0, _core_utils.readUint32)(data, position);
      position += 4;
      halftoneRegion.gridHeight = (0, _core_utils.readUint32)(data, position);
      position += 4;
      halftoneRegion.gridOffsetX = (0, _core_utils.readUint32)(data, position) & 0xffffffff;
      position += 4;
      halftoneRegion.gridOffsetY = (0, _core_utils.readUint32)(data, position) & 0xffffffff;
      position += 4;
      halftoneRegion.gridVectorX = (0, _core_utils.readUint16)(data, position);
      position += 2;
      halftoneRegion.gridVectorY = (0, _core_utils.readUint16)(data, position);
      position += 2;
      args = [halftoneRegion, header.referredTo, data, position, end];
      break;
    case 38:
    case 39:
      const genericRegion = {};
      genericRegion.info = readRegionSegmentInformation(data, position);
      position += RegionSegmentInformationFieldLength;
      const genericRegionSegmentFlags = data[position++];
      genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
      genericRegion.template = genericRegionSegmentFlags >> 1 & 3;
      genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
      if (!genericRegion.mmr) {
        atLength = genericRegion.template === 0 ? 4 : 1;
        at = [];
        for (i = 0; i < atLength; i++) {
          at.push({
            x: (0, _core_utils.readInt8)(data, position),
            y: (0, _core_utils.readInt8)(data, position + 1)
          });
          position += 2;
        }
        genericRegion.at = at;
      }
      args = [genericRegion, data, position, end];
      break;
    case 48:
      const pageInfo = {
        width: (0, _core_utils.readUint32)(data, position),
        height: (0, _core_utils.readUint32)(data, position + 4),
        resolutionX: (0, _core_utils.readUint32)(data, position + 8),
        resolutionY: (0, _core_utils.readUint32)(data, position + 12)
      };
      if (pageInfo.height === 0xffffffff) {
        delete pageInfo.height;
      }
      const pageSegmentFlags = data[position + 16];
      (0, _core_utils.readUint16)(data, position + 17);
      pageInfo.lossless = !!(pageSegmentFlags & 1);
      pageInfo.refinement = !!(pageSegmentFlags & 2);
      pageInfo.defaultPixelValue = pageSegmentFlags >> 2 & 1;
      pageInfo.combinationOperator = pageSegmentFlags >> 3 & 3;
      pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
      pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
      args = [pageInfo];
      break;
    case 49:
      break;
    case 50:
      break;
    case 51:
      break;
    case 53:
      args = [header.number, data, position, end];
      break;
    case 62:
      break;
    default:
      throw new Jbig2Error(`segment type ${header.typeName}(${header.type}) is not implemented`);
  }
  const callbackName = "on" + header.typeName;
  if (callbackName in visitor) {
    visitor[callbackName].apply(visitor, args);
  }
}
function processSegments(segments, visitor) {
  for (let i = 0, ii = segments.length; i < ii; i++) {
    processSegment(segments[i], visitor);
  }
}
function parseJbig2Chunks(chunks) {
  const visitor = new SimpleSegmentVisitor();
  for (let i = 0, ii = chunks.length; i < ii; i++) {
    const chunk = chunks[i];
    const segments = readSegments({}, chunk.data, chunk.start, chunk.end);
    processSegments(segments, visitor);
  }
  return visitor.buffer;
}
function parseJbig2(data) {
  throw new Error("Not implemented: parseJbig2");
}
class SimpleSegmentVisitor {
  onPageInformation(info) {
    this.currentPageInfo = info;
    const rowSize = info.width + 7 >> 3;
    const buffer = new Uint8ClampedArray(rowSize * info.height);
    if (info.defaultPixelValue) {
      buffer.fill(0xff);
    }
    this.buffer = buffer;
  }
  drawBitmap(regionInfo, bitmap) {
    const pageInfo = this.currentPageInfo;
    const width = regionInfo.width,
      height = regionInfo.height;
    const rowSize = pageInfo.width + 7 >> 3;
    const combinationOperator = pageInfo.combinationOperatorOverride ? regionInfo.combinationOperator : pageInfo.combinationOperator;
    const buffer = this.buffer;
    const mask0 = 128 >> (regionInfo.x & 7);
    let offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
    let i, j, mask, offset;
    switch (combinationOperator) {
      case 0:
        for (i = 0; i < height; i++) {
          mask = mask0;
          offset = offset0;
          for (j = 0; j < width; j++) {
            if (bitmap[i][j]) {
              buffer[offset] |= mask;
            }
            mask >>= 1;
            if (!mask) {
              mask = 128;
              offset++;
            }
          }
          offset0 += rowSize;
        }
        break;
      case 2:
        for (i = 0; i < height; i++) {
          mask = mask0;
          offset = offset0;
          for (j = 0; j < width; j++) {
            if (bitmap[i][j]) {
              buffer[offset] ^= mask;
            }
            mask >>= 1;
            if (!mask) {
              mask = 128;
              offset++;
            }
          }
          offset0 += rowSize;
        }
        break;
      default:
        throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
    }
  }
  onImmediateGenericRegion(region, data, start, end) {
    const regionInfo = region.info;
    const decodingContext = new DecodingContext(data, start, end);
    const bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height, region.template, region.prediction, null, region.at, decodingContext);
    this.drawBitmap(regionInfo, bitmap);
  }
  onImmediateLosslessGenericRegion() {
    this.onImmediateGenericRegion(...arguments);
  }
  onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
    let huffmanTables, huffmanInput;
    if (dictionary.huffman) {
      huffmanTables = getSymbolDictionaryHuffmanTables(dictionary, referredSegments, this.customTables);
      huffmanInput = new Reader(data, start, end);
    }
    let symbols = this.symbols;
    if (!symbols) {
      this.symbols = symbols = {};
    }
    const inputSymbols = [];
    for (const referredSegment of referredSegments) {
      const referredSymbols = symbols[referredSegment];
      if (referredSymbols) {
        inputSymbols.push(...referredSymbols);
      }
    }
    const decodingContext = new DecodingContext(data, start, end);
    symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman, dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols, dictionary.numberOfExportedSymbols, huffmanTables, dictionary.template, dictionary.at, dictionary.refinementTemplate, dictionary.refinementAt, decodingContext, huffmanInput);
  }
  onImmediateTextRegion(region, referredSegments, data, start, end) {
    const regionInfo = region.info;
    let huffmanTables, huffmanInput;
    const symbols = this.symbols;
    const inputSymbols = [];
    for (const referredSegment of referredSegments) {
      const referredSymbols = symbols[referredSegment];
      if (referredSymbols) {
        inputSymbols.push(...referredSymbols);
      }
    }
    const symbolCodeLength = (0, _core_utils.log2)(inputSymbols.length);
    if (region.huffman) {
      huffmanInput = new Reader(data, start, end);
      huffmanTables = getTextRegionHuffmanTables(region, referredSegments, this.customTables, inputSymbols.length, huffmanInput);
    }
    const decodingContext = new DecodingContext(data, start, end);
    const bitmap = decodeTextRegion(region.huffman, region.refinement, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.numberOfSymbolInstances, region.stripSize, inputSymbols, symbolCodeLength, region.transposed, region.dsOffset, region.referenceCorner, region.combinationOperator, huffmanTables, region.refinementTemplate, region.refinementAt, decodingContext, region.logStripSize, huffmanInput);
    this.drawBitmap(regionInfo, bitmap);
  }
  onImmediateLosslessTextRegion() {
    this.onImmediateTextRegion(...arguments);
  }
  onPatternDictionary(dictionary, currentSegment, data, start, end) {
    let patterns = this.patterns;
    if (!patterns) {
      this.patterns = patterns = {};
    }
    const decodingContext = new DecodingContext(data, start, end);
    patterns[currentSegment] = decodePatternDictionary(dictionary.mmr, dictionary.patternWidth, dictionary.patternHeight, dictionary.maxPatternIndex, dictionary.template, decodingContext);
  }
  onImmediateHalftoneRegion(region, referredSegments, data, start, end) {
    const patterns = this.patterns[referredSegments[0]];
    const regionInfo = region.info;
    const decodingContext = new DecodingContext(data, start, end);
    const bitmap = decodeHalftoneRegion(region.mmr, patterns, region.template, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.enableSkip, region.combinationOperator, region.gridWidth, region.gridHeight, region.gridOffsetX, region.gridOffsetY, region.gridVectorX, region.gridVectorY, decodingContext);
    this.drawBitmap(regionInfo, bitmap);
  }
  onImmediateLosslessHalftoneRegion() {
    this.onImmediateHalftoneRegion(...arguments);
  }
  onTables(currentSegment, data, start, end) {
    let customTables = this.customTables;
    if (!customTables) {
      this.customTables = customTables = {};
    }
    customTables[currentSegment] = decodeTablesSegment(data, start, end);
  }
}
class HuffmanLine {
  constructor(lineData) {
    if (lineData.length === 2) {
      this.isOOB = true;
      this.rangeLow = 0;
      this.prefixLength = lineData[0];
      this.rangeLength = 0;
      this.prefixCode = lineData[1];
      this.isLowerRange = false;
    } else {
      this.isOOB = false;
      this.rangeLow = lineData[0];
      this.prefixLength = lineData[1];
      this.rangeLength = lineData[2];
      this.prefixCode = lineData[3];
      this.isLowerRange = lineData[4] === "lower";
    }
  }
}
class HuffmanTreeNode {
  constructor(line) {
    this.children = [];
    if (line) {
      this.isLeaf = true;
      this.rangeLength = line.rangeLength;
      this.rangeLow = line.rangeLow;
      this.isLowerRange = line.isLowerRange;
      this.isOOB = line.isOOB;
    } else {
      this.isLeaf = false;
    }
  }
  buildTree(line, shift) {
    const bit = line.prefixCode >> shift & 1;
    if (shift <= 0) {
      this.children[bit] = new HuffmanTreeNode(line);
    } else {
      let node = this.children[bit];
      if (!node) {
        this.children[bit] = node = new HuffmanTreeNode(null);
      }
      node.buildTree(line, shift - 1);
    }
  }
  decodeNode(reader) {
    if (this.isLeaf) {
      if (this.isOOB) {
        return null;
      }
      const htOffset = reader.readBits(this.rangeLength);
      return this.rangeLow + (this.isLowerRange ? -htOffset : htOffset);
    }
    const node = this.children[reader.readBit()];
    if (!node) {
      throw new Jbig2Error("invalid Huffman data");
    }
    return node.decodeNode(reader);
  }
}
class HuffmanTable {
  constructor(lines, prefixCodesDone) {
    if (!prefixCodesDone) {
      this.assignPrefixCodes(lines);
    }
    this.rootNode = new HuffmanTreeNode(null);
    for (let i = 0, ii = lines.length; i < ii; i++) {
      const line = lines[i];
      if (line.prefixLength > 0) {
        this.rootNode.buildTree(line, line.prefixLength - 1);
      }
    }
  }
  decode(reader) {
    return this.rootNode.decodeNode(reader);
  }
  assignPrefixCodes(lines) {
    const linesLength = lines.length;
    let prefixLengthMax = 0;
    for (let i = 0; i < linesLength; i++) {
      prefixLengthMax = Math.max(prefixLengthMax, lines[i].prefixLength);
    }
    const histogram = new Uint32Array(prefixLengthMax + 1);
    for (let i = 0; i < linesLength; i++) {
      histogram[lines[i].prefixLength]++;
    }
    let currentLength = 1,
      firstCode = 0,
      currentCode,
      currentTemp,
      line;
    histogram[0] = 0;
    while (currentLength <= prefixLengthMax) {
      firstCode = firstCode + histogram[currentLength - 1] << 1;
      currentCode = firstCode;
      currentTemp = 0;
      while (currentTemp < linesLength) {
        line = lines[currentTemp];
        if (line.prefixLength === currentLength) {
          line.prefixCode = currentCode;
          currentCode++;
        }
        currentTemp++;
      }
      currentLength++;
    }
  }
}
function decodeTablesSegment(data, start, end) {
  const flags = data[start];
  const lowestValue = (0, _core_utils.readUint32)(data, start + 1) & 0xffffffff;
  const highestValue = (0, _core_utils.readUint32)(data, start + 5) & 0xffffffff;
  const reader = new Reader(data, start + 9, end);
  const prefixSizeBits = (flags >> 1 & 7) + 1;
  const rangeSizeBits = (flags >> 4 & 7) + 1;
  const lines = [];
  let prefixLength,
    rangeLength,
    currentRangeLow = lowestValue;
  do {
    prefixLength = reader.readBits(prefixSizeBits);
    rangeLength = reader.readBits(rangeSizeBits);
    lines.push(new HuffmanLine([currentRangeLow, prefixLength, rangeLength, 0]));
    currentRangeLow += 1 << rangeLength;
  } while (currentRangeLow < highestValue);
  prefixLength = reader.readBits(prefixSizeBits);
  lines.push(new HuffmanLine([lowestValue - 1, prefixLength, 32, 0, "lower"]));
  prefixLength = reader.readBits(prefixSizeBits);
  lines.push(new HuffmanLine([highestValue, prefixLength, 32, 0]));
  if (flags & 1) {
    prefixLength = reader.readBits(prefixSizeBits);
    lines.push(new HuffmanLine([prefixLength, 0]));
  }
  return new HuffmanTable(lines, false);
}
const standardTablesCache = {};
function getStandardTable(number) {
  let table = standardTablesCache[number];
  if (table) {
    return table;
  }
  let lines;
  switch (number) {
    case 1:
      lines = [[0, 1, 4, 0x0], [16, 2, 8, 0x2], [272, 3, 16, 0x6], [65808, 3, 32, 0x7]];
      break;
    case 2:
      lines = [[0, 1, 0, 0x0], [1, 2, 0, 0x2], [2, 3, 0, 0x6], [3, 4, 3, 0xe], [11, 5, 6, 0x1e], [75, 6, 32, 0x3e], [6, 0x3f]];
      break;
    case 3:
      lines = [[-256, 8, 8, 0xfe], [0, 1, 0, 0x0], [1, 2, 0, 0x2], [2, 3, 0, 0x6], [3, 4, 3, 0xe], [11, 5, 6, 0x1e], [-257, 8, 32, 0xff, "lower"], [75, 7, 32, 0x7e], [6, 0x3e]];
      break;
    case 4:
      lines = [[1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 0, 0x6], [4, 4, 3, 0xe], [12, 5, 6, 0x1e], [76, 5, 32, 0x1f]];
      break;
    case 5:
      lines = [[-255, 7, 8, 0x7e], [1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 0, 0x6], [4, 4, 3, 0xe], [12, 5, 6, 0x1e], [-256, 7, 32, 0x7f, "lower"], [76, 6, 32, 0x3e]];
      break;
    case 6:
      lines = [[-2048, 5, 10, 0x1c], [-1024, 4, 9, 0x8], [-512, 4, 8, 0x9], [-256, 4, 7, 0xa], [-128, 5, 6, 0x1d], [-64, 5, 5, 0x1e], [-32, 4, 5, 0xb], [0, 2, 7, 0x0], [128, 3, 7, 0x2], [256, 3, 8, 0x3], [512, 4, 9, 0xc], [1024, 4, 10, 0xd], [-2049, 6, 32, 0x3e, "lower"], [2048, 6, 32, 0x3f]];
      break;
    case 7:
      lines = [[-1024, 4, 9, 0x8], [-512, 3, 8, 0x0], [-256, 4, 7, 0x9], [-128, 5, 6, 0x1a], [-64, 5, 5, 0x1b], [-32, 4, 5, 0xa], [0, 4, 5, 0xb], [32, 5, 5, 0x1c], [64, 5, 6, 0x1d], [128, 4, 7, 0xc], [256, 3, 8, 0x1], [512, 3, 9, 0x2], [1024, 3, 10, 0x3], [-1025, 5, 32, 0x1e, "lower"], [2048, 5, 32, 0x1f]];
      break;
    case 8:
      lines = [[-15, 8, 3, 0xfc], [-7, 9, 1, 0x1fc], [-5, 8, 1, 0xfd], [-3, 9, 0, 0x1fd], [-2, 7, 0, 0x7c], [-1, 4, 0, 0xa], [0, 2, 1, 0x0], [2, 5, 0, 0x1a], [3, 6, 0, 0x3a], [4, 3, 4, 0x4], [20, 6, 1, 0x3b], [22, 4, 4, 0xb], [38, 4, 5, 0xc], [70, 5, 6, 0x1b], [134, 5, 7, 0x1c], [262, 6, 7, 0x3c], [390, 7, 8, 0x7d], [646, 6, 10, 0x3d], [-16, 9, 32, 0x1fe, "lower"], [1670, 9, 32, 0x1ff], [2, 0x1]];
      break;
    case 9:
      lines = [[-31, 8, 4, 0xfc], [-15, 9, 2, 0x1fc], [-11, 8, 2, 0xfd], [-7, 9, 1, 0x1fd], [-5, 7, 1, 0x7c], [-3, 4, 1, 0xa], [-1, 3, 1, 0x2], [1, 3, 1, 0x3], [3, 5, 1, 0x1a], [5, 6, 1, 0x3a], [7, 3, 5, 0x4], [39, 6, 2, 0x3b], [43, 4, 5, 0xb], [75, 4, 6, 0xc], [139, 5, 7, 0x1b], [267, 5, 8, 0x1c], [523, 6, 8, 0x3c], [779, 7, 9, 0x7d], [1291, 6, 11, 0x3d], [-32, 9, 32, 0x1fe, "lower"], [3339, 9, 32, 0x1ff], [2, 0x0]];
      break;
    case 10:
      lines = [[-21, 7, 4, 0x7a], [-5, 8, 0, 0xfc], [-4, 7, 0, 0x7b], [-3, 5, 0, 0x18], [-2, 2, 2, 0x0], [2, 5, 0, 0x19], [3, 6, 0, 0x36], [4, 7, 0, 0x7c], [5, 8, 0, 0xfd], [6, 2, 6, 0x1], [70, 5, 5, 0x1a], [102, 6, 5, 0x37], [134, 6, 6, 0x38], [198, 6, 7, 0x39], [326, 6, 8, 0x3a], [582, 6, 9, 0x3b], [1094, 6, 10, 0x3c], [2118, 7, 11, 0x7d], [-22, 8, 32, 0xfe, "lower"], [4166, 8, 32, 0xff], [2, 0x2]];
      break;
    case 11:
      lines = [[1, 1, 0, 0x0], [2, 2, 1, 0x2], [4, 4, 0, 0xc], [5, 4, 1, 0xd], [7, 5, 1, 0x1c], [9, 5, 2, 0x1d], [13, 6, 2, 0x3c], [17, 7, 2, 0x7a], [21, 7, 3, 0x7b], [29, 7, 4, 0x7c], [45, 7, 5, 0x7d], [77, 7, 6, 0x7e], [141, 7, 32, 0x7f]];
      break;
    case 12:
      lines = [[1, 1, 0, 0x0], [2, 2, 0, 0x2], [3, 3, 1, 0x6], [5, 5, 0, 0x1c], [6, 5, 1, 0x1d], [8, 6, 1, 0x3c], [10, 7, 0, 0x7a], [11, 7, 1, 0x7b], [13, 7, 2, 0x7c], [17, 7, 3, 0x7d], [25, 7, 4, 0x7e], [41, 8, 5, 0xfe], [73, 8, 32, 0xff]];
      break;
    case 13:
      lines = [[1, 1, 0, 0x0], [2, 3, 0, 0x4], [3, 4, 0, 0xc], [4, 5, 0, 0x1c], [5, 4, 1, 0xd], [7, 3, 3, 0x5], [15, 6, 1, 0x3a], [17, 6, 2, 0x3b], [21, 6, 3, 0x3c], [29, 6, 4, 0x3d], [45, 6, 5, 0x3e], [77, 7, 6, 0x7e], [141, 7, 32, 0x7f]];
      break;
    case 14:
      lines = [[-2, 3, 0, 0x4], [-1, 3, 0, 0x5], [0, 1, 0, 0x0], [1, 3, 0, 0x6], [2, 3, 0, 0x7]];
      break;
    case 15:
      lines = [[-24, 7, 4, 0x7c], [-8, 6, 2, 0x3c], [-4, 5, 1, 0x1c], [-2, 4, 0, 0xc], [-1, 3, 0, 0x4], [0, 1, 0, 0x0], [1, 3, 0, 0x5], [2, 4, 0, 0xd], [3, 5, 1, 0x1d], [5, 6, 2, 0x3d], [9, 7, 4, 0x7d], [-25, 7, 32, 0x7e, "lower"], [25, 7, 32, 0x7f]];
      break;
    default:
      throw new Jbig2Error(`standard table B.${number} does not exist`);
  }
  for (let i = 0, ii = lines.length; i < ii; i++) {
    lines[i] = new HuffmanLine(lines[i]);
  }
  table = new HuffmanTable(lines, true);
  standardTablesCache[number] = table;
  return table;
}
class Reader {
  constructor(data, start, end) {
    this.data = data;
    this.start = start;
    this.end = end;
    this.position = start;
    this.shift = -1;
    this.currentByte = 0;
  }
  readBit() {
    if (this.shift < 0) {
      if (this.position >= this.end) {
        throw new Jbig2Error("end of data while reading bit");
      }
      this.currentByte = this.data[this.position++];
      this.shift = 7;
    }
    const bit = this.currentByte >> this.shift & 1;
    this.shift--;
    return bit;
  }
  readBits(numBits) {
    let result = 0,
      i;
    for (i = numBits - 1; i >= 0; i--) {
      result |= this.readBit() << i;
    }
    return result;
  }
  byteAlign() {
    this.shift = -1;
  }
  next() {
    if (this.position >= this.end) {
      return -1;
    }
    return this.data[this.position++];
  }
}
function getCustomHuffmanTable(index, referredTo, customTables) {
  let currentIndex = 0;
  for (let i = 0, ii = referredTo.length; i < ii; i++) {
    const table = customTables[referredTo[i]];
    if (table) {
      if (index === currentIndex) {
        return table;
      }
      currentIndex++;
    }
  }
  throw new Jbig2Error("can't find custom Huffman table");
}
function getTextRegionHuffmanTables(textRegion, referredTo, customTables, numberOfSymbols, reader) {
  const codes = [];
  for (let i = 0; i <= 34; i++) {
    const codeLength = reader.readBits(4);
    codes.push(new HuffmanLine([i, codeLength, 0, 0]));
  }
  const runCodesTable = new HuffmanTable(codes, false);
  codes.length = 0;
  for (let i = 0; i < numberOfSymbols;) {
    const codeLength = runCodesTable.decode(reader);
    if (codeLength >= 32) {
      let repeatedLength, numberOfRepeats, j;
      switch (codeLength) {
        case 32:
          if (i === 0) {
            throw new Jbig2Error("no previous value in symbol ID table");
          }
          numberOfRepeats = reader.readBits(2) + 3;
          repeatedLength = codes[i - 1].prefixLength;
          break;
        case 33:
          numberOfRepeats = reader.readBits(3) + 3;
          repeatedLength = 0;
          break;
        case 34:
          numberOfRepeats = reader.readBits(7) + 11;
          repeatedLength = 0;
          break;
        default:
          throw new Jbig2Error("invalid code length in symbol ID table");
      }
      for (j = 0; j < numberOfRepeats; j++) {
        codes.push(new HuffmanLine([i, repeatedLength, 0, 0]));
        i++;
      }
    } else {
      codes.push(new HuffmanLine([i, codeLength, 0, 0]));
      i++;
    }
  }
  reader.byteAlign();
  const symbolIDTable = new HuffmanTable(codes, false);
  let customIndex = 0,
    tableFirstS,
    tableDeltaS,
    tableDeltaT;
  switch (textRegion.huffmanFS) {
    case 0:
    case 1:
      tableFirstS = getStandardTable(textRegion.huffmanFS + 6);
      break;
    case 3:
      tableFirstS = getCustomHuffmanTable(customIndex, referredTo, customTables);
      customIndex++;
      break;
    default:
      throw new Jbig2Error("invalid Huffman FS selector");
  }
  switch (textRegion.huffmanDS) {
    case 0:
    case 1:
    case 2:
      tableDeltaS = getStandardTable(textRegion.huffmanDS + 8);
      break;
    case 3:
      tableDeltaS = getCustomHuffmanTable(customIndex, referredTo, customTables);
      customIndex++;
      break;
    default:
      throw new Jbig2Error("invalid Huffman DS selector");
  }
  switch (textRegion.huffmanDT) {
    case 0:
    case 1:
    case 2:
      tableDeltaT = getStandardTable(textRegion.huffmanDT + 11);
      break;
    case 3:
      tableDeltaT = getCustomHuffmanTable(customIndex, referredTo, customTables);
      customIndex++;
      break;
    default:
      throw new Jbig2Error("invalid Huffman DT selector");
  }
  if (textRegion.refinement) {
    throw new Jbig2Error("refinement with Huffman is not supported");
  }
  return {
    symbolIDTable,
    tableFirstS,
    tableDeltaS,
    tableDeltaT
  };
}
function getSymbolDictionaryHuffmanTables(dictionary, referredTo, customTables) {
  let customIndex = 0,
    tableDeltaHeight,
    tableDeltaWidth;
  switch (dictionary.huffmanDHSelector) {
    case 0:
    case 1:
      tableDeltaHeight = getStandardTable(dictionary.huffmanDHSelector + 4);
      break;
    case 3:
      tableDeltaHeight = getCustomHuffmanTable(customIndex, referredTo, customTables);
      customIndex++;
      break;
    default:
      throw new Jbig2Error("invalid Huffman DH selector");
  }
  switch (dictionary.huffmanDWSelector) {
    case 0:
    case 1:
      tableDeltaWidth = getStandardTable(dictionary.huffmanDWSelector + 2);
      break;
    case 3:
      tableDeltaWidth = getCustomHuffmanTable(customIndex, referredTo, customTables);
      customIndex++;
      break;
    default:
      throw new Jbig2Error("invalid Huffman DW selector");
  }
  let tableBitmapSize, tableAggregateInstances;
  if (dictionary.bitmapSizeSelector) {
    tableBitmapSize = getCustomHuffmanTable(customIndex, referredTo, customTables);
    customIndex++;
  } else {
    tableBitmapSize = getStandardTable(1);
  }
  if (dictionary.aggregationInstancesSelector) {
    tableAggregateInstances = getCustomHuffmanTable(customIndex, referredTo, customTables);
  } else {
    tableAggregateInstances = getStandardTable(1);
  }
  return {
    tableDeltaHeight,
    tableDeltaWidth,
    tableBitmapSize,
    tableAggregateInstances
  };
}
function readUncompressedBitmap(reader, width, height) {
  const bitmap = [];
  for (let y = 0; y < height; y++) {
    const row = new Uint8Array(width);
    bitmap.push(row);
    for (let x = 0; x < width; x++) {
      row[x] = reader.readBit();
    }
    reader.byteAlign();
  }
  return bitmap;
}
function decodeMMRBitmap(input, width, height, endOfBlock) {
  const params = {
    K: -1,
    Columns: width,
    Rows: height,
    BlackIs1: true,
    EndOfBlock: endOfBlock
  };
  const decoder = new _ccitt.CCITTFaxDecoder(input, params);
  const bitmap = [];
  let currentByte,
    eof = false;
  for (let y = 0; y < height; y++) {
    const row = new Uint8Array(width);
    bitmap.push(row);
    let shift = -1;
    for (let x = 0; x < width; x++) {
      if (shift < 0) {
        currentByte = decoder.readNextChar();
        if (currentByte === -1) {
          currentByte = 0;
          eof = true;
        }
        shift = 7;
      }
      row[x] = currentByte >> shift & 1;
      shift--;
    }
  }
  if (endOfBlock && !eof) {
    const lookForEOFLimit = 5;
    for (let i = 0; i < lookForEOFLimit; i++) {
      if (decoder.readNextChar() === -1) {
        break;
      }
    }
  }
  return bitmap;
}
class Jbig2Image {
  parseChunks(chunks) {
    return parseJbig2Chunks(chunks);
  }
  parse(data) {
    throw new Error("Not implemented: Jbig2Image.parse");
  }
}
exports.Jbig2Image = Jbig2Image;

/***/ }),
/* 24 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ArithmeticDecoder = void 0;
const QeTable = [{
  qe: 0x5601,
  nmps: 1,
  nlps: 1,
  switchFlag: 1
}, {
  qe: 0x3401,
  nmps: 2,
  nlps: 6,
  switchFlag: 0
}, {
  qe: 0x1801,
  nmps: 3,
  nlps: 9,
  switchFlag: 0
}, {
  qe: 0x0ac1,
  nmps: 4,
  nlps: 12,
  switchFlag: 0
}, {
  qe: 0x0521,
  nmps: 5,
  nlps: 29,
  switchFlag: 0
}, {
  qe: 0x0221,
  nmps: 38,
  nlps: 33,
  switchFlag: 0
}, {
  qe: 0x5601,
  nmps: 7,
  nlps: 6,
  switchFlag: 1
}, {
  qe: 0x5401,
  nmps: 8,
  nlps: 14,
  switchFlag: 0
}, {
  qe: 0x4801,
  nmps: 9,
  nlps: 14,
  switchFlag: 0
}, {
  qe: 0x3801,
  nmps: 10,
  nlps: 14,
  switchFlag: 0
}, {
  qe: 0x3001,
  nmps: 11,
  nlps: 17,
  switchFlag: 0
}, {
  qe: 0x2401,
  nmps: 12,
  nlps: 18,
  switchFlag: 0
}, {
  qe: 0x1c01,
  nmps: 13,
  nlps: 20,
  switchFlag: 0
}, {
  qe: 0x1601,
  nmps: 29,
  nlps: 21,
  switchFlag: 0
}, {
  qe: 0x5601,
  nmps: 15,
  nlps: 14,
  switchFlag: 1
}, {
  qe: 0x5401,
  nmps: 16,
  nlps: 14,
  switchFlag: 0
}, {
  qe: 0x5101,
  nmps: 17,
  nlps: 15,
  switchFlag: 0
}, {
  qe: 0x4801,
  nmps: 18,
  nlps: 16,
  switchFlag: 0
}, {
  qe: 0x3801,
  nmps: 19,
  nlps: 17,
  switchFlag: 0
}, {
  qe: 0x3401,
  nmps: 20,
  nlps: 18,
  switchFlag: 0
}, {
  qe: 0x3001,
  nmps: 21,
  nlps: 19,
  switchFlag: 0
}, {
  qe: 0x2801,
  nmps: 22,
  nlps: 19,
  switchFlag: 0
}, {
  qe: 0x2401,
  nmps: 23,
  nlps: 20,
  switchFlag: 0
}, {
  qe: 0x2201,
  nmps: 24,
  nlps: 21,
  switchFlag: 0
}, {
  qe: 0x1c01,
  nmps: 25,
  nlps: 22,
  switchFlag: 0
}, {
  qe: 0x1801,
  nmps: 26,
  nlps: 23,
  switchFlag: 0
}, {
  qe: 0x1601,
  nmps: 27,
  nlps: 24,
  switchFlag: 0
}, {
  qe: 0x1401,
  nmps: 28,
  nlps: 25,
  switchFlag: 0
}, {
  qe: 0x1201,
  nmps: 29,
  nlps: 26,
  switchFlag: 0
}, {
  qe: 0x1101,
  nmps: 30,
  nlps: 27,
  switchFlag: 0
}, {
  qe: 0x0ac1,
  nmps: 31,
  nlps: 28,
  switchFlag: 0
}, {
  qe: 0x09c1,
  nmps: 32,
  nlps: 29,
  switchFlag: 0
}, {
  qe: 0x08a1,
  nmps: 33,
  nlps: 30,
  switchFlag: 0
}, {
  qe: 0x0521,
  nmps: 34,
  nlps: 31,
  switchFlag: 0
}, {
  qe: 0x0441,
  nmps: 35,
  nlps: 32,
  switchFlag: 0
}, {
  qe: 0x02a1,
  nmps: 36,
  nlps: 33,
  switchFlag: 0
}, {
  qe: 0x0221,
  nmps: 37,
  nlps: 34,
  switchFlag: 0
}, {
  qe: 0x0141,
  nmps: 38,
  nlps: 35,
  switchFlag: 0
}, {
  qe: 0x0111,
  nmps: 39,
  nlps: 36,
  switchFlag: 0
}, {
  qe: 0x0085,
  nmps: 40,
  nlps: 37,
  switchFlag: 0
}, {
  qe: 0x0049,
  nmps: 41,
  nlps: 38,
  switchFlag: 0
}, {
  qe: 0x0025,
  nmps: 42,
  nlps: 39,
  switchFlag: 0
}, {
  qe: 0x0015,
  nmps: 43,
  nlps: 40,
  switchFlag: 0
}, {
  qe: 0x0009,
  nmps: 44,
  nlps: 41,
  switchFlag: 0
}, {
  qe: 0x0005,
  nmps: 45,
  nlps: 42,
  switchFlag: 0
}, {
  qe: 0x0001,
  nmps: 45,
  nlps: 43,
  switchFlag: 0
}, {
  qe: 0x5601,
  nmps: 46,
  nlps: 46,
  switchFlag: 0
}];
class ArithmeticDecoder {
  constructor(data, start, end) {
    this.data = data;
    this.bp = start;
    this.dataEnd = end;
    this.chigh = data[start];
    this.clow = 0;
    this.byteIn();
    this.chigh = this.chigh << 7 & 0xffff | this.clow >> 9 & 0x7f;
    this.clow = this.clow << 7 & 0xffff;
    this.ct -= 7;
    this.a = 0x8000;
  }
  byteIn() {
    const data = this.data;
    let bp = this.bp;
    if (data[bp] === 0xff) {
      if (data[bp + 1] > 0x8f) {
        this.clow += 0xff00;
        this.ct = 8;
      } else {
        bp++;
        this.clow += data[bp] << 9;
        this.ct = 7;
        this.bp = bp;
      }
    } else {
      bp++;
      this.clow += bp < this.dataEnd ? data[bp] << 8 : 0xff00;
      this.ct = 8;
      this.bp = bp;
    }
    if (this.clow > 0xffff) {
      this.chigh += this.clow >> 16;
      this.clow &= 0xffff;
    }
  }
  readBit(contexts, pos) {
    let cx_index = contexts[pos] >> 1,
      cx_mps = contexts[pos] & 1;
    const qeTableIcx = QeTable[cx_index];
    const qeIcx = qeTableIcx.qe;
    let d;
    let a = this.a - qeIcx;
    if (this.chigh < qeIcx) {
      if (a < qeIcx) {
        a = qeIcx;
        d = cx_mps;
        cx_index = qeTableIcx.nmps;
      } else {
        a = qeIcx;
        d = 1 ^ cx_mps;
        if (qeTableIcx.switchFlag === 1) {
          cx_mps = d;
        }
        cx_index = qeTableIcx.nlps;
      }
    } else {
      this.chigh -= qeIcx;
      if ((a & 0x8000) !== 0) {
        this.a = a;
        return cx_mps;
      }
      if (a < qeIcx) {
        d = 1 ^ cx_mps;
        if (qeTableIcx.switchFlag === 1) {
          cx_mps = d;
        }
        cx_index = qeTableIcx.nlps;
      } else {
        d = cx_mps;
        cx_index = qeTableIcx.nmps;
      }
    }
    do {
      if (this.ct === 0) {
        this.byteIn();
      }
      a <<= 1;
      this.chigh = this.chigh << 1 & 0xffff | this.clow >> 15 & 1;
      this.clow = this.clow << 1 & 0xffff;
      this.ct--;
    } while ((a & 0x8000) === 0);
    this.a = a;
    contexts[pos] = cx_index << 1 | cx_mps;
    return d;
  }
}
exports.ArithmeticDecoder = ArithmeticDecoder;

/***/ }),
/* 25 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.JpegStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
var _primitives = __w_pdfjs_require__(3);
var _jpg = __w_pdfjs_require__(26);
var _util = __w_pdfjs_require__(2);
class JpegStream extends _decode_stream.DecodeStream {
  constructor(stream, maybeLength, params) {
    let ch;
    while ((ch = stream.getByte()) !== -1) {
      if (ch === 0xff) {
        stream.skip(-1);
        break;
      }
    }
    super(maybeLength);
    this.stream = stream;
    this.dict = stream.dict;
    this.maybeLength = maybeLength;
    this.params = params;
  }
  get bytes() {
    return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
  }
  ensureBuffer(requested) {}
  readBlock() {
    if (this.eof) {
      return;
    }
    const jpegOptions = {
      decodeTransform: undefined,
      colorTransform: undefined
    };
    const decodeArr = this.dict.getArray("D", "Decode");
    if (this.forceRGB && Array.isArray(decodeArr)) {
      const bitsPerComponent = this.dict.get("BPC", "BitsPerComponent") || 8;
      const decodeArrLength = decodeArr.length;
      const transform = new Int32Array(decodeArrLength);
      let transformNeeded = false;
      const maxValue = (1 << bitsPerComponent) - 1;
      for (let i = 0; i < decodeArrLength; i += 2) {
        transform[i] = (decodeArr[i + 1] - decodeArr[i]) * 256 | 0;
        transform[i + 1] = decodeArr[i] * maxValue | 0;
        if (transform[i] !== 256 || transform[i + 1] !== 0) {
          transformNeeded = true;
        }
      }
      if (transformNeeded) {
        jpegOptions.decodeTransform = transform;
      }
    }
    if (this.params instanceof _primitives.Dict) {
      const colorTransform = this.params.get("ColorTransform");
      if (Number.isInteger(colorTransform)) {
        jpegOptions.colorTransform = colorTransform;
      }
    }
    const jpegImage = new _jpg.JpegImage(jpegOptions);
    jpegImage.parse(this.bytes);
    const data = jpegImage.getData({
      width: this.drawWidth,
      height: this.drawHeight,
      forceRGB: this.forceRGB,
      isSourcePDF: true
    });
    this.buffer = data;
    this.bufferLength = data.length;
    this.eof = true;
  }
}
exports.JpegStream = JpegStream;

/***/ }),
/* 26 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.JpegImage = void 0;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
class JpegError extends _util.BaseException {
  constructor(msg) {
    super(`JPEG error: ${msg}`, "JpegError");
  }
}
class DNLMarkerError extends _util.BaseException {
  constructor(message, scanLines) {
    super(message, "DNLMarkerError");
    this.scanLines = scanLines;
  }
}
class EOIMarkerError extends _util.BaseException {
  constructor(msg) {
    super(msg, "EOIMarkerError");
  }
}
const dctZigZag = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
const dctCos1 = 4017;
const dctSin1 = 799;
const dctCos3 = 3406;
const dctSin3 = 2276;
const dctCos6 = 1567;
const dctSin6 = 3784;
const dctSqrt2 = 5793;
const dctSqrt1d2 = 2896;
function buildHuffmanTable(codeLengths, values) {
  let k = 0,
    i,
    j,
    length = 16;
  while (length > 0 && !codeLengths[length - 1]) {
    length--;
  }
  const code = [{
    children: [],
    index: 0
  }];
  let p = code[0],
    q;
  for (i = 0; i < length; i++) {
    for (j = 0; j < codeLengths[i]; j++) {
      p = code.pop();
      p.children[p.index] = values[k];
      while (p.index > 0) {
        p = code.pop();
      }
      p.index++;
      code.push(p);
      while (code.length <= i) {
        code.push(q = {
          children: [],
          index: 0
        });
        p.children[p.index] = q.children;
        p = q;
      }
      k++;
    }
    if (i + 1 < length) {
      code.push(q = {
        children: [],
        index: 0
      });
      p.children[p.index] = q.children;
      p = q;
    }
  }
  return code[0].children;
}
function getBlockBufferOffset(component, row, col) {
  return 64 * ((component.blocksPerLine + 1) * row + col);
}
function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, parseDNLMarker = false) {
  const mcusPerLine = frame.mcusPerLine;
  const progressive = frame.progressive;
  const startOffset = offset;
  let bitsData = 0,
    bitsCount = 0;
  function readBit() {
    if (bitsCount > 0) {
      bitsCount--;
      return bitsData >> bitsCount & 1;
    }
    bitsData = data[offset++];
    if (bitsData === 0xff) {
      const nextByte = data[offset++];
      if (nextByte) {
        if (nextByte === 0xdc && parseDNLMarker) {
          offset += 2;
          const scanLines = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          if (scanLines > 0 && scanLines !== frame.scanLines) {
            throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", scanLines);
          }
        } else if (nextByte === 0xd9) {
          if (parseDNLMarker) {
            const maybeScanLines = blockRow * (frame.precision === 8 ? 8 : 0);
            if (maybeScanLines > 0 && Math.round(frame.scanLines / maybeScanLines) >= 5) {
              throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", maybeScanLines);
            }
          }
          throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data");
        }
        throw new JpegError(`unexpected marker ${(bitsData << 8 | nextByte).toString(16)}`);
      }
    }
    bitsCount = 7;
    return bitsData >>> 7;
  }
  function decodeHuffman(tree) {
    let node = tree;
    while (true) {
      node = node[readBit()];
      switch (typeof node) {
        case "number":
          return node;
        case "object":
          continue;
      }
      throw new JpegError("invalid huffman sequence");
    }
  }
  function receive(length) {
    let n = 0;
    while (length > 0) {
      n = n << 1 | readBit();
      length--;
    }
    return n;
  }
  function receiveAndExtend(length) {
    if (length === 1) {
      return readBit() === 1 ? 1 : -1;
    }
    const n = receive(length);
    if (n >= 1 << length - 1) {
      return n;
    }
    return n + (-1 << length) + 1;
  }
  function decodeBaseline(component, blockOffset) {
    const t = decodeHuffman(component.huffmanTableDC);
    const diff = t === 0 ? 0 : receiveAndExtend(t);
    component.blockData[blockOffset] = component.pred += diff;
    let k = 1;
    while (k < 64) {
      const rs = decodeHuffman(component.huffmanTableAC);
      const s = rs & 15,
        r = rs >> 4;
      if (s === 0) {
        if (r < 15) {
          break;
        }
        k += 16;
        continue;
      }
      k += r;
      const z = dctZigZag[k];
      component.blockData[blockOffset + z] = receiveAndExtend(s);
      k++;
    }
  }
  function decodeDCFirst(component, blockOffset) {
    const t = decodeHuffman(component.huffmanTableDC);
    const diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
    component.blockData[blockOffset] = component.pred += diff;
  }
  function decodeDCSuccessive(component, blockOffset) {
    component.blockData[blockOffset] |= readBit() << successive;
  }
  let eobrun = 0;
  function decodeACFirst(component, blockOffset) {
    if (eobrun > 0) {
      eobrun--;
      return;
    }
    let k = spectralStart;
    const e = spectralEnd;
    while (k <= e) {
      const rs = decodeHuffman(component.huffmanTableAC);
      const s = rs & 15,
        r = rs >> 4;
      if (s === 0) {
        if (r < 15) {
          eobrun = receive(r) + (1 << r) - 1;
          break;
        }
        k += 16;
        continue;
      }
      k += r;
      const z = dctZigZag[k];
      component.blockData[blockOffset + z] = receiveAndExtend(s) * (1 << successive);
      k++;
    }
  }
  let successiveACState = 0,
    successiveACNextValue;
  function decodeACSuccessive(component, blockOffset) {
    let k = spectralStart;
    const e = spectralEnd;
    let r = 0;
    let s;
    let rs;
    while (k <= e) {
      const offsetZ = blockOffset + dctZigZag[k];
      const sign = component.blockData[offsetZ] < 0 ? -1 : 1;
      switch (successiveACState) {
        case 0:
          rs = decodeHuffman(component.huffmanTableAC);
          s = rs & 15;
          r = rs >> 4;
          if (s === 0) {
            if (r < 15) {
              eobrun = receive(r) + (1 << r);
              successiveACState = 4;
            } else {
              r = 16;
              successiveACState = 1;
            }
          } else {
            if (s !== 1) {
              throw new JpegError("invalid ACn encoding");
            }
            successiveACNextValue = receiveAndExtend(s);
            successiveACState = r ? 2 : 3;
          }
          continue;
        case 1:
        case 2:
          if (component.blockData[offsetZ]) {
            component.blockData[offsetZ] += sign * (readBit() << successive);
          } else {
            r--;
            if (r === 0) {
              successiveACState = successiveACState === 2 ? 3 : 0;
            }
          }
          break;
        case 3:
          if (component.blockData[offsetZ]) {
            component.blockData[offsetZ] += sign * (readBit() << successive);
          } else {
            component.blockData[offsetZ] = successiveACNextValue << successive;
            successiveACState = 0;
          }
          break;
        case 4:
          if (component.blockData[offsetZ]) {
            component.blockData[offsetZ] += sign * (readBit() << successive);
          }
          break;
      }
      k++;
    }
    if (successiveACState === 4) {
      eobrun--;
      if (eobrun === 0) {
        successiveACState = 0;
      }
    }
  }
  let blockRow = 0;
  function decodeMcu(component, decode, mcu, row, col) {
    const mcuRow = mcu / mcusPerLine | 0;
    const mcuCol = mcu % mcusPerLine;
    blockRow = mcuRow * component.v + row;
    const blockCol = mcuCol * component.h + col;
    const blockOffset = getBlockBufferOffset(component, blockRow, blockCol);
    decode(component, blockOffset);
  }
  function decodeBlock(component, decode, mcu) {
    blockRow = mcu / component.blocksPerLine | 0;
    const blockCol = mcu % component.blocksPerLine;
    const blockOffset = getBlockBufferOffset(component, blockRow, blockCol);
    decode(component, blockOffset);
  }
  const componentsLength = components.length;
  let component, i, j, k, n;
  let decodeFn;
  if (progressive) {
    if (spectralStart === 0) {
      decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
    } else {
      decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
    }
  } else {
    decodeFn = decodeBaseline;
  }
  let mcu = 0,
    fileMarker;
  let mcuExpected;
  if (componentsLength === 1) {
    mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  } else {
    mcuExpected = mcusPerLine * frame.mcusPerColumn;
  }
  let h, v;
  while (mcu <= mcuExpected) {
    const mcuToRead = resetInterval ? Math.min(mcuExpected - mcu, resetInterval) : mcuExpected;
    if (mcuToRead > 0) {
      for (i = 0; i < componentsLength; i++) {
        components[i].pred = 0;
      }
      eobrun = 0;
      if (componentsLength === 1) {
        component = components[0];
        for (n = 0; n < mcuToRead; n++) {
          decodeBlock(component, decodeFn, mcu);
          mcu++;
        }
      } else {
        for (n = 0; n < mcuToRead; n++) {
          for (i = 0; i < componentsLength; i++) {
            component = components[i];
            h = component.h;
            v = component.v;
            for (j = 0; j < v; j++) {
              for (k = 0; k < h; k++) {
                decodeMcu(component, decodeFn, mcu, j, k);
              }
            }
          }
          mcu++;
        }
      }
    }
    bitsCount = 0;
    fileMarker = findNextFileMarker(data, offset);
    if (!fileMarker) {
      break;
    }
    if (fileMarker.invalid) {
      const partialMsg = mcuToRead > 0 ? "unexpected" : "excessive";
      (0, _util.warn)(`decodeScan - ${partialMsg} MCU data, current marker is: ${fileMarker.invalid}`);
      offset = fileMarker.offset;
    }
    if (fileMarker.marker >= 0xffd0 && fileMarker.marker <= 0xffd7) {
      offset += 2;
    } else {
      break;
    }
  }
  return offset - startOffset;
}
function quantizeAndInverse(component, blockBufferOffset, p) {
  const qt = component.quantizationTable,
    blockData = component.blockData;
  let v0, v1, v2, v3, v4, v5, v6, v7;
  let p0, p1, p2, p3, p4, p5, p6, p7;
  let t;
  if (!qt) {
    throw new JpegError("missing required Quantization Table.");
  }
  for (let row = 0; row < 64; row += 8) {
    p0 = blockData[blockBufferOffset + row];
    p1 = blockData[blockBufferOffset + row + 1];
    p2 = blockData[blockBufferOffset + row + 2];
    p3 = blockData[blockBufferOffset + row + 3];
    p4 = blockData[blockBufferOffset + row + 4];
    p5 = blockData[blockBufferOffset + row + 5];
    p6 = blockData[blockBufferOffset + row + 6];
    p7 = blockData[blockBufferOffset + row + 7];
    p0 *= qt[row];
    if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
      t = dctSqrt2 * p0 + 512 >> 10;
      p[row] = t;
      p[row + 1] = t;
      p[row + 2] = t;
      p[row + 3] = t;
      p[row + 4] = t;
      p[row + 5] = t;
      p[row + 6] = t;
      p[row + 7] = t;
      continue;
    }
    p1 *= qt[row + 1];
    p2 *= qt[row + 2];
    p3 *= qt[row + 3];
    p4 *= qt[row + 4];
    p5 *= qt[row + 5];
    p6 *= qt[row + 6];
    p7 *= qt[row + 7];
    v0 = dctSqrt2 * p0 + 128 >> 8;
    v1 = dctSqrt2 * p4 + 128 >> 8;
    v2 = p2;
    v3 = p6;
    v4 = dctSqrt1d2 * (p1 - p7) + 128 >> 8;
    v7 = dctSqrt1d2 * (p1 + p7) + 128 >> 8;
    v5 = p3 << 4;
    v6 = p5 << 4;
    v0 = v0 + v1 + 1 >> 1;
    v1 = v0 - v1;
    t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8;
    v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8;
    v3 = t;
    v4 = v4 + v6 + 1 >> 1;
    v6 = v4 - v6;
    v7 = v7 + v5 + 1 >> 1;
    v5 = v7 - v5;
    v0 = v0 + v3 + 1 >> 1;
    v3 = v0 - v3;
    v1 = v1 + v2 + 1 >> 1;
    v2 = v1 - v2;
    t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
    v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
    v7 = t;
    t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
    v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
    v6 = t;
    p[row] = v0 + v7;
    p[row + 7] = v0 - v7;
    p[row + 1] = v1 + v6;
    p[row + 6] = v1 - v6;
    p[row + 2] = v2 + v5;
    p[row + 5] = v2 - v5;
    p[row + 3] = v3 + v4;
    p[row + 4] = v3 - v4;
  }
  for (let col = 0; col < 8; ++col) {
    p0 = p[col];
    p1 = p[col + 8];
    p2 = p[col + 16];
    p3 = p[col + 24];
    p4 = p[col + 32];
    p5 = p[col + 40];
    p6 = p[col + 48];
    p7 = p[col + 56];
    if ((p1 | p2 | p3 | p4 | p5 | p6 | p7) === 0) {
      t = dctSqrt2 * p0 + 8192 >> 14;
      if (t < -2040) {
        t = 0;
      } else if (t >= 2024) {
        t = 255;
      } else {
        t = t + 2056 >> 4;
      }
      blockData[blockBufferOffset + col] = t;
      blockData[blockBufferOffset + col + 8] = t;
      blockData[blockBufferOffset + col + 16] = t;
      blockData[blockBufferOffset + col + 24] = t;
      blockData[blockBufferOffset + col + 32] = t;
      blockData[blockBufferOffset + col + 40] = t;
      blockData[blockBufferOffset + col + 48] = t;
      blockData[blockBufferOffset + col + 56] = t;
      continue;
    }
    v0 = dctSqrt2 * p0 + 2048 >> 12;
    v1 = dctSqrt2 * p4 + 2048 >> 12;
    v2 = p2;
    v3 = p6;
    v4 = dctSqrt1d2 * (p1 - p7) + 2048 >> 12;
    v7 = dctSqrt1d2 * (p1 + p7) + 2048 >> 12;
    v5 = p3;
    v6 = p5;
    v0 = (v0 + v1 + 1 >> 1) + 4112;
    v1 = v0 - v1;
    t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12;
    v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12;
    v3 = t;
    v4 = v4 + v6 + 1 >> 1;
    v6 = v4 - v6;
    v7 = v7 + v5 + 1 >> 1;
    v5 = v7 - v5;
    v0 = v0 + v3 + 1 >> 1;
    v3 = v0 - v3;
    v1 = v1 + v2 + 1 >> 1;
    v2 = v1 - v2;
    t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
    v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
    v7 = t;
    t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
    v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
    v6 = t;
    p0 = v0 + v7;
    p7 = v0 - v7;
    p1 = v1 + v6;
    p6 = v1 - v6;
    p2 = v2 + v5;
    p5 = v2 - v5;
    p3 = v3 + v4;
    p4 = v3 - v4;
    if (p0 < 16) {
      p0 = 0;
    } else if (p0 >= 4080) {
      p0 = 255;
    } else {
      p0 >>= 4;
    }
    if (p1 < 16) {
      p1 = 0;
    } else if (p1 >= 4080) {
      p1 = 255;
    } else {
      p1 >>= 4;
    }
    if (p2 < 16) {
      p2 = 0;
    } else if (p2 >= 4080) {
      p2 = 255;
    } else {
      p2 >>= 4;
    }
    if (p3 < 16) {
      p3 = 0;
    } else if (p3 >= 4080) {
      p3 = 255;
    } else {
      p3 >>= 4;
    }
    if (p4 < 16) {
      p4 = 0;
    } else if (p4 >= 4080) {
      p4 = 255;
    } else {
      p4 >>= 4;
    }
    if (p5 < 16) {
      p5 = 0;
    } else if (p5 >= 4080) {
      p5 = 255;
    } else {
      p5 >>= 4;
    }
    if (p6 < 16) {
      p6 = 0;
    } else if (p6 >= 4080) {
      p6 = 255;
    } else {
      p6 >>= 4;
    }
    if (p7 < 16) {
      p7 = 0;
    } else if (p7 >= 4080) {
      p7 = 255;
    } else {
      p7 >>= 4;
    }
    blockData[blockBufferOffset + col] = p0;
    blockData[blockBufferOffset + col + 8] = p1;
    blockData[blockBufferOffset + col + 16] = p2;
    blockData[blockBufferOffset + col + 24] = p3;
    blockData[blockBufferOffset + col + 32] = p4;
    blockData[blockBufferOffset + col + 40] = p5;
    blockData[blockBufferOffset + col + 48] = p6;
    blockData[blockBufferOffset + col + 56] = p7;
  }
}
function buildComponentData(frame, component) {
  const blocksPerLine = component.blocksPerLine;
  const blocksPerColumn = component.blocksPerColumn;
  const computationBuffer = new Int16Array(64);
  for (let blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
    for (let blockCol = 0; blockCol < blocksPerLine; blockCol++) {
      const offset = getBlockBufferOffset(component, blockRow, blockCol);
      quantizeAndInverse(component, offset, computationBuffer);
    }
  }
  return component.blockData;
}
function findNextFileMarker(data, currentPos, startPos = currentPos) {
  const maxPos = data.length - 1;
  let newPos = startPos < currentPos ? startPos : currentPos;
  if (currentPos >= maxPos) {
    return null;
  }
  const currentMarker = (0, _core_utils.readUint16)(data, currentPos);
  if (currentMarker >= 0xffc0 && currentMarker <= 0xfffe) {
    return {
      invalid: null,
      marker: currentMarker,
      offset: currentPos
    };
  }
  let newMarker = (0, _core_utils.readUint16)(data, newPos);
  while (!(newMarker >= 0xffc0 && newMarker <= 0xfffe)) {
    if (++newPos >= maxPos) {
      return null;
    }
    newMarker = (0, _core_utils.readUint16)(data, newPos);
  }
  return {
    invalid: currentMarker.toString(16),
    marker: newMarker,
    offset: newPos
  };
}
class JpegImage {
  constructor({
    decodeTransform = null,
    colorTransform = -1
  } = {}) {
    this._decodeTransform = decodeTransform;
    this._colorTransform = colorTransform;
  }
  parse(data, {
    dnlScanLines = null
  } = {}) {
    function readDataBlock() {
      const length = (0, _core_utils.readUint16)(data, offset);
      offset += 2;
      let endOffset = offset + length - 2;
      const fileMarker = findNextFileMarker(data, endOffset, offset);
      if (fileMarker && fileMarker.invalid) {
        (0, _util.warn)("readDataBlock - incorrect length, current marker is: " + fileMarker.invalid);
        endOffset = fileMarker.offset;
      }
      const array = data.subarray(offset, endOffset);
      offset += array.length;
      return array;
    }
    function prepareComponents(frame) {
      const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
      const mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
      for (const component of frame.components) {
        const blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / frame.maxH);
        const blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / frame.maxV);
        const blocksPerLineForMcu = mcusPerLine * component.h;
        const blocksPerColumnForMcu = mcusPerColumn * component.v;
        const blocksBufferSize = 64 * blocksPerColumnForMcu * (blocksPerLineForMcu + 1);
        component.blockData = new Int16Array(blocksBufferSize);
        component.blocksPerLine = blocksPerLine;
        component.blocksPerColumn = blocksPerColumn;
      }
      frame.mcusPerLine = mcusPerLine;
      frame.mcusPerColumn = mcusPerColumn;
    }
    let offset = 0;
    let jfif = null;
    let adobe = null;
    let frame, resetInterval;
    let numSOSMarkers = 0;
    const quantizationTables = [];
    const huffmanTablesAC = [],
      huffmanTablesDC = [];
    let fileMarker = (0, _core_utils.readUint16)(data, offset);
    offset += 2;
    if (fileMarker !== 0xffd8) {
      throw new JpegError("SOI not found");
    }
    fileMarker = (0, _core_utils.readUint16)(data, offset);
    offset += 2;
    markerLoop: while (fileMarker !== 0xffd9) {
      let i, j, l;
      switch (fileMarker) {
        case 0xffe0:
        case 0xffe1:
        case 0xffe2:
        case 0xffe3:
        case 0xffe4:
        case 0xffe5:
        case 0xffe6:
        case 0xffe7:
        case 0xffe8:
        case 0xffe9:
        case 0xffea:
        case 0xffeb:
        case 0xffec:
        case 0xffed:
        case 0xffee:
        case 0xffef:
        case 0xfffe:
          const appData = readDataBlock();
          if (fileMarker === 0xffe0) {
            if (appData[0] === 0x4a && appData[1] === 0x46 && appData[2] === 0x49 && appData[3] === 0x46 && appData[4] === 0) {
              jfif = {
                version: {
                  major: appData[5],
                  minor: appData[6]
                },
                densityUnits: appData[7],
                xDensity: appData[8] << 8 | appData[9],
                yDensity: appData[10] << 8 | appData[11],
                thumbWidth: appData[12],
                thumbHeight: appData[13],
                thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
              };
            }
          }
          if (fileMarker === 0xffee) {
            if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6f && appData[3] === 0x62 && appData[4] === 0x65) {
              adobe = {
                version: appData[5] << 8 | appData[6],
                flags0: appData[7] << 8 | appData[8],
                flags1: appData[9] << 8 | appData[10],
                transformCode: appData[11]
              };
            }
          }
          break;
        case 0xffdb:
          const quantizationTablesLength = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          const quantizationTablesEnd = quantizationTablesLength + offset - 2;
          let z;
          while (offset < quantizationTablesEnd) {
            const quantizationTableSpec = data[offset++];
            const tableData = new Uint16Array(64);
            if (quantizationTableSpec >> 4 === 0) {
              for (j = 0; j < 64; j++) {
                z = dctZigZag[j];
                tableData[z] = data[offset++];
              }
            } else if (quantizationTableSpec >> 4 === 1) {
              for (j = 0; j < 64; j++) {
                z = dctZigZag[j];
                tableData[z] = (0, _core_utils.readUint16)(data, offset);
                offset += 2;
              }
            } else {
              throw new JpegError("DQT - invalid table spec");
            }
            quantizationTables[quantizationTableSpec & 15] = tableData;
          }
          break;
        case 0xffc0:
        case 0xffc1:
        case 0xffc2:
          if (frame) {
            throw new JpegError("Only single frame JPEGs supported");
          }
          offset += 2;
          frame = {};
          frame.extended = fileMarker === 0xffc1;
          frame.progressive = fileMarker === 0xffc2;
          frame.precision = data[offset++];
          const sofScanLines = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          frame.scanLines = dnlScanLines || sofScanLines;
          frame.samplesPerLine = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          frame.components = [];
          frame.componentIds = {};
          const componentsCount = data[offset++];
          let maxH = 0,
            maxV = 0;
          for (i = 0; i < componentsCount; i++) {
            const componentId = data[offset];
            const h = data[offset + 1] >> 4;
            const v = data[offset + 1] & 15;
            if (maxH < h) {
              maxH = h;
            }
            if (maxV < v) {
              maxV = v;
            }
            const qId = data[offset + 2];
            l = frame.components.push({
              h,
              v,
              quantizationId: qId,
              quantizationTable: null
            });
            frame.componentIds[componentId] = l - 1;
            offset += 3;
          }
          frame.maxH = maxH;
          frame.maxV = maxV;
          prepareComponents(frame);
          break;
        case 0xffc4:
          const huffmanLength = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          for (i = 2; i < huffmanLength;) {
            const huffmanTableSpec = data[offset++];
            const codeLengths = new Uint8Array(16);
            let codeLengthSum = 0;
            for (j = 0; j < 16; j++, offset++) {
              codeLengthSum += codeLengths[j] = data[offset];
            }
            const huffmanValues = new Uint8Array(codeLengthSum);
            for (j = 0; j < codeLengthSum; j++, offset++) {
              huffmanValues[j] = data[offset];
            }
            i += 17 + codeLengthSum;
            (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
          }
          break;
        case 0xffdd:
          offset += 2;
          resetInterval = (0, _core_utils.readUint16)(data, offset);
          offset += 2;
          break;
        case 0xffda:
          const parseDNLMarker = ++numSOSMarkers === 1 && !dnlScanLines;
          offset += 2;
          const selectorsCount = data[offset++],
            components = [];
          for (i = 0; i < selectorsCount; i++) {
            const index = data[offset++];
            const componentIndex = frame.componentIds[index];
            const component = frame.components[componentIndex];
            component.index = index;
            const tableSpec = data[offset++];
            component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
            component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
            components.push(component);
          }
          const spectralStart = data[offset++],
            spectralEnd = data[offset++],
            successiveApproximation = data[offset++];
          try {
            const processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15, parseDNLMarker);
            offset += processed;
          } catch (ex) {
            if (ex instanceof DNLMarkerError) {
              (0, _util.warn)(`${ex.message} -- attempting to re-parse the JPEG image.`);
              return this.parse(data, {
                dnlScanLines: ex.scanLines
              });
            } else if (ex instanceof EOIMarkerError) {
              (0, _util.warn)(`${ex.message} -- ignoring the rest of the image data.`);
              break markerLoop;
            }
            throw ex;
          }
          break;
        case 0xffdc:
          offset += 4;
          break;
        case 0xffff:
          if (data[offset] !== 0xff) {
            offset--;
          }
          break;
        default:
          const nextFileMarker = findNextFileMarker(data, offset - 2, offset - 3);
          if (nextFileMarker && nextFileMarker.invalid) {
            (0, _util.warn)("JpegImage.parse - unexpected data, current marker is: " + nextFileMarker.invalid);
            offset = nextFileMarker.offset;
            break;
          }
          if (!nextFileMarker || offset >= data.length - 1) {
            (0, _util.warn)("JpegImage.parse - reached the end of the image data " + "without finding an EOI marker (0xFFD9).");
            break markerLoop;
          }
          throw new JpegError("JpegImage.parse - unknown marker: " + fileMarker.toString(16));
      }
      fileMarker = (0, _core_utils.readUint16)(data, offset);
      offset += 2;
    }
    this.width = frame.samplesPerLine;
    this.height = frame.scanLines;
    this.jfif = jfif;
    this.adobe = adobe;
    this.components = [];
    for (const component of frame.components) {
      const quantizationTable = quantizationTables[component.quantizationId];
      if (quantizationTable) {
        component.quantizationTable = quantizationTable;
      }
      this.components.push({
        index: component.index,
        output: buildComponentData(frame, component),
        scaleX: component.h / frame.maxH,
        scaleY: component.v / frame.maxV,
        blocksPerLine: component.blocksPerLine,
        blocksPerColumn: component.blocksPerColumn
      });
    }
    this.numComponents = this.components.length;
    return undefined;
  }
  _getLinearizedBlockData(width, height, isSourcePDF = false) {
    const scaleX = this.width / width,
      scaleY = this.height / height;
    let component, componentScaleX, componentScaleY, blocksPerScanline;
    let x, y, i, j, k;
    let index;
    let offset = 0;
    let output;
    const numComponents = this.components.length;
    const dataLength = width * height * numComponents;
    const data = new Uint8ClampedArray(dataLength);
    const xScaleBlockOffset = new Uint32Array(width);
    const mask3LSB = 0xfffffff8;
    let lastComponentScaleX;
    for (i = 0; i < numComponents; i++) {
      component = this.components[i];
      componentScaleX = component.scaleX * scaleX;
      componentScaleY = component.scaleY * scaleY;
      offset = i;
      output = component.output;
      blocksPerScanline = component.blocksPerLine + 1 << 3;
      if (componentScaleX !== lastComponentScaleX) {
        for (x = 0; x < width; x++) {
          j = 0 | x * componentScaleX;
          xScaleBlockOffset[x] = (j & mask3LSB) << 3 | j & 7;
        }
        lastComponentScaleX = componentScaleX;
      }
      for (y = 0; y < height; y++) {
        j = 0 | y * componentScaleY;
        index = blocksPerScanline * (j & mask3LSB) | (j & 7) << 3;
        for (x = 0; x < width; x++) {
          data[offset] = output[index + xScaleBlockOffset[x]];
          offset += numComponents;
        }
      }
    }
    let transform = this._decodeTransform;
    if (!isSourcePDF && numComponents === 4 && !transform) {
      transform = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]);
    }
    if (transform) {
      for (i = 0; i < dataLength;) {
        for (j = 0, k = 0; j < numComponents; j++, i++, k += 2) {
          data[i] = (data[i] * transform[k] >> 8) + transform[k + 1];
        }
      }
    }
    return data;
  }
  get _isColorConversionNeeded() {
    if (this.adobe) {
      return !!this.adobe.transformCode;
    }
    if (this.numComponents === 3) {
      if (this._colorTransform === 0) {
        return false;
      } else if (this.components[0].index === 0x52 && this.components[1].index === 0x47 && this.components[2].index === 0x42) {
        return false;
      }
      return true;
    }
    if (this._colorTransform === 1) {
      return true;
    }
    return false;
  }
  _convertYccToRgb(data) {
    let Y, Cb, Cr;
    for (let i = 0, length = data.length; i < length; i += 3) {
      Y = data[i];
      Cb = data[i + 1];
      Cr = data[i + 2];
      data[i] = Y - 179.456 + 1.402 * Cr;
      data[i + 1] = Y + 135.459 - 0.344 * Cb - 0.714 * Cr;
      data[i + 2] = Y - 226.816 + 1.772 * Cb;
    }
    return data;
  }
  _convertYcckToRgb(data) {
    let Y, Cb, Cr, k;
    let offset = 0;
    for (let i = 0, length = data.length; i < length; i += 4) {
      Y = data[i];
      Cb = data[i + 1];
      Cr = data[i + 2];
      k = data[i + 3];
      data[offset++] = -122.67195406894 + Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr - 5.4080610064599e-5 * Y + 0.00048449797120281 * k - 0.154362151871126) + Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y - 0.00477271405408747 * k + 1.53380253221734) + Y * (0.000961250184130688 * Y - 0.00266257332283933 * k + 0.48357088451265) + k * (-0.000336197177618394 * k + 0.484791561490776);
      data[offset++] = 107.268039397724 + Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr + 0.000659397001245577 * Y + 0.000426105652938837 * k - 0.176491792462875) + Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y + 0.000770482631801132 * k - 0.151051492775562) + Y * (0.00126935368114843 * Y - 0.00265090189010898 * k + 0.25802910206845) + k * (-0.000318913117588328 * k - 0.213742400323665);
      data[offset++] = -20.810012546947 + Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr + 0.0020741088115012 * Y - 0.00288260236853442 * k + 0.814272968359295) + Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y + 0.000560833691242812 * k - 0.195152027534049) + Y * (0.00174418132927582 * Y - 0.00255243321439347 * k + 0.116935020465145) + k * (-0.000343531996510555 * k + 0.24165260232407);
    }
    return data.subarray(0, offset);
  }
  _convertYcckToCmyk(data) {
    let Y, Cb, Cr;
    for (let i = 0, length = data.length; i < length; i += 4) {
      Y = data[i];
      Cb = data[i + 1];
      Cr = data[i + 2];
      data[i] = 434.456 - Y - 1.402 * Cr;
      data[i + 1] = 119.541 - Y + 0.344 * Cb + 0.714 * Cr;
      data[i + 2] = 481.816 - Y - 1.772 * Cb;
    }
    return data;
  }
  _convertCmykToRgb(data) {
    let c, m, y, k;
    let offset = 0;
    for (let i = 0, length = data.length; i < length; i += 4) {
      c = data[i];
      m = data[i + 1];
      y = data[i + 2];
      k = data[i + 3];
      data[offset++] = 255 + c * (-0.00006747147073602441 * c + 0.0008379262121013727 * m + 0.0002894718188643294 * y + 0.003264231057537806 * k - 1.1185611867203937) + m * (0.000026374107616089405 * m - 0.00008626949158638572 * y - 0.0002748769067499491 * k - 0.02155688794978967) + y * (-0.00003878099212869363 * y - 0.0003267808279485286 * k + 0.0686742238595345) - k * (0.0003361971776183937 * k + 0.7430659151342254);
      data[offset++] = 255 + c * (0.00013596372813588848 * c + 0.000924537132573585 * m + 0.00010567359618683593 * y + 0.0004791864687436512 * k - 0.3109689587515875) + m * (-0.00023545346108370344 * m + 0.0002702845253534714 * y + 0.0020200308977307156 * k - 0.7488052167015494) + y * (0.00006834815998235662 * y + 0.00015168452363460973 * k - 0.09751927774728933) - k * (0.0003189131175883281 * k + 0.7364883807733168);
      data[offset++] = 255 + c * (0.000013598650411385307 * c + 0.00012423956175490851 * m + 0.0004751985097583589 * y - 0.0000036729317476630422 * k - 0.05562186980264034) + m * (0.00016141380598724676 * m + 0.0009692239130725186 * y + 0.0007782692450036253 * k - 0.44015232367526463) + y * (5.068882914068769e-7 * y + 0.0017778369011375071 * k - 0.7591454649749609) - k * (0.0003435319965105553 * k + 0.7063770186160144);
    }
    return data.subarray(0, offset);
  }
  getData({
    width,
    height,
    forceRGB = false,
    isSourcePDF = false
  }) {
    if (this.numComponents > 4) {
      throw new JpegError("Unsupported color mode");
    }
    const data = this._getLinearizedBlockData(width, height, isSourcePDF);
    if (this.numComponents === 1 && forceRGB) {
      const rgbData = new Uint8ClampedArray(data.length * 3);
      let offset = 0;
      for (const grayColor of data) {
        rgbData[offset++] = grayColor;
        rgbData[offset++] = grayColor;
        rgbData[offset++] = grayColor;
      }
      return rgbData;
    } else if (this.numComponents === 3 && this._isColorConversionNeeded) {
      return this._convertYccToRgb(data);
    } else if (this.numComponents === 4) {
      if (this._isColorConversionNeeded) {
        if (forceRGB) {
          return this._convertYcckToRgb(data);
        }
        return this._convertYcckToCmyk(data);
      } else if (forceRGB) {
        return this._convertCmykToRgb(data);
      }
    }
    return data;
  }
}
exports.JpegImage = JpegImage;

/***/ }),
/* 27 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.JpxStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
var _jpx = __w_pdfjs_require__(28);
var _util = __w_pdfjs_require__(2);
class JpxStream extends _decode_stream.DecodeStream {
  constructor(stream, maybeLength, params) {
    super(maybeLength);
    this.stream = stream;
    this.dict = stream.dict;
    this.maybeLength = maybeLength;
    this.params = params;
  }
  get bytes() {
    return (0, _util.shadow)(this, "bytes", this.stream.getBytes(this.maybeLength));
  }
  ensureBuffer(requested) {}
  readBlock() {
    if (this.eof) {
      return;
    }
    const jpxImage = new _jpx.JpxImage();
    jpxImage.parse(this.bytes);
    const width = jpxImage.width;
    const height = jpxImage.height;
    const componentsCount = jpxImage.componentsCount;
    const tileCount = jpxImage.tiles.length;
    if (tileCount === 1) {
      this.buffer = jpxImage.tiles[0].items;
    } else {
      const data = new Uint8ClampedArray(width * height * componentsCount);
      for (let k = 0; k < tileCount; k++) {
        const tileComponents = jpxImage.tiles[k];
        const tileWidth = tileComponents.width;
        const tileHeight = tileComponents.height;
        const tileLeft = tileComponents.left;
        const tileTop = tileComponents.top;
        const src = tileComponents.items;
        let srcPosition = 0;
        let dataPosition = (width * tileTop + tileLeft) * componentsCount;
        const imgRowSize = width * componentsCount;
        const tileRowSize = tileWidth * componentsCount;
        for (let j = 0; j < tileHeight; j++) {
          const rowBytes = src.subarray(srcPosition, srcPosition + tileRowSize);
          data.set(rowBytes, dataPosition);
          srcPosition += tileRowSize;
          dataPosition += imgRowSize;
        }
      }
      this.buffer = data;
    }
    this.bufferLength = this.buffer.length;
    this.eof = true;
  }
}
exports.JpxStream = JpxStream;

/***/ }),
/* 28 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.JpxImage = void 0;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _arithmetic_decoder = __w_pdfjs_require__(24);
class JpxError extends _util.BaseException {
  constructor(msg) {
    super(`JPX error: ${msg}`, "JpxError");
  }
}
const SubbandsGainLog2 = {
  LL: 0,
  LH: 1,
  HL: 1,
  HH: 2
};
class JpxImage {
  constructor() {
    this.failOnCorruptedImage = false;
  }
  parse(data) {
    const head = (0, _core_utils.readUint16)(data, 0);
    if (head === 0xff4f) {
      this.parseCodestream(data, 0, data.length);
      return;
    }
    const length = data.length;
    let position = 0;
    while (position < length) {
      let headerSize = 8;
      let lbox = (0, _core_utils.readUint32)(data, position);
      const tbox = (0, _core_utils.readUint32)(data, position + 4);
      position += headerSize;
      if (lbox === 1) {
        lbox = (0, _core_utils.readUint32)(data, position) * 4294967296 + (0, _core_utils.readUint32)(data, position + 4);
        position += 8;
        headerSize += 8;
      }
      if (lbox === 0) {
        lbox = length - position + headerSize;
      }
      if (lbox < headerSize) {
        throw new JpxError("Invalid box field size");
      }
      const dataLength = lbox - headerSize;
      let jumpDataLength = true;
      switch (tbox) {
        case 0x6a703268:
          jumpDataLength = false;
          break;
        case 0x636f6c72:
          const method = data[position];
          if (method === 1) {
            const colorspace = (0, _core_utils.readUint32)(data, position + 3);
            switch (colorspace) {
              case 16:
              case 17:
              case 18:
                break;
              default:
                (0, _util.warn)("Unknown colorspace " + colorspace);
                break;
            }
          } else if (method === 2) {
            (0, _util.info)("ICC profile not supported");
          }
          break;
        case 0x6a703263:
          this.parseCodestream(data, position, position + dataLength);
          break;
        case 0x6a502020:
          if ((0, _core_utils.readUint32)(data, position) !== 0x0d0a870a) {
            (0, _util.warn)("Invalid JP2 signature");
          }
          break;
        case 0x6a501a1a:
        case 0x66747970:
        case 0x72726571:
        case 0x72657320:
        case 0x69686472:
          break;
        default:
          const headerType = String.fromCharCode(tbox >> 24 & 0xff, tbox >> 16 & 0xff, tbox >> 8 & 0xff, tbox & 0xff);
          (0, _util.warn)(`Unsupported header type ${tbox} (${headerType}).`);
          break;
      }
      if (jumpDataLength) {
        position += dataLength;
      }
    }
  }
  parseImageProperties(stream) {
    let newByte = stream.getByte();
    while (newByte >= 0) {
      const oldByte = newByte;
      newByte = stream.getByte();
      const code = oldByte << 8 | newByte;
      if (code === 0xff51) {
        stream.skip(4);
        const Xsiz = stream.getInt32() >>> 0;
        const Ysiz = stream.getInt32() >>> 0;
        const XOsiz = stream.getInt32() >>> 0;
        const YOsiz = stream.getInt32() >>> 0;
        stream.skip(16);
        const Csiz = stream.getUint16();
        this.width = Xsiz - XOsiz;
        this.height = Ysiz - YOsiz;
        this.componentsCount = Csiz;
        this.bitsPerComponent = 8;
        return;
      }
    }
    throw new JpxError("No size marker found in JPX stream");
  }
  parseCodestream(data, start, end) {
    const context = {};
    let doNotRecover = false;
    try {
      let position = start;
      while (position + 1 < end) {
        const code = (0, _core_utils.readUint16)(data, position);
        position += 2;
        let length = 0,
          j,
          sqcd,
          spqcds,
          spqcdSize,
          scalarExpounded,
          tile;
        switch (code) {
          case 0xff4f:
            context.mainHeader = true;
            break;
          case 0xffd9:
            break;
          case 0xff51:
            length = (0, _core_utils.readUint16)(data, position);
            const siz = {};
            siz.Xsiz = (0, _core_utils.readUint32)(data, position + 4);
            siz.Ysiz = (0, _core_utils.readUint32)(data, position + 8);
            siz.XOsiz = (0, _core_utils.readUint32)(data, position + 12);
            siz.YOsiz = (0, _core_utils.readUint32)(data, position + 16);
            siz.XTsiz = (0, _core_utils.readUint32)(data, position + 20);
            siz.YTsiz = (0, _core_utils.readUint32)(data, position + 24);
            siz.XTOsiz = (0, _core_utils.readUint32)(data, position + 28);
            siz.YTOsiz = (0, _core_utils.readUint32)(data, position + 32);
            const componentsCount = (0, _core_utils.readUint16)(data, position + 36);
            siz.Csiz = componentsCount;
            const components = [];
            j = position + 38;
            for (let i = 0; i < componentsCount; i++) {
              const component = {
                precision: (data[j] & 0x7f) + 1,
                isSigned: !!(data[j] & 0x80),
                XRsiz: data[j + 1],
                YRsiz: data[j + 2]
              };
              j += 3;
              calculateComponentDimensions(component, siz);
              components.push(component);
            }
            context.SIZ = siz;
            context.components = components;
            calculateTileGrids(context, components);
            context.QCC = [];
            context.COC = [];
            break;
          case 0xff5c:
            length = (0, _core_utils.readUint16)(data, position);
            const qcd = {};
            j = position + 2;
            sqcd = data[j++];
            switch (sqcd & 0x1f) {
              case 0:
                spqcdSize = 8;
                scalarExpounded = true;
                break;
              case 1:
                spqcdSize = 16;
                scalarExpounded = false;
                break;
              case 2:
                spqcdSize = 16;
                scalarExpounded = true;
                break;
              default:
                throw new Error("Invalid SQcd value " + sqcd);
            }
            qcd.noQuantization = spqcdSize === 8;
            qcd.scalarExpounded = scalarExpounded;
            qcd.guardBits = sqcd >> 5;
            spqcds = [];
            while (j < length + position) {
              const spqcd = {};
              if (spqcdSize === 8) {
                spqcd.epsilon = data[j++] >> 3;
                spqcd.mu = 0;
              } else {
                spqcd.epsilon = data[j] >> 3;
                spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
                j += 2;
              }
              spqcds.push(spqcd);
            }
            qcd.SPqcds = spqcds;
            if (context.mainHeader) {
              context.QCD = qcd;
            } else {
              context.currentTile.QCD = qcd;
              context.currentTile.QCC = [];
            }
            break;
          case 0xff5d:
            length = (0, _core_utils.readUint16)(data, position);
            const qcc = {};
            j = position + 2;
            let cqcc;
            if (context.SIZ.Csiz < 257) {
              cqcc = data[j++];
            } else {
              cqcc = (0, _core_utils.readUint16)(data, j);
              j += 2;
            }
            sqcd = data[j++];
            switch (sqcd & 0x1f) {
              case 0:
                spqcdSize = 8;
                scalarExpounded = true;
                break;
              case 1:
                spqcdSize = 16;
                scalarExpounded = false;
                break;
              case 2:
                spqcdSize = 16;
                scalarExpounded = true;
                break;
              default:
                throw new Error("Invalid SQcd value " + sqcd);
            }
            qcc.noQuantization = spqcdSize === 8;
            qcc.scalarExpounded = scalarExpounded;
            qcc.guardBits = sqcd >> 5;
            spqcds = [];
            while (j < length + position) {
              const spqcd = {};
              if (spqcdSize === 8) {
                spqcd.epsilon = data[j++] >> 3;
                spqcd.mu = 0;
              } else {
                spqcd.epsilon = data[j] >> 3;
                spqcd.mu = (data[j] & 0x7) << 8 | data[j + 1];
                j += 2;
              }
              spqcds.push(spqcd);
            }
            qcc.SPqcds = spqcds;
            if (context.mainHeader) {
              context.QCC[cqcc] = qcc;
            } else {
              context.currentTile.QCC[cqcc] = qcc;
            }
            break;
          case 0xff52:
            length = (0, _core_utils.readUint16)(data, position);
            const cod = {};
            j = position + 2;
            const scod = data[j++];
            cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
            cod.sopMarkerUsed = !!(scod & 2);
            cod.ephMarkerUsed = !!(scod & 4);
            cod.progressionOrder = data[j++];
            cod.layersCount = (0, _core_utils.readUint16)(data, j);
            j += 2;
            cod.multipleComponentTransform = data[j++];
            cod.decompositionLevelsCount = data[j++];
            cod.xcb = (data[j++] & 0xf) + 2;
            cod.ycb = (data[j++] & 0xf) + 2;
            const blockStyle = data[j++];
            cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
            cod.resetContextProbabilities = !!(blockStyle & 2);
            cod.terminationOnEachCodingPass = !!(blockStyle & 4);
            cod.verticallyStripe = !!(blockStyle & 8);
            cod.predictableTermination = !!(blockStyle & 16);
            cod.segmentationSymbolUsed = !!(blockStyle & 32);
            cod.reversibleTransformation = data[j++];
            if (cod.entropyCoderWithCustomPrecincts) {
              const precinctsSizes = [];
              while (j < length + position) {
                const precinctsSize = data[j++];
                precinctsSizes.push({
                  PPx: precinctsSize & 0xf,
                  PPy: precinctsSize >> 4
                });
              }
              cod.precinctsSizes = precinctsSizes;
            }
            const unsupported = [];
            if (cod.selectiveArithmeticCodingBypass) {
              unsupported.push("selectiveArithmeticCodingBypass");
            }
            if (cod.terminationOnEachCodingPass) {
              unsupported.push("terminationOnEachCodingPass");
            }
            if (cod.verticallyStripe) {
              unsupported.push("verticallyStripe");
            }
            if (cod.predictableTermination) {
              unsupported.push("predictableTermination");
            }
            if (unsupported.length > 0) {
              doNotRecover = true;
              (0, _util.warn)(`JPX: Unsupported COD options (${unsupported.join(", ")}).`);
            }
            if (context.mainHeader) {
              context.COD = cod;
            } else {
              context.currentTile.COD = cod;
              context.currentTile.COC = [];
            }
            break;
          case 0xff90:
            length = (0, _core_utils.readUint16)(data, position);
            tile = {};
            tile.index = (0, _core_utils.readUint16)(data, position + 2);
            tile.length = (0, _core_utils.readUint32)(data, position + 4);
            tile.dataEnd = tile.length + position - 2;
            tile.partIndex = data[position + 8];
            tile.partsCount = data[position + 9];
            context.mainHeader = false;
            if (tile.partIndex === 0) {
              tile.COD = context.COD;
              tile.COC = context.COC.slice(0);
              tile.QCD = context.QCD;
              tile.QCC = context.QCC.slice(0);
            }
            context.currentTile = tile;
            break;
          case 0xff93:
            tile = context.currentTile;
            if (tile.partIndex === 0) {
              initializeTile(context, tile.index);
              buildPackets(context);
            }
            length = tile.dataEnd - position;
            parseTilePackets(context, data, position, length);
            break;
          case 0xff53:
            (0, _util.warn)("JPX: Codestream code 0xFF53 (COC) is not implemented.");
          case 0xff55:
          case 0xff57:
          case 0xff58:
          case 0xff64:
            length = (0, _core_utils.readUint16)(data, position);
            break;
          default:
            throw new Error("Unknown codestream code: " + code.toString(16));
        }
        position += length;
      }
    } catch (e) {
      if (doNotRecover || this.failOnCorruptedImage) {
        throw new JpxError(e.message);
      } else {
        (0, _util.warn)(`JPX: Trying to recover from: "${e.message}".`);
      }
    }
    this.tiles = transformComponents(context);
    this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
    this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
    this.componentsCount = context.SIZ.Csiz;
  }
}
exports.JpxImage = JpxImage;
function calculateComponentDimensions(component, siz) {
  component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
  component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
  component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
  component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
  component.width = component.x1 - component.x0;
  component.height = component.y1 - component.y0;
}
function calculateTileGrids(context, components) {
  const siz = context.SIZ;
  const tiles = [];
  let tile;
  const numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
  const numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
  for (let q = 0; q < numYtiles; q++) {
    for (let p = 0; p < numXtiles; p++) {
      tile = {};
      tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
      tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
      tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
      tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
      tile.width = tile.tx1 - tile.tx0;
      tile.height = tile.ty1 - tile.ty0;
      tile.components = [];
      tiles.push(tile);
    }
  }
  context.tiles = tiles;
  const componentsCount = siz.Csiz;
  for (let i = 0, ii = componentsCount; i < ii; i++) {
    const component = components[i];
    for (let j = 0, jj = tiles.length; j < jj; j++) {
      const tileComponent = {};
      tile = tiles[j];
      tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
      tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
      tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
      tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
      tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
      tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
      tile.components[i] = tileComponent;
    }
  }
}
function getBlocksDimensions(context, component, r) {
  const codOrCoc = component.codingStyleParameters;
  const result = {};
  if (!codOrCoc.entropyCoderWithCustomPrecincts) {
    result.PPx = 15;
    result.PPy = 15;
  } else {
    result.PPx = codOrCoc.precinctsSizes[r].PPx;
    result.PPy = codOrCoc.precinctsSizes[r].PPy;
  }
  result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) : Math.min(codOrCoc.xcb, result.PPx);
  result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) : Math.min(codOrCoc.ycb, result.PPy);
  return result;
}
function buildPrecincts(context, resolution, dimensions) {
  const precinctWidth = 1 << dimensions.PPx;
  const precinctHeight = 1 << dimensions.PPy;
  const isZeroRes = resolution.resLevel === 0;
  const precinctWidthInSubband = 1 << dimensions.PPx + (isZeroRes ? 0 : -1);
  const precinctHeightInSubband = 1 << dimensions.PPy + (isZeroRes ? 0 : -1);
  const numprecinctswide = resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0;
  const numprecinctshigh = resolution.try1 > resolution.try0 ? Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0;
  const numprecincts = numprecinctswide * numprecinctshigh;
  resolution.precinctParameters = {
    precinctWidth,
    precinctHeight,
    numprecinctswide,
    numprecinctshigh,
    numprecincts,
    precinctWidthInSubband,
    precinctHeightInSubband
  };
}
function buildCodeblocks(context, subband, dimensions) {
  const xcb_ = dimensions.xcb_;
  const ycb_ = dimensions.ycb_;
  const codeblockWidth = 1 << xcb_;
  const codeblockHeight = 1 << ycb_;
  const cbx0 = subband.tbx0 >> xcb_;
  const cby0 = subband.tby0 >> ycb_;
  const cbx1 = subband.tbx1 + codeblockWidth - 1 >> xcb_;
  const cby1 = subband.tby1 + codeblockHeight - 1 >> ycb_;
  const precinctParameters = subband.resolution.precinctParameters;
  const codeblocks = [];
  const precincts = [];
  let i, j, codeblock, precinctNumber;
  for (j = cby0; j < cby1; j++) {
    for (i = cbx0; i < cbx1; i++) {
      codeblock = {
        cbx: i,
        cby: j,
        tbx0: codeblockWidth * i,
        tby0: codeblockHeight * j,
        tbx1: codeblockWidth * (i + 1),
        tby1: codeblockHeight * (j + 1)
      };
      codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
      codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
      codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
      codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
      const pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / precinctParameters.precinctWidthInSubband);
      const pj = Math.floor((codeblock.tby0_ - subband.tby0) / precinctParameters.precinctHeightInSubband);
      precinctNumber = pi + pj * precinctParameters.numprecinctswide;
      codeblock.precinctNumber = precinctNumber;
      codeblock.subbandType = subband.type;
      codeblock.Lblock = 3;
      if (codeblock.tbx1_ <= codeblock.tbx0_ || codeblock.tby1_ <= codeblock.tby0_) {
        continue;
      }
      codeblocks.push(codeblock);
      let precinct = precincts[precinctNumber];
      if (precinct !== undefined) {
        if (i < precinct.cbxMin) {
          precinct.cbxMin = i;
        } else if (i > precinct.cbxMax) {
          precinct.cbxMax = i;
        }
        if (j < precinct.cbyMin) {
          precinct.cbxMin = j;
        } else if (j > precinct.cbyMax) {
          precinct.cbyMax = j;
        }
      } else {
        precincts[precinctNumber] = precinct = {
          cbxMin: i,
          cbyMin: j,
          cbxMax: i,
          cbyMax: j
        };
      }
      codeblock.precinct = precinct;
    }
  }
  subband.codeblockParameters = {
    codeblockWidth: xcb_,
    codeblockHeight: ycb_,
    numcodeblockwide: cbx1 - cbx0 + 1,
    numcodeblockhigh: cby1 - cby0 + 1
  };
  subband.codeblocks = codeblocks;
  subband.precincts = precincts;
}
function createPacket(resolution, precinctNumber, layerNumber) {
  const precinctCodeblocks = [];
  const subbands = resolution.subbands;
  for (let i = 0, ii = subbands.length; i < ii; i++) {
    const subband = subbands[i];
    const codeblocks = subband.codeblocks;
    for (let j = 0, jj = codeblocks.length; j < jj; j++) {
      const codeblock = codeblocks[j];
      if (codeblock.precinctNumber !== precinctNumber) {
        continue;
      }
      precinctCodeblocks.push(codeblock);
    }
  }
  return {
    layerNumber,
    codeblocks: precinctCodeblocks
  };
}
function LayerResolutionComponentPositionIterator(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const layersCount = tile.codingStyleDefaultParameters.layersCount;
  const componentsCount = siz.Csiz;
  let maxDecompositionLevelsCount = 0;
  for (let q = 0; q < componentsCount; q++) {
    maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  }
  let l = 0,
    r = 0,
    i = 0,
    k = 0;
  this.nextPacket = function JpxImage_nextPacket() {
    for (; l < layersCount; l++) {
      for (; r <= maxDecompositionLevelsCount; r++) {
        for (; i < componentsCount; i++) {
          const component = tile.components[i];
          if (r > component.codingStyleParameters.decompositionLevelsCount) {
            continue;
          }
          const resolution = component.resolutions[r];
          const numprecincts = resolution.precinctParameters.numprecincts;
          for (; k < numprecincts;) {
            const packet = createPacket(resolution, k, l);
            k++;
            return packet;
          }
          k = 0;
        }
        i = 0;
      }
      r = 0;
    }
    throw new JpxError("Out of packets");
  };
}
function ResolutionLayerComponentPositionIterator(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const layersCount = tile.codingStyleDefaultParameters.layersCount;
  const componentsCount = siz.Csiz;
  let maxDecompositionLevelsCount = 0;
  for (let q = 0; q < componentsCount; q++) {
    maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, tile.components[q].codingStyleParameters.decompositionLevelsCount);
  }
  let r = 0,
    l = 0,
    i = 0,
    k = 0;
  this.nextPacket = function JpxImage_nextPacket() {
    for (; r <= maxDecompositionLevelsCount; r++) {
      for (; l < layersCount; l++) {
        for (; i < componentsCount; i++) {
          const component = tile.components[i];
          if (r > component.codingStyleParameters.decompositionLevelsCount) {
            continue;
          }
          const resolution = component.resolutions[r];
          const numprecincts = resolution.precinctParameters.numprecincts;
          for (; k < numprecincts;) {
            const packet = createPacket(resolution, k, l);
            k++;
            return packet;
          }
          k = 0;
        }
        i = 0;
      }
      l = 0;
    }
    throw new JpxError("Out of packets");
  };
}
function ResolutionPositionComponentLayerIterator(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const layersCount = tile.codingStyleDefaultParameters.layersCount;
  const componentsCount = siz.Csiz;
  let l, r, c, p;
  let maxDecompositionLevelsCount = 0;
  for (c = 0; c < componentsCount; c++) {
    const component = tile.components[c];
    maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, component.codingStyleParameters.decompositionLevelsCount);
  }
  const maxNumPrecinctsInLevel = new Int32Array(maxDecompositionLevelsCount + 1);
  for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
    let maxNumPrecincts = 0;
    for (c = 0; c < componentsCount; ++c) {
      const resolutions = tile.components[c].resolutions;
      if (r < resolutions.length) {
        maxNumPrecincts = Math.max(maxNumPrecincts, resolutions[r].precinctParameters.numprecincts);
      }
    }
    maxNumPrecinctsInLevel[r] = maxNumPrecincts;
  }
  l = 0;
  r = 0;
  c = 0;
  p = 0;
  this.nextPacket = function JpxImage_nextPacket() {
    for (; r <= maxDecompositionLevelsCount; r++) {
      for (; p < maxNumPrecinctsInLevel[r]; p++) {
        for (; c < componentsCount; c++) {
          const component = tile.components[c];
          if (r > component.codingStyleParameters.decompositionLevelsCount) {
            continue;
          }
          const resolution = component.resolutions[r];
          const numprecincts = resolution.precinctParameters.numprecincts;
          if (p >= numprecincts) {
            continue;
          }
          for (; l < layersCount;) {
            const packet = createPacket(resolution, p, l);
            l++;
            return packet;
          }
          l = 0;
        }
        c = 0;
      }
      p = 0;
    }
    throw new JpxError("Out of packets");
  };
}
function PositionComponentResolutionLayerIterator(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const layersCount = tile.codingStyleDefaultParameters.layersCount;
  const componentsCount = siz.Csiz;
  const precinctsSizes = getPrecinctSizesInImageScale(tile);
  const precinctsIterationSizes = precinctsSizes;
  let l = 0,
    r = 0,
    c = 0,
    px = 0,
    py = 0;
  this.nextPacket = function JpxImage_nextPacket() {
    for (; py < precinctsIterationSizes.maxNumHigh; py++) {
      for (; px < precinctsIterationSizes.maxNumWide; px++) {
        for (; c < componentsCount; c++) {
          const component = tile.components[c];
          const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
          for (; r <= decompositionLevelsCount; r++) {
            const resolution = component.resolutions[r];
            const sizeInImageScale = precinctsSizes.components[c].resolutions[r];
            const k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
            if (k === null) {
              continue;
            }
            for (; l < layersCount;) {
              const packet = createPacket(resolution, k, l);
              l++;
              return packet;
            }
            l = 0;
          }
          r = 0;
        }
        c = 0;
      }
      px = 0;
    }
    throw new JpxError("Out of packets");
  };
}
function ComponentPositionResolutionLayerIterator(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const layersCount = tile.codingStyleDefaultParameters.layersCount;
  const componentsCount = siz.Csiz;
  const precinctsSizes = getPrecinctSizesInImageScale(tile);
  let l = 0,
    r = 0,
    c = 0,
    px = 0,
    py = 0;
  this.nextPacket = function JpxImage_nextPacket() {
    for (; c < componentsCount; ++c) {
      const component = tile.components[c];
      const precinctsIterationSizes = precinctsSizes.components[c];
      const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
      for (; py < precinctsIterationSizes.maxNumHigh; py++) {
        for (; px < precinctsIterationSizes.maxNumWide; px++) {
          for (; r <= decompositionLevelsCount; r++) {
            const resolution = component.resolutions[r];
            const sizeInImageScale = precinctsIterationSizes.resolutions[r];
            const k = getPrecinctIndexIfExist(px, py, sizeInImageScale, precinctsIterationSizes, resolution);
            if (k === null) {
              continue;
            }
            for (; l < layersCount;) {
              const packet = createPacket(resolution, k, l);
              l++;
              return packet;
            }
            l = 0;
          }
          r = 0;
        }
        px = 0;
      }
      py = 0;
    }
    throw new JpxError("Out of packets");
  };
}
function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
  const posX = pxIndex * precinctIterationSizes.minWidth;
  const posY = pyIndex * precinctIterationSizes.minHeight;
  if (posX % sizeInImageScale.width !== 0 || posY % sizeInImageScale.height !== 0) {
    return null;
  }
  const startPrecinctRowIndex = posY / sizeInImageScale.width * resolution.precinctParameters.numprecinctswide;
  return posX / sizeInImageScale.height + startPrecinctRowIndex;
}
function getPrecinctSizesInImageScale(tile) {
  const componentsCount = tile.components.length;
  let minWidth = Number.MAX_VALUE;
  let minHeight = Number.MAX_VALUE;
  let maxNumWide = 0;
  let maxNumHigh = 0;
  const sizePerComponent = new Array(componentsCount);
  for (let c = 0; c < componentsCount; c++) {
    const component = tile.components[c];
    const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
    const sizePerResolution = new Array(decompositionLevelsCount + 1);
    let minWidthCurrentComponent = Number.MAX_VALUE;
    let minHeightCurrentComponent = Number.MAX_VALUE;
    let maxNumWideCurrentComponent = 0;
    let maxNumHighCurrentComponent = 0;
    let scale = 1;
    for (let r = decompositionLevelsCount; r >= 0; --r) {
      const resolution = component.resolutions[r];
      const widthCurrentResolution = scale * resolution.precinctParameters.precinctWidth;
      const heightCurrentResolution = scale * resolution.precinctParameters.precinctHeight;
      minWidthCurrentComponent = Math.min(minWidthCurrentComponent, widthCurrentResolution);
      minHeightCurrentComponent = Math.min(minHeightCurrentComponent, heightCurrentResolution);
      maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent, resolution.precinctParameters.numprecinctswide);
      maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent, resolution.precinctParameters.numprecinctshigh);
      sizePerResolution[r] = {
        width: widthCurrentResolution,
        height: heightCurrentResolution
      };
      scale <<= 1;
    }
    minWidth = Math.min(minWidth, minWidthCurrentComponent);
    minHeight = Math.min(minHeight, minHeightCurrentComponent);
    maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
    maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
    sizePerComponent[c] = {
      resolutions: sizePerResolution,
      minWidth: minWidthCurrentComponent,
      minHeight: minHeightCurrentComponent,
      maxNumWide: maxNumWideCurrentComponent,
      maxNumHigh: maxNumHighCurrentComponent
    };
  }
  return {
    components: sizePerComponent,
    minWidth,
    minHeight,
    maxNumWide,
    maxNumHigh
  };
}
function buildPackets(context) {
  const siz = context.SIZ;
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const componentsCount = siz.Csiz;
  for (let c = 0; c < componentsCount; c++) {
    const component = tile.components[c];
    const decompositionLevelsCount = component.codingStyleParameters.decompositionLevelsCount;
    const resolutions = [];
    const subbands = [];
    for (let r = 0; r <= decompositionLevelsCount; r++) {
      const blocksDimensions = getBlocksDimensions(context, component, r);
      const resolution = {};
      const scale = 1 << decompositionLevelsCount - r;
      resolution.trx0 = Math.ceil(component.tcx0 / scale);
      resolution.try0 = Math.ceil(component.tcy0 / scale);
      resolution.trx1 = Math.ceil(component.tcx1 / scale);
      resolution.try1 = Math.ceil(component.tcy1 / scale);
      resolution.resLevel = r;
      buildPrecincts(context, resolution, blocksDimensions);
      resolutions.push(resolution);
      let subband;
      if (r === 0) {
        subband = {};
        subband.type = "LL";
        subband.tbx0 = Math.ceil(component.tcx0 / scale);
        subband.tby0 = Math.ceil(component.tcy0 / scale);
        subband.tbx1 = Math.ceil(component.tcx1 / scale);
        subband.tby1 = Math.ceil(component.tcy1 / scale);
        subband.resolution = resolution;
        buildCodeblocks(context, subband, blocksDimensions);
        subbands.push(subband);
        resolution.subbands = [subband];
      } else {
        const bscale = 1 << decompositionLevelsCount - r + 1;
        const resolutionSubbands = [];
        subband = {};
        subband.type = "HL";
        subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
        subband.tby0 = Math.ceil(component.tcy0 / bscale);
        subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
        subband.tby1 = Math.ceil(component.tcy1 / bscale);
        subband.resolution = resolution;
        buildCodeblocks(context, subband, blocksDimensions);
        subbands.push(subband);
        resolutionSubbands.push(subband);
        subband = {};
        subband.type = "LH";
        subband.tbx0 = Math.ceil(component.tcx0 / bscale);
        subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
        subband.tbx1 = Math.ceil(component.tcx1 / bscale);
        subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
        subband.resolution = resolution;
        buildCodeblocks(context, subband, blocksDimensions);
        subbands.push(subband);
        resolutionSubbands.push(subband);
        subband = {};
        subband.type = "HH";
        subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
        subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
        subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
        subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
        subband.resolution = resolution;
        buildCodeblocks(context, subband, blocksDimensions);
        subbands.push(subband);
        resolutionSubbands.push(subband);
        resolution.subbands = resolutionSubbands;
      }
    }
    component.resolutions = resolutions;
    component.subbands = subbands;
  }
  const progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
  switch (progressionOrder) {
    case 0:
      tile.packetsIterator = new LayerResolutionComponentPositionIterator(context);
      break;
    case 1:
      tile.packetsIterator = new ResolutionLayerComponentPositionIterator(context);
      break;
    case 2:
      tile.packetsIterator = new ResolutionPositionComponentLayerIterator(context);
      break;
    case 3:
      tile.packetsIterator = new PositionComponentResolutionLayerIterator(context);
      break;
    case 4:
      tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
      break;
    default:
      throw new JpxError(`Unsupported progression order ${progressionOrder}`);
  }
}
function parseTilePackets(context, data, offset, dataLength) {
  let position = 0;
  let buffer,
    bufferSize = 0,
    skipNextBit = false;
  function readBits(count) {
    while (bufferSize < count) {
      const b = data[offset + position];
      position++;
      if (skipNextBit) {
        buffer = buffer << 7 | b;
        bufferSize += 7;
        skipNextBit = false;
      } else {
        buffer = buffer << 8 | b;
        bufferSize += 8;
      }
      if (b === 0xff) {
        skipNextBit = true;
      }
    }
    bufferSize -= count;
    return buffer >>> bufferSize & (1 << count) - 1;
  }
  function skipMarkerIfEqual(value) {
    if (data[offset + position - 1] === 0xff && data[offset + position] === value) {
      skipBytes(1);
      return true;
    } else if (data[offset + position] === 0xff && data[offset + position + 1] === value) {
      skipBytes(2);
      return true;
    }
    return false;
  }
  function skipBytes(count) {
    position += count;
  }
  function alignToByte() {
    bufferSize = 0;
    if (skipNextBit) {
      position++;
      skipNextBit = false;
    }
  }
  function readCodingpasses() {
    if (readBits(1) === 0) {
      return 1;
    }
    if (readBits(1) === 0) {
      return 2;
    }
    let value = readBits(2);
    if (value < 3) {
      return value + 3;
    }
    value = readBits(5);
    if (value < 31) {
      return value + 6;
    }
    value = readBits(7);
    return value + 37;
  }
  const tileIndex = context.currentTile.index;
  const tile = context.tiles[tileIndex];
  const sopMarkerUsed = context.COD.sopMarkerUsed;
  const ephMarkerUsed = context.COD.ephMarkerUsed;
  const packetsIterator = tile.packetsIterator;
  while (position < dataLength) {
    alignToByte();
    if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
      skipBytes(4);
    }
    const packet = packetsIterator.nextPacket();
    if (!readBits(1)) {
      continue;
    }
    const layerNumber = packet.layerNumber,
      queue = [];
    let codeblock;
    for (let i = 0, ii = packet.codeblocks.length; i < ii; i++) {
      codeblock = packet.codeblocks[i];
      let precinct = codeblock.precinct;
      const codeblockColumn = codeblock.cbx - precinct.cbxMin;
      const codeblockRow = codeblock.cby - precinct.cbyMin;
      let codeblockIncluded = false;
      let firstTimeInclusion = false;
      let valueReady, zeroBitPlanesTree;
      if (codeblock.included !== undefined) {
        codeblockIncluded = !!readBits(1);
      } else {
        precinct = codeblock.precinct;
        let inclusionTree;
        if (precinct.inclusionTree !== undefined) {
          inclusionTree = precinct.inclusionTree;
        } else {
          const width = precinct.cbxMax - precinct.cbxMin + 1;
          const height = precinct.cbyMax - precinct.cbyMin + 1;
          inclusionTree = new InclusionTree(width, height, layerNumber);
          zeroBitPlanesTree = new TagTree(width, height);
          precinct.inclusionTree = inclusionTree;
          precinct.zeroBitPlanesTree = zeroBitPlanesTree;
          for (let l = 0; l < layerNumber; l++) {
            if (readBits(1) !== 0) {
              throw new JpxError("Invalid tag tree");
            }
          }
        }
        if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {
          while (true) {
            if (readBits(1)) {
              valueReady = !inclusionTree.nextLevel();
              if (valueReady) {
                codeblock.included = true;
                codeblockIncluded = firstTimeInclusion = true;
                break;
              }
            } else {
              inclusionTree.incrementValue(layerNumber);
              break;
            }
          }
        }
      }
      if (!codeblockIncluded) {
        continue;
      }
      if (firstTimeInclusion) {
        zeroBitPlanesTree = precinct.zeroBitPlanesTree;
        zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
        while (true) {
          if (readBits(1)) {
            valueReady = !zeroBitPlanesTree.nextLevel();
            if (valueReady) {
              break;
            }
          } else {
            zeroBitPlanesTree.incrementValue();
          }
        }
        codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
      }
      const codingpasses = readCodingpasses();
      while (readBits(1)) {
        codeblock.Lblock++;
      }
      const codingpassesLog2 = (0, _core_utils.log2)(codingpasses);
      const bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
      const codedDataLength = readBits(bits);
      queue.push({
        codeblock,
        codingpasses,
        dataLength: codedDataLength
      });
    }
    alignToByte();
    if (ephMarkerUsed) {
      skipMarkerIfEqual(0x92);
    }
    while (queue.length > 0) {
      const packetItem = queue.shift();
      codeblock = packetItem.codeblock;
      if (codeblock.data === undefined) {
        codeblock.data = [];
      }
      codeblock.data.push({
        data,
        start: offset + position,
        end: offset + position + packetItem.dataLength,
        codingpasses: packetItem.codingpasses
      });
      position += packetItem.dataLength;
    }
  }
  return position;
}
function copyCoefficients(coefficients, levelWidth, levelHeight, subband, delta, mb, reversible, segmentationSymbolUsed, resetContextProbabilities) {
  const x0 = subband.tbx0;
  const y0 = subband.tby0;
  const width = subband.tbx1 - subband.tbx0;
  const codeblocks = subband.codeblocks;
  const right = subband.type.charAt(0) === "H" ? 1 : 0;
  const bottom = subband.type.charAt(1) === "H" ? levelWidth : 0;
  for (let i = 0, ii = codeblocks.length; i < ii; ++i) {
    const codeblock = codeblocks[i];
    const blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
    const blockHeight = codeblock.tby1_ - codeblock.tby0_;
    if (blockWidth === 0 || blockHeight === 0) {
      continue;
    }
    if (codeblock.data === undefined) {
      continue;
    }
    const bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType, codeblock.zeroBitPlanes, mb);
    let currentCodingpassType = 2;
    const data = codeblock.data;
    let totalLength = 0,
      codingpasses = 0;
    let j, jj, dataItem;
    for (j = 0, jj = data.length; j < jj; j++) {
      dataItem = data[j];
      totalLength += dataItem.end - dataItem.start;
      codingpasses += dataItem.codingpasses;
    }
    const encodedData = new Uint8Array(totalLength);
    let position = 0;
    for (j = 0, jj = data.length; j < jj; j++) {
      dataItem = data[j];
      const chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
      encodedData.set(chunk, position);
      position += chunk.length;
    }
    const decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
    bitModel.setDecoder(decoder);
    for (j = 0; j < codingpasses; j++) {
      switch (currentCodingpassType) {
        case 0:
          bitModel.runSignificancePropagationPass();
          break;
        case 1:
          bitModel.runMagnitudeRefinementPass();
          break;
        case 2:
          bitModel.runCleanupPass();
          if (segmentationSymbolUsed) {
            bitModel.checkSegmentationSymbol();
          }
          break;
      }
      if (resetContextProbabilities) {
        bitModel.reset();
      }
      currentCodingpassType = (currentCodingpassType + 1) % 3;
    }
    let offset = codeblock.tbx0_ - x0 + (codeblock.tby0_ - y0) * width;
    const sign = bitModel.coefficentsSign;
    const magnitude = bitModel.coefficentsMagnitude;
    const bitsDecoded = bitModel.bitsDecoded;
    const magnitudeCorrection = reversible ? 0 : 0.5;
    let k, n, nb;
    position = 0;
    const interleave = subband.type !== "LL";
    for (j = 0; j < blockHeight; j++) {
      const row = offset / width | 0;
      const levelOffset = 2 * row * (levelWidth - width) + right + bottom;
      for (k = 0; k < blockWidth; k++) {
        n = magnitude[position];
        if (n !== 0) {
          n = (n + magnitudeCorrection) * delta;
          if (sign[position] !== 0) {
            n = -n;
          }
          nb = bitsDecoded[position];
          const pos = interleave ? levelOffset + (offset << 1) : offset;
          if (reversible && nb >= mb) {
            coefficients[pos] = n;
          } else {
            coefficients[pos] = n * (1 << mb - nb);
          }
        }
        offset++;
        position++;
      }
      offset += width - blockWidth;
    }
  }
}
function transformTile(context, tile, c) {
  const component = tile.components[c];
  const codingStyleParameters = component.codingStyleParameters;
  const quantizationParameters = component.quantizationParameters;
  const decompositionLevelsCount = codingStyleParameters.decompositionLevelsCount;
  const spqcds = quantizationParameters.SPqcds;
  const scalarExpounded = quantizationParameters.scalarExpounded;
  const guardBits = quantizationParameters.guardBits;
  const segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
  const resetContextProbabilities = codingStyleParameters.resetContextProbabilities;
  const precision = context.components[c].precision;
  const reversible = codingStyleParameters.reversibleTransformation;
  const transform = reversible ? new ReversibleTransform() : new IrreversibleTransform();
  const subbandCoefficients = [];
  let b = 0;
  for (let i = 0; i <= decompositionLevelsCount; i++) {
    const resolution = component.resolutions[i];
    const width = resolution.trx1 - resolution.trx0;
    const height = resolution.try1 - resolution.try0;
    const coefficients = new Float32Array(width * height);
    for (let j = 0, jj = resolution.subbands.length; j < jj; j++) {
      let mu, epsilon;
      if (!scalarExpounded) {
        mu = spqcds[0].mu;
        epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
      } else {
        mu = spqcds[b].mu;
        epsilon = spqcds[b].epsilon;
        b++;
      }
      const subband = resolution.subbands[j];
      const gainLog2 = SubbandsGainLog2[subband.type];
      const delta = reversible ? 1 : 2 ** (precision + gainLog2 - epsilon) * (1 + mu / 2048);
      const mb = guardBits + epsilon - 1;
      copyCoefficients(coefficients, width, height, subband, delta, mb, reversible, segmentationSymbolUsed, resetContextProbabilities);
    }
    subbandCoefficients.push({
      width,
      height,
      items: coefficients
    });
  }
  const result = transform.calculate(subbandCoefficients, component.tcx0, component.tcy0);
  return {
    left: component.tcx0,
    top: component.tcy0,
    width: result.width,
    height: result.height,
    items: result.items
  };
}
function transformComponents(context) {
  const siz = context.SIZ;
  const components = context.components;
  const componentsCount = siz.Csiz;
  const resultImages = [];
  for (let i = 0, ii = context.tiles.length; i < ii; i++) {
    const tile = context.tiles[i];
    const transformedTiles = [];
    for (let c = 0; c < componentsCount; c++) {
      transformedTiles[c] = transformTile(context, tile, c);
    }
    const tile0 = transformedTiles[0];
    const out = new Uint8ClampedArray(tile0.items.length * componentsCount);
    const result = {
      left: tile0.left,
      top: tile0.top,
      width: tile0.width,
      height: tile0.height,
      items: out
    };
    let shift, offset;
    let pos = 0,
      j,
      jj,
      y0,
      y1,
      y2;
    if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
      const fourComponents = componentsCount === 4;
      const y0items = transformedTiles[0].items;
      const y1items = transformedTiles[1].items;
      const y2items = transformedTiles[2].items;
      const y3items = fourComponents ? transformedTiles[3].items : null;
      shift = components[0].precision - 8;
      offset = (128 << shift) + 0.5;
      const component0 = tile.components[0];
      const alpha01 = componentsCount - 3;
      jj = y0items.length;
      if (!component0.codingStyleParameters.reversibleTransformation) {
        for (j = 0; j < jj; j++, pos += alpha01) {
          y0 = y0items[j] + offset;
          y1 = y1items[j];
          y2 = y2items[j];
          out[pos++] = y0 + 1.402 * y2 >> shift;
          out[pos++] = y0 - 0.34413 * y1 - 0.71414 * y2 >> shift;
          out[pos++] = y0 + 1.772 * y1 >> shift;
        }
      } else {
        for (j = 0; j < jj; j++, pos += alpha01) {
          y0 = y0items[j] + offset;
          y1 = y1items[j];
          y2 = y2items[j];
          const g = y0 - (y2 + y1 >> 2);
          out[pos++] = g + y2 >> shift;
          out[pos++] = g >> shift;
          out[pos++] = g + y1 >> shift;
        }
      }
      if (fourComponents) {
        for (j = 0, pos = 3; j < jj; j++, pos += 4) {
          out[pos] = y3items[j] + offset >> shift;
        }
      }
    } else {
      for (let c = 0; c < componentsCount; c++) {
        const items = transformedTiles[c].items;
        shift = components[c].precision - 8;
        offset = (128 << shift) + 0.5;
        for (pos = c, j = 0, jj = items.length; j < jj; j++) {
          out[pos] = items[j] + offset >> shift;
          pos += componentsCount;
        }
      }
    }
    resultImages.push(result);
  }
  return resultImages;
}
function initializeTile(context, tileIndex) {
  const siz = context.SIZ;
  const componentsCount = siz.Csiz;
  const tile = context.tiles[tileIndex];
  for (let c = 0; c < componentsCount; c++) {
    const component = tile.components[c];
    const qcdOrQcc = context.currentTile.QCC[c] !== undefined ? context.currentTile.QCC[c] : context.currentTile.QCD;
    component.quantizationParameters = qcdOrQcc;
    const codOrCoc = context.currentTile.COC[c] !== undefined ? context.currentTile.COC[c] : context.currentTile.COD;
    component.codingStyleParameters = codOrCoc;
  }
  tile.codingStyleDefaultParameters = context.currentTile.COD;
}
class TagTree {
  constructor(width, height) {
    const levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
    this.levels = [];
    for (let i = 0; i < levelsLength; i++) {
      const level = {
        width,
        height,
        items: []
      };
      this.levels.push(level);
      width = Math.ceil(width / 2);
      height = Math.ceil(height / 2);
    }
  }
  reset(i, j) {
    let currentLevel = 0,
      value = 0,
      level;
    while (currentLevel < this.levels.length) {
      level = this.levels[currentLevel];
      const index = i + j * level.width;
      if (level.items[index] !== undefined) {
        value = level.items[index];
        break;
      }
      level.index = index;
      i >>= 1;
      j >>= 1;
      currentLevel++;
    }
    currentLevel--;
    level = this.levels[currentLevel];
    level.items[level.index] = value;
    this.currentLevel = currentLevel;
    delete this.value;
  }
  incrementValue() {
    const level = this.levels[this.currentLevel];
    level.items[level.index]++;
  }
  nextLevel() {
    let currentLevel = this.currentLevel;
    let level = this.levels[currentLevel];
    const value = level.items[level.index];
    currentLevel--;
    if (currentLevel < 0) {
      this.value = value;
      return false;
    }
    this.currentLevel = currentLevel;
    level = this.levels[currentLevel];
    level.items[level.index] = value;
    return true;
  }
}
class InclusionTree {
  constructor(width, height, defaultValue) {
    const levelsLength = (0, _core_utils.log2)(Math.max(width, height)) + 1;
    this.levels = [];
    for (let i = 0; i < levelsLength; i++) {
      const items = new Uint8Array(width * height);
      for (let j = 0, jj = items.length; j < jj; j++) {
        items[j] = defaultValue;
      }
      const level = {
        width,
        height,
        items
      };
      this.levels.push(level);
      width = Math.ceil(width / 2);
      height = Math.ceil(height / 2);
    }
  }
  reset(i, j, stopValue) {
    let currentLevel = 0;
    while (currentLevel < this.levels.length) {
      const level = this.levels[currentLevel];
      const index = i + j * level.width;
      level.index = index;
      const value = level.items[index];
      if (value === 0xff) {
        break;
      }
      if (value > stopValue) {
        this.currentLevel = currentLevel;
        this.propagateValues();
        return false;
      }
      i >>= 1;
      j >>= 1;
      currentLevel++;
    }
    this.currentLevel = currentLevel - 1;
    return true;
  }
  incrementValue(stopValue) {
    const level = this.levels[this.currentLevel];
    level.items[level.index] = stopValue + 1;
    this.propagateValues();
  }
  propagateValues() {
    let levelIndex = this.currentLevel;
    let level = this.levels[levelIndex];
    const currentValue = level.items[level.index];
    while (--levelIndex >= 0) {
      level = this.levels[levelIndex];
      level.items[level.index] = currentValue;
    }
  }
  nextLevel() {
    let currentLevel = this.currentLevel;
    let level = this.levels[currentLevel];
    const value = level.items[level.index];
    level.items[level.index] = 0xff;
    currentLevel--;
    if (currentLevel < 0) {
      return false;
    }
    this.currentLevel = currentLevel;
    level = this.levels[currentLevel];
    level.items[level.index] = value;
    return true;
  }
}
const BitModel = function BitModelClosure() {
  const UNIFORM_CONTEXT = 17;
  const RUNLENGTH_CONTEXT = 18;
  const LLAndLHContextsLabel = new Uint8Array([0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8]);
  const HLContextLabel = new Uint8Array([0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8]);
  const HHContextLabel = new Uint8Array([0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5, 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8]);
  class BitModel {
    constructor(width, height, subband, zeroBitPlanes, mb) {
      this.width = width;
      this.height = height;
      let contextLabelTable;
      if (subband === "HH") {
        contextLabelTable = HHContextLabel;
      } else if (subband === "HL") {
        contextLabelTable = HLContextLabel;
      } else {
        contextLabelTable = LLAndLHContextsLabel;
      }
      this.contextLabelTable = contextLabelTable;
      const coefficientCount = width * height;
      this.neighborsSignificance = new Uint8Array(coefficientCount);
      this.coefficentsSign = new Uint8Array(coefficientCount);
      let coefficentsMagnitude;
      if (mb > 14) {
        coefficentsMagnitude = new Uint32Array(coefficientCount);
      } else if (mb > 6) {
        coefficentsMagnitude = new Uint16Array(coefficientCount);
      } else {
        coefficentsMagnitude = new Uint8Array(coefficientCount);
      }
      this.coefficentsMagnitude = coefficentsMagnitude;
      this.processingFlags = new Uint8Array(coefficientCount);
      const bitsDecoded = new Uint8Array(coefficientCount);
      if (zeroBitPlanes !== 0) {
        for (let i = 0; i < coefficientCount; i++) {
          bitsDecoded[i] = zeroBitPlanes;
        }
      }
      this.bitsDecoded = bitsDecoded;
      this.reset();
    }
    setDecoder(decoder) {
      this.decoder = decoder;
    }
    reset() {
      this.contexts = new Int8Array(19);
      this.contexts[0] = 4 << 1 | 0;
      this.contexts[UNIFORM_CONTEXT] = 46 << 1 | 0;
      this.contexts[RUNLENGTH_CONTEXT] = 3 << 1 | 0;
    }
    setNeighborsSignificance(row, column, index) {
      const neighborsSignificance = this.neighborsSignificance;
      const width = this.width,
        height = this.height;
      const left = column > 0;
      const right = column + 1 < width;
      let i;
      if (row > 0) {
        i = index - width;
        if (left) {
          neighborsSignificance[i - 1] += 0x10;
        }
        if (right) {
          neighborsSignificance[i + 1] += 0x10;
        }
        neighborsSignificance[i] += 0x04;
      }
      if (row + 1 < height) {
        i = index + width;
        if (left) {
          neighborsSignificance[i - 1] += 0x10;
        }
        if (right) {
          neighborsSignificance[i + 1] += 0x10;
        }
        neighborsSignificance[i] += 0x04;
      }
      if (left) {
        neighborsSignificance[index - 1] += 0x01;
      }
      if (right) {
        neighborsSignificance[index + 1] += 0x01;
      }
      neighborsSignificance[index] |= 0x80;
    }
    runSignificancePropagationPass() {
      const decoder = this.decoder;
      const width = this.width,
        height = this.height;
      const coefficentsMagnitude = this.coefficentsMagnitude;
      const coefficentsSign = this.coefficentsSign;
      const neighborsSignificance = this.neighborsSignificance;
      const processingFlags = this.processingFlags;
      const contexts = this.contexts;
      const labels = this.contextLabelTable;
      const bitsDecoded = this.bitsDecoded;
      const processedInverseMask = ~1;
      const processedMask = 1;
      const firstMagnitudeBitMask = 2;
      for (let i0 = 0; i0 < height; i0 += 4) {
        for (let j = 0; j < width; j++) {
          let index = i0 * width + j;
          for (let i1 = 0; i1 < 4; i1++, index += width) {
            const i = i0 + i1;
            if (i >= height) {
              break;
            }
            processingFlags[index] &= processedInverseMask;
            if (coefficentsMagnitude[index] || !neighborsSignificance[index]) {
              continue;
            }
            const contextLabel = labels[neighborsSignificance[index]];
            const decision = decoder.readBit(contexts, contextLabel);
            if (decision) {
              const sign = this.decodeSignBit(i, j, index);
              coefficentsSign[index] = sign;
              coefficentsMagnitude[index] = 1;
              this.setNeighborsSignificance(i, j, index);
              processingFlags[index] |= firstMagnitudeBitMask;
            }
            bitsDecoded[index]++;
            processingFlags[index] |= processedMask;
          }
        }
      }
    }
    decodeSignBit(row, column, index) {
      const width = this.width,
        height = this.height;
      const coefficentsMagnitude = this.coefficentsMagnitude;
      const coefficentsSign = this.coefficentsSign;
      let contribution, sign0, sign1, significance1;
      let contextLabel, decoded;
      significance1 = column > 0 && coefficentsMagnitude[index - 1] !== 0;
      if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
        sign1 = coefficentsSign[index + 1];
        if (significance1) {
          sign0 = coefficentsSign[index - 1];
          contribution = 1 - sign1 - sign0;
        } else {
          contribution = 1 - sign1 - sign1;
        }
      } else if (significance1) {
        sign0 = coefficentsSign[index - 1];
        contribution = 1 - sign0 - sign0;
      } else {
        contribution = 0;
      }
      const horizontalContribution = 3 * contribution;
      significance1 = row > 0 && coefficentsMagnitude[index - width] !== 0;
      if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
        sign1 = coefficentsSign[index + width];
        if (significance1) {
          sign0 = coefficentsSign[index - width];
          contribution = 1 - sign1 - sign0 + horizontalContribution;
        } else {
          contribution = 1 - sign1 - sign1 + horizontalContribution;
        }
      } else if (significance1) {
        sign0 = coefficentsSign[index - width];
        contribution = 1 - sign0 - sign0 + horizontalContribution;
      } else {
        contribution = horizontalContribution;
      }
      if (contribution >= 0) {
        contextLabel = 9 + contribution;
        decoded = this.decoder.readBit(this.contexts, contextLabel);
      } else {
        contextLabel = 9 - contribution;
        decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
      }
      return decoded;
    }
    runMagnitudeRefinementPass() {
      const decoder = this.decoder;
      const width = this.width,
        height = this.height;
      const coefficentsMagnitude = this.coefficentsMagnitude;
      const neighborsSignificance = this.neighborsSignificance;
      const contexts = this.contexts;
      const bitsDecoded = this.bitsDecoded;
      const processingFlags = this.processingFlags;
      const processedMask = 1;
      const firstMagnitudeBitMask = 2;
      const length = width * height;
      const width4 = width * 4;
      for (let index0 = 0, indexNext; index0 < length; index0 = indexNext) {
        indexNext = Math.min(length, index0 + width4);
        for (let j = 0; j < width; j++) {
          for (let index = index0 + j; index < indexNext; index += width) {
            if (!coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
              continue;
            }
            let contextLabel = 16;
            if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
              processingFlags[index] ^= firstMagnitudeBitMask;
              const significance = neighborsSignificance[index] & 127;
              contextLabel = significance === 0 ? 15 : 14;
            }
            const bit = decoder.readBit(contexts, contextLabel);
            coefficentsMagnitude[index] = coefficentsMagnitude[index] << 1 | bit;
            bitsDecoded[index]++;
            processingFlags[index] |= processedMask;
          }
        }
      }
    }
    runCleanupPass() {
      const decoder = this.decoder;
      const width = this.width,
        height = this.height;
      const neighborsSignificance = this.neighborsSignificance;
      const coefficentsMagnitude = this.coefficentsMagnitude;
      const coefficentsSign = this.coefficentsSign;
      const contexts = this.contexts;
      const labels = this.contextLabelTable;
      const bitsDecoded = this.bitsDecoded;
      const processingFlags = this.processingFlags;
      const processedMask = 1;
      const firstMagnitudeBitMask = 2;
      const oneRowDown = width;
      const twoRowsDown = width * 2;
      const threeRowsDown = width * 3;
      let iNext;
      for (let i0 = 0; i0 < height; i0 = iNext) {
        iNext = Math.min(i0 + 4, height);
        const indexBase = i0 * width;
        const checkAllEmpty = i0 + 3 < height;
        for (let j = 0; j < width; j++) {
          const index0 = indexBase + j;
          const allEmpty = checkAllEmpty && processingFlags[index0] === 0 && processingFlags[index0 + oneRowDown] === 0 && processingFlags[index0 + twoRowsDown] === 0 && processingFlags[index0 + threeRowsDown] === 0 && neighborsSignificance[index0] === 0 && neighborsSignificance[index0 + oneRowDown] === 0 && neighborsSignificance[index0 + twoRowsDown] === 0 && neighborsSignificance[index0 + threeRowsDown] === 0;
          let i1 = 0,
            index = index0;
          let i = i0,
            sign;
          if (allEmpty) {
            const hasSignificantCoefficent = decoder.readBit(contexts, RUNLENGTH_CONTEXT);
            if (!hasSignificantCoefficent) {
              bitsDecoded[index0]++;
              bitsDecoded[index0 + oneRowDown]++;
              bitsDecoded[index0 + twoRowsDown]++;
              bitsDecoded[index0 + threeRowsDown]++;
              continue;
            }
            i1 = decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
            if (i1 !== 0) {
              i = i0 + i1;
              index += i1 * width;
            }
            sign = this.decodeSignBit(i, j, index);
            coefficentsSign[index] = sign;
            coefficentsMagnitude[index] = 1;
            this.setNeighborsSignificance(i, j, index);
            processingFlags[index] |= firstMagnitudeBitMask;
            index = index0;
            for (let i2 = i0; i2 <= i; i2++, index += width) {
              bitsDecoded[index]++;
            }
            i1++;
          }
          for (i = i0 + i1; i < iNext; i++, index += width) {
            if (coefficentsMagnitude[index] || (processingFlags[index] & processedMask) !== 0) {
              continue;
            }
            const contextLabel = labels[neighborsSignificance[index]];
            const decision = decoder.readBit(contexts, contextLabel);
            if (decision === 1) {
              sign = this.decodeSignBit(i, j, index);
              coefficentsSign[index] = sign;
              coefficentsMagnitude[index] = 1;
              this.setNeighborsSignificance(i, j, index);
              processingFlags[index] |= firstMagnitudeBitMask;
            }
            bitsDecoded[index]++;
          }
        }
      }
    }
    checkSegmentationSymbol() {
      const decoder = this.decoder;
      const contexts = this.contexts;
      const symbol = decoder.readBit(contexts, UNIFORM_CONTEXT) << 3 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 2 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
      if (symbol !== 0xa) {
        throw new JpxError("Invalid segmentation symbol");
      }
    }
  }
  return BitModel;
}();
class Transform {
  constructor() {
    if (this.constructor === Transform) {
      (0, _util.unreachable)("Cannot initialize Transform.");
    }
  }
  calculate(subbands, u0, v0) {
    let ll = subbands[0];
    for (let i = 1, ii = subbands.length; i < ii; i++) {
      ll = this.iterate(ll, subbands[i], u0, v0);
    }
    return ll;
  }
  extend(buffer, offset, size) {
    let i1 = offset - 1,
      j1 = offset + 1;
    let i2 = offset + size - 2,
      j2 = offset + size;
    buffer[i1--] = buffer[j1++];
    buffer[j2++] = buffer[i2--];
    buffer[i1--] = buffer[j1++];
    buffer[j2++] = buffer[i2--];
    buffer[i1--] = buffer[j1++];
    buffer[j2++] = buffer[i2--];
    buffer[i1] = buffer[j1];
    buffer[j2] = buffer[i2];
  }
  filter(x, offset, length) {
    (0, _util.unreachable)("Abstract method `filter` called");
  }
  iterate(ll, hl_lh_hh, u0, v0) {
    const llWidth = ll.width,
      llHeight = ll.height;
    let llItems = ll.items;
    const width = hl_lh_hh.width;
    const height = hl_lh_hh.height;
    const items = hl_lh_hh.items;
    let i, j, k, l, u, v;
    for (k = 0, i = 0; i < llHeight; i++) {
      l = i * 2 * width;
      for (j = 0; j < llWidth; j++, k++, l += 2) {
        items[l] = llItems[k];
      }
    }
    llItems = ll.items = null;
    const bufferPadding = 4;
    const rowBuffer = new Float32Array(width + 2 * bufferPadding);
    if (width === 1) {
      if ((u0 & 1) !== 0) {
        for (v = 0, k = 0; v < height; v++, k += width) {
          items[k] *= 0.5;
        }
      }
    } else {
      for (v = 0, k = 0; v < height; v++, k += width) {
        rowBuffer.set(items.subarray(k, k + width), bufferPadding);
        this.extend(rowBuffer, bufferPadding, width);
        this.filter(rowBuffer, bufferPadding, width);
        items.set(rowBuffer.subarray(bufferPadding, bufferPadding + width), k);
      }
    }
    let numBuffers = 16;
    const colBuffers = [];
    for (i = 0; i < numBuffers; i++) {
      colBuffers.push(new Float32Array(height + 2 * bufferPadding));
    }
    let b,
      currentBuffer = 0;
    ll = bufferPadding + height;
    if (height === 1) {
      if ((v0 & 1) !== 0) {
        for (u = 0; u < width; u++) {
          items[u] *= 0.5;
        }
      }
    } else {
      for (u = 0; u < width; u++) {
        if (currentBuffer === 0) {
          numBuffers = Math.min(width - u, numBuffers);
          for (k = u, l = bufferPadding; l < ll; k += width, l++) {
            for (b = 0; b < numBuffers; b++) {
              colBuffers[b][l] = items[k + b];
            }
          }
          currentBuffer = numBuffers;
        }
        currentBuffer--;
        const buffer = colBuffers[currentBuffer];
        this.extend(buffer, bufferPadding, height);
        this.filter(buffer, bufferPadding, height);
        if (currentBuffer === 0) {
          k = u - numBuffers + 1;
          for (l = bufferPadding; l < ll; k += width, l++) {
            for (b = 0; b < numBuffers; b++) {
              items[k + b] = colBuffers[b][l];
            }
          }
        }
      }
    }
    return {
      width,
      height,
      items
    };
  }
}
class IrreversibleTransform extends Transform {
  filter(x, offset, length) {
    const len = length >> 1;
    offset |= 0;
    let j, n, current, next;
    const alpha = -1.586134342059924;
    const beta = -0.052980118572961;
    const gamma = 0.882911075530934;
    const delta = 0.443506852043971;
    const K = 1.230174104914001;
    const K_ = 1 / K;
    j = offset - 3;
    for (n = len + 4; n--; j += 2) {
      x[j] *= K_;
    }
    j = offset - 2;
    current = delta * x[j - 1];
    for (n = len + 3; n--; j += 2) {
      next = delta * x[j + 1];
      x[j] = K * x[j] - current - next;
      if (n--) {
        j += 2;
        current = delta * x[j + 1];
        x[j] = K * x[j] - current - next;
      } else {
        break;
      }
    }
    j = offset - 1;
    current = gamma * x[j - 1];
    for (n = len + 2; n--; j += 2) {
      next = gamma * x[j + 1];
      x[j] -= current + next;
      if (n--) {
        j += 2;
        current = gamma * x[j + 1];
        x[j] -= current + next;
      } else {
        break;
      }
    }
    j = offset;
    current = beta * x[j - 1];
    for (n = len + 1; n--; j += 2) {
      next = beta * x[j + 1];
      x[j] -= current + next;
      if (n--) {
        j += 2;
        current = beta * x[j + 1];
        x[j] -= current + next;
      } else {
        break;
      }
    }
    if (len !== 0) {
      j = offset + 1;
      current = alpha * x[j - 1];
      for (n = len; n--; j += 2) {
        next = alpha * x[j + 1];
        x[j] -= current + next;
        if (n--) {
          j += 2;
          current = alpha * x[j + 1];
          x[j] -= current + next;
        } else {
          break;
        }
      }
    }
  }
}
class ReversibleTransform extends Transform {
  filter(x, offset, length) {
    const len = length >> 1;
    offset |= 0;
    let j, n;
    for (j = offset, n = len + 1; n--; j += 2) {
      x[j] -= x[j - 1] + x[j + 1] + 2 >> 2;
    }
    for (j = offset + 1, n = len; n--; j += 2) {
      x[j] += x[j - 1] + x[j + 1] >> 1;
    }
  }
}

/***/ }),
/* 29 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.LZWStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
class LZWStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength, earlyChange) {
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    this.cachedData = 0;
    this.bitsCached = 0;
    const maxLzwDictionarySize = 4096;
    const lzwState = {
      earlyChange,
      codeLength: 9,
      nextCode: 258,
      dictionaryValues: new Uint8Array(maxLzwDictionarySize),
      dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
      dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
      currentSequence: new Uint8Array(maxLzwDictionarySize),
      currentSequenceLength: 0
    };
    for (let i = 0; i < 256; ++i) {
      lzwState.dictionaryValues[i] = i;
      lzwState.dictionaryLengths[i] = 1;
    }
    this.lzwState = lzwState;
  }
  readBits(n) {
    let bitsCached = this.bitsCached;
    let cachedData = this.cachedData;
    while (bitsCached < n) {
      const c = this.str.getByte();
      if (c === -1) {
        this.eof = true;
        return null;
      }
      cachedData = cachedData << 8 | c;
      bitsCached += 8;
    }
    this.bitsCached = bitsCached -= n;
    this.cachedData = cachedData;
    this.lastCode = null;
    return cachedData >>> bitsCached & (1 << n) - 1;
  }
  readBlock() {
    const blockSize = 512,
      decodedSizeDelta = blockSize;
    let estimatedDecodedSize = blockSize * 2;
    let i, j, q;
    const lzwState = this.lzwState;
    if (!lzwState) {
      return;
    }
    const earlyChange = lzwState.earlyChange;
    let nextCode = lzwState.nextCode;
    const dictionaryValues = lzwState.dictionaryValues;
    const dictionaryLengths = lzwState.dictionaryLengths;
    const dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
    let codeLength = lzwState.codeLength;
    let prevCode = lzwState.prevCode;
    const currentSequence = lzwState.currentSequence;
    let currentSequenceLength = lzwState.currentSequenceLength;
    let decodedLength = 0;
    let currentBufferLength = this.bufferLength;
    let buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
    for (i = 0; i < blockSize; i++) {
      const code = this.readBits(codeLength);
      const hasPrev = currentSequenceLength > 0;
      if (code < 256) {
        currentSequence[0] = code;
        currentSequenceLength = 1;
      } else if (code >= 258) {
        if (code < nextCode) {
          currentSequenceLength = dictionaryLengths[code];
          for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
            currentSequence[j] = dictionaryValues[q];
            q = dictionaryPrevCodes[q];
          }
        } else {
          currentSequence[currentSequenceLength++] = currentSequence[0];
        }
      } else if (code === 256) {
        codeLength = 9;
        nextCode = 258;
        currentSequenceLength = 0;
        continue;
      } else {
        this.eof = true;
        delete this.lzwState;
        break;
      }
      if (hasPrev) {
        dictionaryPrevCodes[nextCode] = prevCode;
        dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
        dictionaryValues[nextCode] = currentSequence[0];
        nextCode++;
        codeLength = nextCode + earlyChange & nextCode + earlyChange - 1 ? codeLength : Math.min(Math.log(nextCode + earlyChange) / 0.6931471805599453 + 1, 12) | 0;
      }
      prevCode = code;
      decodedLength += currentSequenceLength;
      if (estimatedDecodedSize < decodedLength) {
        do {
          estimatedDecodedSize += decodedSizeDelta;
        } while (estimatedDecodedSize < decodedLength);
        buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
      }
      for (j = 0; j < currentSequenceLength; j++) {
        buffer[currentBufferLength++] = currentSequence[j];
      }
    }
    lzwState.nextCode = nextCode;
    lzwState.codeLength = codeLength;
    lzwState.prevCode = prevCode;
    lzwState.currentSequenceLength = currentSequenceLength;
    this.bufferLength = currentBufferLength;
  }
}
exports.LZWStream = LZWStream;

/***/ }),
/* 30 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PredictorStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
var _primitives = __w_pdfjs_require__(3);
var _util = __w_pdfjs_require__(2);
class PredictorStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength, params) {
    super(maybeLength);
    if (!(params instanceof _primitives.Dict)) {
      return str;
    }
    const predictor = this.predictor = params.get("Predictor") || 1;
    if (predictor <= 1) {
      return str;
    }
    if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
      throw new _util.FormatError(`Unsupported predictor: ${predictor}`);
    }
    if (predictor === 2) {
      this.readBlock = this.readBlockTiff;
    } else {
      this.readBlock = this.readBlockPng;
    }
    this.str = str;
    this.dict = str.dict;
    const colors = this.colors = params.get("Colors") || 1;
    const bits = this.bits = params.get("BPC", "BitsPerComponent") || 8;
    const columns = this.columns = params.get("Columns") || 1;
    this.pixBytes = colors * bits + 7 >> 3;
    this.rowBytes = columns * colors * bits + 7 >> 3;
    return this;
  }
  readBlockTiff() {
    const rowBytes = this.rowBytes;
    const bufferLength = this.bufferLength;
    const buffer = this.ensureBuffer(bufferLength + rowBytes);
    const bits = this.bits;
    const colors = this.colors;
    const rawBytes = this.str.getBytes(rowBytes);
    this.eof = !rawBytes.length;
    if (this.eof) {
      return;
    }
    let inbuf = 0,
      outbuf = 0;
    let inbits = 0,
      outbits = 0;
    let pos = bufferLength;
    let i;
    if (bits === 1 && colors === 1) {
      for (i = 0; i < rowBytes; ++i) {
        let c = rawBytes[i] ^ inbuf;
        c ^= c >> 1;
        c ^= c >> 2;
        c ^= c >> 4;
        inbuf = (c & 1) << 7;
        buffer[pos++] = c;
      }
    } else if (bits === 8) {
      for (i = 0; i < colors; ++i) {
        buffer[pos++] = rawBytes[i];
      }
      for (; i < rowBytes; ++i) {
        buffer[pos] = buffer[pos - colors] + rawBytes[i];
        pos++;
      }
    } else if (bits === 16) {
      const bytesPerPixel = colors * 2;
      for (i = 0; i < bytesPerPixel; ++i) {
        buffer[pos++] = rawBytes[i];
      }
      for (; i < rowBytes; i += 2) {
        const sum = ((rawBytes[i] & 0xff) << 8) + (rawBytes[i + 1] & 0xff) + ((buffer[pos - bytesPerPixel] & 0xff) << 8) + (buffer[pos - bytesPerPixel + 1] & 0xff);
        buffer[pos++] = sum >> 8 & 0xff;
        buffer[pos++] = sum & 0xff;
      }
    } else {
      const compArray = new Uint8Array(colors + 1);
      const bitMask = (1 << bits) - 1;
      let j = 0,
        k = bufferLength;
      const columns = this.columns;
      for (i = 0; i < columns; ++i) {
        for (let kk = 0; kk < colors; ++kk) {
          if (inbits < bits) {
            inbuf = inbuf << 8 | rawBytes[j++] & 0xff;
            inbits += 8;
          }
          compArray[kk] = compArray[kk] + (inbuf >> inbits - bits) & bitMask;
          inbits -= bits;
          outbuf = outbuf << bits | compArray[kk];
          outbits += bits;
          if (outbits >= 8) {
            buffer[k++] = outbuf >> outbits - 8 & 0xff;
            outbits -= 8;
          }
        }
      }
      if (outbits > 0) {
        buffer[k++] = (outbuf << 8 - outbits) + (inbuf & (1 << 8 - outbits) - 1);
      }
    }
    this.bufferLength += rowBytes;
  }
  readBlockPng() {
    const rowBytes = this.rowBytes;
    const pixBytes = this.pixBytes;
    const predictor = this.str.getByte();
    const rawBytes = this.str.getBytes(rowBytes);
    this.eof = !rawBytes.length;
    if (this.eof) {
      return;
    }
    const bufferLength = this.bufferLength;
    const buffer = this.ensureBuffer(bufferLength + rowBytes);
    let prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);
    if (prevRow.length === 0) {
      prevRow = new Uint8Array(rowBytes);
    }
    let i,
      j = bufferLength,
      up,
      c;
    switch (predictor) {
      case 0:
        for (i = 0; i < rowBytes; ++i) {
          buffer[j++] = rawBytes[i];
        }
        break;
      case 1:
        for (i = 0; i < pixBytes; ++i) {
          buffer[j++] = rawBytes[i];
        }
        for (; i < rowBytes; ++i) {
          buffer[j] = buffer[j - pixBytes] + rawBytes[i] & 0xff;
          j++;
        }
        break;
      case 2:
        for (i = 0; i < rowBytes; ++i) {
          buffer[j++] = prevRow[i] + rawBytes[i] & 0xff;
        }
        break;
      case 3:
        for (i = 0; i < pixBytes; ++i) {
          buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];
        }
        for (; i < rowBytes; ++i) {
          buffer[j] = (prevRow[i] + buffer[j - pixBytes] >> 1) + rawBytes[i] & 0xff;
          j++;
        }
        break;
      case 4:
        for (i = 0; i < pixBytes; ++i) {
          up = prevRow[i];
          c = rawBytes[i];
          buffer[j++] = up + c;
        }
        for (; i < rowBytes; ++i) {
          up = prevRow[i];
          const upLeft = prevRow[i - pixBytes];
          const left = buffer[j - pixBytes];
          const p = left + up - upLeft;
          let pa = p - left;
          if (pa < 0) {
            pa = -pa;
          }
          let pb = p - up;
          if (pb < 0) {
            pb = -pb;
          }
          let pc = p - upLeft;
          if (pc < 0) {
            pc = -pc;
          }
          c = rawBytes[i];
          if (pa <= pb && pa <= pc) {
            buffer[j++] = left + c;
          } else if (pb <= pc) {
            buffer[j++] = up + c;
          } else {
            buffer[j++] = upLeft + c;
          }
        }
        break;
      default:
        throw new _util.FormatError(`Unsupported predictor: ${predictor}`);
    }
    this.bufferLength += rowBytes;
  }
}
exports.PredictorStream = PredictorStream;

/***/ }),
/* 31 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.RunLengthStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
class RunLengthStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength) {
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
  }
  readBlock() {
    const repeatHeader = this.str.getBytes(2);
    if (!repeatHeader || repeatHeader.length < 2 || repeatHeader[0] === 128) {
      this.eof = true;
      return;
    }
    let buffer;
    let bufferLength = this.bufferLength;
    let n = repeatHeader[0];
    if (n < 128) {
      buffer = this.ensureBuffer(bufferLength + n + 1);
      buffer[bufferLength++] = repeatHeader[1];
      if (n > 0) {
        const source = this.str.getBytes(n);
        buffer.set(source, bufferLength);
        bufferLength += n;
      }
    } else {
      n = 257 - n;
      const b = repeatHeader[1];
      buffer = this.ensureBuffer(bufferLength + n + 1);
      for (let i = 0; i < n; i++) {
        buffer[bufferLength++] = b;
      }
    }
    this.bufferLength = bufferLength;
  }
}
exports.RunLengthStream = RunLengthStream;

/***/ }),
/* 32 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Font = exports.ErrorFont = void 0;
var _util = __w_pdfjs_require__(2);
var _cff_parser = __w_pdfjs_require__(33);
var _fonts_utils = __w_pdfjs_require__(36);
var _unicode = __w_pdfjs_require__(38);
var _glyphlist = __w_pdfjs_require__(37);
var _encodings = __w_pdfjs_require__(35);
var _standard_fonts = __w_pdfjs_require__(39);
var _to_unicode_map = __w_pdfjs_require__(40);
var _cff_font = __w_pdfjs_require__(41);
var _font_renderer = __w_pdfjs_require__(42);
var _metrics = __w_pdfjs_require__(43);
var _glyf = __w_pdfjs_require__(44);
var _cmap = __w_pdfjs_require__(14);
var _opentype_file_builder = __w_pdfjs_require__(45);
var _core_utils = __w_pdfjs_require__(4);
var _stream = __w_pdfjs_require__(8);
var _type1_font = __w_pdfjs_require__(46);
const PRIVATE_USE_AREAS = [[0xe000, 0xf8ff], [0x100000, 0x10fffd]];
const PDF_GLYPH_SPACE_UNITS = 1000;
const EXPORT_DATA_PROPERTIES = ["ascent", "bbox", "black", "bold", "charProcOperatorList", "composite", "cssFontInfo", "data", "defaultVMetrics", "defaultWidth", "descent", "fallbackName", "fontMatrix", "isInvalidPDFjsFont", "isType3Font", "italic", "loadedName", "mimetype", "missingFile", "name", "remeasure", "subtype", "type", "vertical"];
const EXPORT_DATA_EXTRA_PROPERTIES = ["cMap", "defaultEncoding", "differences", "isMonospace", "isSerifFont", "isSymbolicFont", "seacMap", "toFontChar", "toUnicode", "vmetrics", "widths"];
function adjustWidths(properties) {
  if (!properties.fontMatrix) {
    return;
  }
  if (properties.fontMatrix[0] === _util.FONT_IDENTITY_MATRIX[0]) {
    return;
  }
  const scale = 0.001 / properties.fontMatrix[0];
  const glyphsWidths = properties.widths;
  for (const glyph in glyphsWidths) {
    glyphsWidths[glyph] *= scale;
  }
  properties.defaultWidth *= scale;
}
function adjustTrueTypeToUnicode(properties, isSymbolicFont, nameRecords) {
  if (properties.isInternalFont) {
    return;
  }
  if (properties.hasIncludedToUnicodeMap) {
    return;
  }
  if (properties.hasEncoding) {
    return;
  }
  if (properties.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap) {
    return;
  }
  if (!isSymbolicFont) {
    return;
  }
  if (nameRecords.length === 0) {
    return;
  }
  if (properties.defaultEncoding === _encodings.WinAnsiEncoding) {
    return;
  }
  for (const r of nameRecords) {
    if (!isWinNameRecord(r)) {
      return;
    }
  }
  const encoding = _encodings.WinAnsiEncoding;
  const toUnicode = [],
    glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  for (const charCode in encoding) {
    const glyphName = encoding[charCode];
    if (glyphName === "") {
      continue;
    }
    const unicode = glyphsUnicodeMap[glyphName];
    if (unicode === undefined) {
      continue;
    }
    toUnicode[charCode] = String.fromCharCode(unicode);
  }
  if (toUnicode.length > 0) {
    properties.toUnicode.amend(toUnicode);
  }
}
function adjustType1ToUnicode(properties, builtInEncoding) {
  if (properties.isInternalFont) {
    return;
  }
  if (properties.hasIncludedToUnicodeMap) {
    return;
  }
  if (builtInEncoding === properties.defaultEncoding) {
    return;
  }
  if (properties.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap) {
    return;
  }
  const toUnicode = [],
    glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  for (const charCode in builtInEncoding) {
    if (properties.hasEncoding) {
      if (properties.baseEncodingName || properties.differences[charCode] !== undefined) {
        continue;
      }
    }
    const glyphName = builtInEncoding[charCode];
    const unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
    if (unicode !== -1) {
      toUnicode[charCode] = String.fromCharCode(unicode);
    }
  }
  if (toUnicode.length > 0) {
    properties.toUnicode.amend(toUnicode);
  }
}
function amendFallbackToUnicode(properties) {
  if (!properties.fallbackToUnicode) {
    return;
  }
  if (properties.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap) {
    return;
  }
  const toUnicode = [];
  for (const charCode in properties.fallbackToUnicode) {
    if (properties.toUnicode.has(charCode)) {
      continue;
    }
    toUnicode[charCode] = properties.fallbackToUnicode[charCode];
  }
  if (toUnicode.length > 0) {
    properties.toUnicode.amend(toUnicode);
  }
}
class Glyph {
  constructor(originalCharCode, fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont) {
    this.originalCharCode = originalCharCode;
    this.fontChar = fontChar;
    this.unicode = unicode;
    this.accent = accent;
    this.width = width;
    this.vmetric = vmetric;
    this.operatorListId = operatorListId;
    this.isSpace = isSpace;
    this.isInFont = isInFont;
  }
  get category() {
    return (0, _util.shadow)(this, "category", (0, _unicode.getCharUnicodeCategory)(this.unicode), true);
  }
  get normalizedUnicode() {
    return (0, _util.shadow)(this, "normalizedUnicode", (0, _unicode.reverseIfRtl)(Glyph._NormalizedUnicodes[this.unicode] || this.unicode), true);
  }
  static get _NormalizedUnicodes() {
    return (0, _util.shadow)(this, "_NormalizedUnicodes", (0, _unicode.getNormalizedUnicodes)());
  }
}
function int16(b0, b1) {
  return (b0 << 8) + b1;
}
function writeSignedInt16(bytes, index, value) {
  bytes[index + 1] = value;
  bytes[index] = value >>> 8;
}
function signedInt16(b0, b1) {
  const value = (b0 << 8) + b1;
  return value & 1 << 15 ? value - 0x10000 : value;
}
function int32(b0, b1, b2, b3) {
  return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
}
function string16(value) {
  return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
}
function safeString16(value) {
  if (value > 0x7fff) {
    value = 0x7fff;
  } else if (value < -0x8000) {
    value = -0x8000;
  }
  return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
}
function isTrueTypeFile(file) {
  const header = file.peekBytes(4);
  return (0, _core_utils.readUint32)(header, 0) === 0x00010000 || (0, _util.bytesToString)(header) === "true";
}
function isTrueTypeCollectionFile(file) {
  const header = file.peekBytes(4);
  return (0, _util.bytesToString)(header) === "ttcf";
}
function isOpenTypeFile(file) {
  const header = file.peekBytes(4);
  return (0, _util.bytesToString)(header) === "OTTO";
}
function isType1File(file) {
  const header = file.peekBytes(2);
  if (header[0] === 0x25 && header[1] === 0x21) {
    return true;
  }
  if (header[0] === 0x80 && header[1] === 0x01) {
    return true;
  }
  return false;
}
function isCFFFile(file) {
  const header = file.peekBytes(4);
  if (header[0] >= 1 && header[3] >= 1 && header[3] <= 4) {
    return true;
  }
  return false;
}
function getFontFileType(file, {
  type,
  subtype,
  composite
}) {
  let fileType, fileSubtype;
  if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) {
    if (composite) {
      fileType = "CIDFontType2";
    } else {
      fileType = "TrueType";
    }
  } else if (isOpenTypeFile(file)) {
    if (composite) {
      fileType = "CIDFontType2";
    } else {
      fileType = "OpenType";
    }
  } else if (isType1File(file)) {
    if (composite) {
      fileType = "CIDFontType0";
    } else {
      fileType = type === "MMType1" ? "MMType1" : "Type1";
    }
  } else if (isCFFFile(file)) {
    if (composite) {
      fileType = "CIDFontType0";
      fileSubtype = "CIDFontType0C";
    } else {
      fileType = type === "MMType1" ? "MMType1" : "Type1";
      fileSubtype = "Type1C";
    }
  } else {
    (0, _util.warn)("getFontFileType: Unable to detect correct font file Type/Subtype.");
    fileType = type;
    fileSubtype = subtype;
  }
  return [fileType, fileSubtype];
}
function applyStandardFontGlyphMap(map, glyphMap) {
  for (const charCode in glyphMap) {
    map[+charCode] = glyphMap[charCode];
  }
}
function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
  const toFontChar = [];
  let unicode;
  for (let i = 0, ii = encoding.length; i < ii; i++) {
    unicode = (0, _unicode.getUnicodeForGlyph)(encoding[i], glyphsUnicodeMap);
    if (unicode !== -1) {
      toFontChar[i] = unicode;
    }
  }
  for (const charCode in differences) {
    unicode = (0, _unicode.getUnicodeForGlyph)(differences[charCode], glyphsUnicodeMap);
    if (unicode !== -1) {
      toFontChar[+charCode] = unicode;
    }
  }
  return toFontChar;
}
function isMacNameRecord(r) {
  return r.platform === 1 && r.encoding === 0 && r.language === 0;
}
function isWinNameRecord(r) {
  return r.platform === 3 && r.encoding === 1 && r.language === 0x409;
}
function convertCidString(charCode, cid, shouldThrow = false) {
  switch (cid.length) {
    case 1:
      return cid.charCodeAt(0);
    case 2:
      return cid.charCodeAt(0) << 8 | cid.charCodeAt(1);
  }
  const msg = `Unsupported CID string (charCode ${charCode}): "${cid}".`;
  if (shouldThrow) {
    throw new _util.FormatError(msg);
  }
  (0, _util.warn)(msg);
  return cid;
}
function adjustMapping(charCodeToGlyphId, hasGlyph, newGlyphZeroId, toUnicode) {
  const newMap = Object.create(null);
  const toUnicodeExtraMap = new Map();
  const toFontChar = [];
  const usedGlyphIds = new Set();
  let privateUseAreaIndex = 0;
  const privateUseOffetStart = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
  let nextAvailableFontCharCode = privateUseOffetStart;
  let privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
  for (let originalCharCode in charCodeToGlyphId) {
    originalCharCode |= 0;
    let glyphId = charCodeToGlyphId[originalCharCode];
    if (!hasGlyph(glyphId)) {
      continue;
    }
    if (nextAvailableFontCharCode > privateUseOffetEnd) {
      privateUseAreaIndex++;
      if (privateUseAreaIndex >= PRIVATE_USE_AREAS.length) {
        (0, _util.warn)("Ran out of space in font private use area.");
        break;
      }
      nextAvailableFontCharCode = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
      privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
    }
    const fontCharCode = nextAvailableFontCharCode++;
    if (glyphId === 0) {
      glyphId = newGlyphZeroId;
    }
    let unicode = toUnicode.get(originalCharCode);
    if (typeof unicode === "string") {
      unicode = unicode.codePointAt(0);
    }
    if (unicode && unicode < privateUseOffetStart && !usedGlyphIds.has(glyphId)) {
      toUnicodeExtraMap.set(unicode, glyphId);
      usedGlyphIds.add(glyphId);
    }
    newMap[fontCharCode] = glyphId;
    toFontChar[originalCharCode] = fontCharCode;
  }
  return {
    toFontChar,
    charCodeToGlyphId: newMap,
    toUnicodeExtraMap,
    nextAvailableFontCharCode
  };
}
function getRanges(glyphs, toUnicodeExtraMap, numGlyphs) {
  const codes = [];
  for (const charCode in glyphs) {
    if (glyphs[charCode] >= numGlyphs) {
      continue;
    }
    codes.push({
      fontCharCode: charCode | 0,
      glyphId: glyphs[charCode]
    });
  }
  if (toUnicodeExtraMap) {
    for (const [unicode, glyphId] of toUnicodeExtraMap) {
      if (glyphId >= numGlyphs) {
        continue;
      }
      codes.push({
        fontCharCode: unicode,
        glyphId
      });
    }
  }
  if (codes.length === 0) {
    codes.push({
      fontCharCode: 0,
      glyphId: 0
    });
  }
  codes.sort(function fontGetRangesSort(a, b) {
    return a.fontCharCode - b.fontCharCode;
  });
  const ranges = [];
  const length = codes.length;
  for (let n = 0; n < length;) {
    const start = codes[n].fontCharCode;
    const codeIndices = [codes[n].glyphId];
    ++n;
    let end = start;
    while (n < length && end + 1 === codes[n].fontCharCode) {
      codeIndices.push(codes[n].glyphId);
      ++end;
      ++n;
      if (end === 0xffff) {
        break;
      }
    }
    ranges.push([start, end, codeIndices]);
  }
  return ranges;
}
function createCmapTable(glyphs, toUnicodeExtraMap, numGlyphs) {
  const ranges = getRanges(glyphs, toUnicodeExtraMap, numGlyphs);
  const numTables = ranges.at(-1)[1] > 0xffff ? 2 : 1;
  let cmap = "\x00\x00" + string16(numTables) + "\x00\x03" + "\x00\x01" + (0, _util.string32)(4 + numTables * 8);
  let i, ii, j, jj;
  for (i = ranges.length - 1; i >= 0; --i) {
    if (ranges[i][0] <= 0xffff) {
      break;
    }
  }
  const bmpLength = i + 1;
  if (ranges[i][0] < 0xffff && ranges[i][1] === 0xffff) {
    ranges[i][1] = 0xfffe;
  }
  const trailingRangesCount = ranges[i][1] < 0xffff ? 1 : 0;
  const segCount = bmpLength + trailingRangesCount;
  const searchParams = _opentype_file_builder.OpenTypeFileBuilder.getSearchParams(segCount, 2);
  let startCount = "";
  let endCount = "";
  let idDeltas = "";
  let idRangeOffsets = "";
  let glyphsIds = "";
  let bias = 0;
  let range, start, end, codes;
  for (i = 0, ii = bmpLength; i < ii; i++) {
    range = ranges[i];
    start = range[0];
    end = range[1];
    startCount += string16(start);
    endCount += string16(end);
    codes = range[2];
    let contiguous = true;
    for (j = 1, jj = codes.length; j < jj; ++j) {
      if (codes[j] !== codes[j - 1] + 1) {
        contiguous = false;
        break;
      }
    }
    if (!contiguous) {
      const offset = (segCount - i) * 2 + bias * 2;
      bias += end - start + 1;
      idDeltas += string16(0);
      idRangeOffsets += string16(offset);
      for (j = 0, jj = codes.length; j < jj; ++j) {
        glyphsIds += string16(codes[j]);
      }
    } else {
      const startCode = codes[0];
      idDeltas += string16(startCode - start & 0xffff);
      idRangeOffsets += string16(0);
    }
  }
  if (trailingRangesCount > 0) {
    endCount += "\xFF\xFF";
    startCount += "\xFF\xFF";
    idDeltas += "\x00\x01";
    idRangeOffsets += "\x00\x00";
  }
  const format314 = "\x00\x00" + string16(2 * segCount) + string16(searchParams.range) + string16(searchParams.entry) + string16(searchParams.rangeShift) + endCount + "\x00\x00" + startCount + idDeltas + idRangeOffsets + glyphsIds;
  let format31012 = "";
  let header31012 = "";
  if (numTables > 1) {
    cmap += "\x00\x03" + "\x00\x0A" + (0, _util.string32)(4 + numTables * 8 + 4 + format314.length);
    format31012 = "";
    for (i = 0, ii = ranges.length; i < ii; i++) {
      range = ranges[i];
      start = range[0];
      codes = range[2];
      let code = codes[0];
      for (j = 1, jj = codes.length; j < jj; ++j) {
        if (codes[j] !== codes[j - 1] + 1) {
          end = range[0] + j - 1;
          format31012 += (0, _util.string32)(start) + (0, _util.string32)(end) + (0, _util.string32)(code);
          start = end + 1;
          code = codes[j];
        }
      }
      format31012 += (0, _util.string32)(start) + (0, _util.string32)(range[1]) + (0, _util.string32)(code);
    }
    header31012 = "\x00\x0C" + "\x00\x00" + (0, _util.string32)(format31012.length + 16) + "\x00\x00\x00\x00" + (0, _util.string32)(format31012.length / 12);
  }
  return cmap + "\x00\x04" + string16(format314.length + 4) + format314 + header31012 + format31012;
}
function validateOS2Table(os2, file) {
  file.pos = (file.start || 0) + os2.offset;
  const version = file.getUint16();
  file.skip(60);
  const selection = file.getUint16();
  if (version < 4 && selection & 0x0300) {
    return false;
  }
  const firstChar = file.getUint16();
  const lastChar = file.getUint16();
  if (firstChar > lastChar) {
    return false;
  }
  file.skip(6);
  const usWinAscent = file.getUint16();
  if (usWinAscent === 0) {
    return false;
  }
  os2.data[8] = os2.data[9] = 0;
  return true;
}
function createOS2Table(properties, charstrings, override) {
  override = override || {
    unitsPerEm: 0,
    yMax: 0,
    yMin: 0,
    ascent: 0,
    descent: 0
  };
  let ulUnicodeRange1 = 0;
  let ulUnicodeRange2 = 0;
  let ulUnicodeRange3 = 0;
  let ulUnicodeRange4 = 0;
  let firstCharIndex = null;
  let lastCharIndex = 0;
  if (charstrings) {
    for (let code in charstrings) {
      code |= 0;
      if (firstCharIndex > code || !firstCharIndex) {
        firstCharIndex = code;
      }
      if (lastCharIndex < code) {
        lastCharIndex = code;
      }
      const position = (0, _unicode.getUnicodeRangeFor)(code);
      if (position < 32) {
        ulUnicodeRange1 |= 1 << position;
      } else if (position < 64) {
        ulUnicodeRange2 |= 1 << position - 32;
      } else if (position < 96) {
        ulUnicodeRange3 |= 1 << position - 64;
      } else if (position < 123) {
        ulUnicodeRange4 |= 1 << position - 96;
      } else {
        throw new _util.FormatError("Unicode ranges Bits > 123 are reserved for internal usage");
      }
    }
    if (lastCharIndex > 0xffff) {
      lastCharIndex = 0xffff;
    }
  } else {
    firstCharIndex = 0;
    lastCharIndex = 255;
  }
  const bbox = properties.bbox || [0, 0, 0, 0];
  const unitsPerEm = override.unitsPerEm || 1 / (properties.fontMatrix || _util.FONT_IDENTITY_MATRIX)[0];
  const scale = properties.ascentScaled ? 1.0 : unitsPerEm / PDF_GLYPH_SPACE_UNITS;
  const typoAscent = override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
  let typoDescent = override.descent || Math.round(scale * (properties.descent || bbox[1]));
  if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
    typoDescent = -typoDescent;
  }
  const winAscent = override.yMax || typoAscent;
  const winDescent = -override.yMin || -typoDescent;
  return "\x00\x03" + "\x02\x24" + "\x01\xF4" + "\x00\x05" + "\x00\x00" + "\x02\x8A" + "\x02\xBB" + "\x00\x00" + "\x00\x8C" + "\x02\x8A" + "\x02\xBB" + "\x00\x00" + "\x01\xDF" + "\x00\x31" + "\x01\x02" + "\x00\x00" + "\x00\x00\x06" + String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) + "\x00\x00\x00\x00\x00\x00" + (0, _util.string32)(ulUnicodeRange1) + (0, _util.string32)(ulUnicodeRange2) + (0, _util.string32)(ulUnicodeRange3) + (0, _util.string32)(ulUnicodeRange4) + "\x2A\x32\x31\x2A" + string16(properties.italicAngle ? 1 : 0) + string16(firstCharIndex || properties.firstChar) + string16(lastCharIndex || properties.lastChar) + string16(typoAscent) + string16(typoDescent) + "\x00\x64" + string16(winAscent) + string16(winDescent) + "\x00\x00\x00\x00" + "\x00\x00\x00\x00" + string16(properties.xHeight) + string16(properties.capHeight) + string16(0) + string16(firstCharIndex || properties.firstChar) + "\x00\x03";
}
function createPostTable(properties) {
  const angle = Math.floor(properties.italicAngle * 2 ** 16);
  return "\x00\x03\x00\x00" + (0, _util.string32)(angle) + "\x00\x00" + "\x00\x00" + (0, _util.string32)(properties.fixedPitch ? 1 : 0) + "\x00\x00\x00\x00" + "\x00\x00\x00\x00" + "\x00\x00\x00\x00" + "\x00\x00\x00\x00";
}
function createPostscriptName(name) {
  return name.replace(/[^\x21-\x7E]|[[\](){}<>/%]/g, "").slice(0, 63);
}
function createNameTable(name, proto) {
  if (!proto) {
    proto = [[], []];
  }
  const strings = [proto[0][0] || "Original licence", proto[0][1] || name, proto[0][2] || "Unknown", proto[0][3] || "uniqueID", proto[0][4] || name, proto[0][5] || "Version 0.11", proto[0][6] || createPostscriptName(name), proto[0][7] || "Unknown", proto[0][8] || "Unknown", proto[0][9] || "Unknown"];
  const stringsUnicode = [];
  let i, ii, j, jj, str;
  for (i = 0, ii = strings.length; i < ii; i++) {
    str = proto[1][i] || strings[i];
    const strBufUnicode = [];
    for (j = 0, jj = str.length; j < jj; j++) {
      strBufUnicode.push(string16(str.charCodeAt(j)));
    }
    stringsUnicode.push(strBufUnicode.join(""));
  }
  const names = [strings, stringsUnicode];
  const platforms = ["\x00\x01", "\x00\x03"];
  const encodings = ["\x00\x00", "\x00\x01"];
  const languages = ["\x00\x00", "\x04\x09"];
  const namesRecordCount = strings.length * platforms.length;
  let nameTable = "\x00\x00" + string16(namesRecordCount) + string16(namesRecordCount * 12 + 6);
  let strOffset = 0;
  for (i = 0, ii = platforms.length; i < ii; i++) {
    const strs = names[i];
    for (j = 0, jj = strs.length; j < jj; j++) {
      str = strs[j];
      const nameRecord = platforms[i] + encodings[i] + languages[i] + string16(j) + string16(str.length) + string16(strOffset);
      nameTable += nameRecord;
      strOffset += str.length;
    }
  }
  nameTable += strings.join("") + stringsUnicode.join("");
  return nameTable;
}
class Font {
  constructor(name, file, properties) {
    this.name = name;
    this.psName = null;
    this.mimetype = null;
    this.disableFontFace = false;
    this.loadedName = properties.loadedName;
    this.isType3Font = properties.isType3Font;
    this.missingFile = false;
    this.cssFontInfo = properties.cssFontInfo;
    this._charsCache = Object.create(null);
    this._glyphCache = Object.create(null);
    let isSerifFont = !!(properties.flags & _fonts_utils.FontFlags.Serif);
    if (!isSerifFont && !properties.isSimulatedFlags) {
      const baseName = name.replace(/[,_]/g, "-").split("-")[0],
        serifFonts = (0, _standard_fonts.getSerifFonts)();
      for (const namePart of baseName.split("+")) {
        if (serifFonts[namePart]) {
          isSerifFont = true;
          break;
        }
      }
    }
    this.isSerifFont = isSerifFont;
    this.isSymbolicFont = !!(properties.flags & _fonts_utils.FontFlags.Symbolic);
    this.isMonospace = !!(properties.flags & _fonts_utils.FontFlags.FixedPitch);
    let {
      type,
      subtype
    } = properties;
    this.type = type;
    this.subtype = subtype;
    const matches = name.match(/^InvalidPDFjsFont_(.*)_\d+$/);
    this.isInvalidPDFjsFont = !!matches;
    if (this.isInvalidPDFjsFont) {
      this.fallbackName = matches[1];
    } else if (this.isMonospace) {
      this.fallbackName = "monospace";
    } else if (this.isSerifFont) {
      this.fallbackName = "serif";
    } else {
      this.fallbackName = "sans-serif";
    }
    this.differences = properties.differences;
    this.widths = properties.widths;
    this.defaultWidth = properties.defaultWidth;
    this.composite = properties.composite;
    this.cMap = properties.cMap;
    this.capHeight = properties.capHeight / PDF_GLYPH_SPACE_UNITS;
    this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
    this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
    this.lineHeight = this.ascent - this.descent;
    this.fontMatrix = properties.fontMatrix;
    this.bbox = properties.bbox;
    this.defaultEncoding = properties.defaultEncoding;
    this.toUnicode = properties.toUnicode;
    this.toFontChar = [];
    if (properties.type === "Type3") {
      for (let charCode = 0; charCode < 256; charCode++) {
        this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
      }
      return;
    }
    this.cidEncoding = properties.cidEncoding || "";
    this.vertical = !!properties.vertical;
    if (this.vertical) {
      this.vmetrics = properties.vmetrics;
      this.defaultVMetrics = properties.defaultVMetrics;
    }
    if (!file || file.isEmpty) {
      if (file) {
        (0, _util.warn)('Font file is empty in "' + name + '" (' + this.loadedName + ")");
      }
      this.fallbackToSystemFont(properties);
      return;
    }
    [type, subtype] = getFontFileType(file, properties);
    if (type !== this.type || subtype !== this.subtype) {
      (0, _util.info)("Inconsistent font file Type/SubType, expected: " + `${this.type}/${this.subtype} but found: ${type}/${subtype}.`);
    }
    let data;
    try {
      switch (type) {
        case "MMType1":
          (0, _util.info)("MMType1 font (" + name + "), falling back to Type1.");
        case "Type1":
        case "CIDFontType0":
          this.mimetype = "font/opentype";
          const cff = subtype === "Type1C" || subtype === "CIDFontType0C" ? new _cff_font.CFFFont(file, properties) : new _type1_font.Type1Font(name, file, properties);
          adjustWidths(properties);
          data = this.convert(name, cff, properties);
          break;
        case "OpenType":
        case "TrueType":
        case "CIDFontType2":
          this.mimetype = "font/opentype";
          data = this.checkAndRepair(name, file, properties);
          if (this.isOpenType) {
            adjustWidths(properties);
            type = "OpenType";
          }
          break;
        default:
          throw new _util.FormatError(`Font ${type} is not supported`);
      }
    } catch (e) {
      (0, _util.warn)(e);
      this.fallbackToSystemFont(properties);
      return;
    }
    amendFallbackToUnicode(properties);
    this.data = data;
    this.type = type;
    this.subtype = subtype;
    this.fontMatrix = properties.fontMatrix;
    this.widths = properties.widths;
    this.defaultWidth = properties.defaultWidth;
    this.toUnicode = properties.toUnicode;
    this.seacMap = properties.seacMap;
  }
  get renderer() {
    const renderer = _font_renderer.FontRendererFactory.create(this, _fonts_utils.SEAC_ANALYSIS_ENABLED);
    return (0, _util.shadow)(this, "renderer", renderer);
  }
  exportData(extraProperties = false) {
    const exportDataProperties = extraProperties ? [...EXPORT_DATA_PROPERTIES, ...EXPORT_DATA_EXTRA_PROPERTIES] : EXPORT_DATA_PROPERTIES;
    const data = Object.create(null);
    let property, value;
    for (property of exportDataProperties) {
      value = this[property];
      if (value !== undefined) {
        data[property] = value;
      }
    }
    return data;
  }
  fallbackToSystemFont(properties) {
    this.missingFile = true;
    const {
      name,
      type
    } = this;
    let fontName = (0, _fonts_utils.normalizeFontName)(name);
    const stdFontMap = (0, _standard_fonts.getStdFontMap)(),
      nonStdFontMap = (0, _standard_fonts.getNonStdFontMap)();
    const isStandardFont = !!stdFontMap[fontName];
    const isMappedToStandardFont = !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
    fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
    const fontBasicMetricsMap = (0, _metrics.getFontBasicMetrics)();
    const metrics = fontBasicMetricsMap[fontName];
    if (metrics) {
      if (isNaN(this.ascent)) {
        this.ascent = metrics.ascent / PDF_GLYPH_SPACE_UNITS;
      }
      if (isNaN(this.descent)) {
        this.descent = metrics.descent / PDF_GLYPH_SPACE_UNITS;
      }
      if (isNaN(this.capHeight)) {
        this.capHeight = metrics.capHeight / PDF_GLYPH_SPACE_UNITS;
      }
    }
    this.bold = /bold/gi.test(fontName);
    this.italic = /oblique|italic/gi.test(fontName);
    this.black = /Black/g.test(name);
    const isNarrow = /Narrow/g.test(name);
    this.remeasure = (!isStandardFont || isNarrow) && Object.keys(this.widths).length > 0;
    if ((isStandardFont || isMappedToStandardFont) && type === "CIDFontType2" && this.cidEncoding.startsWith("Identity-")) {
      const cidToGidMap = properties.cidToGidMap;
      const map = [];
      applyStandardFontGlyphMap(map, (0, _standard_fonts.getGlyphMapForStandardFonts)());
      if (/Arial-?Black/i.test(name)) {
        applyStandardFontGlyphMap(map, (0, _standard_fonts.getSupplementalGlyphMapForArialBlack)());
      } else if (/Calibri/i.test(name)) {
        applyStandardFontGlyphMap(map, (0, _standard_fonts.getSupplementalGlyphMapForCalibri)());
      }
      if (cidToGidMap) {
        for (const charCode in map) {
          const cid = map[charCode];
          if (cidToGidMap[cid] !== undefined) {
            map[+charCode] = cidToGidMap[cid];
          }
        }
        if (cidToGidMap.length !== this.toUnicode.length && properties.hasIncludedToUnicodeMap && this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap) {
          this.toUnicode.forEach(function (charCode, unicodeCharCode) {
            const cid = map[charCode];
            if (cidToGidMap[cid] === undefined) {
              map[+charCode] = unicodeCharCode;
            }
          });
        }
      }
      if (!(this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap)) {
        this.toUnicode.forEach(function (charCode, unicodeCharCode) {
          map[+charCode] = unicodeCharCode;
        });
      }
      this.toFontChar = map;
      this.toUnicode = new _to_unicode_map.ToUnicodeMap(map);
    } else if (/Symbol/i.test(fontName)) {
      this.toFontChar = buildToFontChar(_encodings.SymbolSetEncoding, (0, _glyphlist.getGlyphsUnicode)(), this.differences);
    } else if (/Dingbats/i.test(fontName)) {
      if (/Wingdings/i.test(name)) {
        (0, _util.warn)("Non-embedded Wingdings font, falling back to ZapfDingbats.");
      }
      this.toFontChar = buildToFontChar(_encodings.ZapfDingbatsEncoding, (0, _glyphlist.getDingbatsGlyphsUnicode)(), this.differences);
    } else if (isStandardFont) {
      const map = buildToFontChar(this.defaultEncoding, (0, _glyphlist.getGlyphsUnicode)(), this.differences);
      if (type === "CIDFontType2" && !this.cidEncoding.startsWith("Identity-") && !(this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap)) {
        this.toUnicode.forEach(function (charCode, unicodeCharCode) {
          map[+charCode] = unicodeCharCode;
        });
      }
      this.toFontChar = map;
    } else {
      const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
      const map = [];
      this.toUnicode.forEach((charCode, unicodeCharCode) => {
        if (!this.composite) {
          const glyphName = this.differences[charCode] || this.defaultEncoding[charCode];
          const unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
          if (unicode !== -1) {
            unicodeCharCode = unicode;
          }
        }
        map[+charCode] = unicodeCharCode;
      });
      if (this.composite && this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap) {
        if (/Tahoma|Verdana/i.test(name)) {
          applyStandardFontGlyphMap(map, (0, _standard_fonts.getGlyphMapForStandardFonts)());
        }
      }
      this.toFontChar = map;
    }
    amendFallbackToUnicode(properties);
    this.loadedName = fontName.split("-")[0];
  }
  checkAndRepair(name, font, properties) {
    const VALID_TABLES = ["OS/2", "cmap", "head", "hhea", "hmtx", "maxp", "name", "post", "loca", "glyf", "fpgm", "prep", "cvt ", "CFF "];
    function readTables(file, numTables) {
      const tables = Object.create(null);
      tables["OS/2"] = null;
      tables.cmap = null;
      tables.head = null;
      tables.hhea = null;
      tables.hmtx = null;
      tables.maxp = null;
      tables.name = null;
      tables.post = null;
      for (let i = 0; i < numTables; i++) {
        const table = readTableEntry(file);
        if (!VALID_TABLES.includes(table.tag)) {
          continue;
        }
        if (table.length === 0) {
          continue;
        }
        tables[table.tag] = table;
      }
      return tables;
    }
    function readTableEntry(file) {
      const tag = file.getString(4);
      const checksum = file.getInt32() >>> 0;
      const offset = file.getInt32() >>> 0;
      const length = file.getInt32() >>> 0;
      const previousPosition = file.pos;
      file.pos = file.start || 0;
      file.skip(offset);
      const data = file.getBytes(length);
      file.pos = previousPosition;
      if (tag === "head") {
        data[8] = data[9] = data[10] = data[11] = 0;
        data[17] |= 0x20;
      }
      return {
        tag,
        checksum,
        length,
        offset,
        data
      };
    }
    function readOpenTypeHeader(ttf) {
      return {
        version: ttf.getString(4),
        numTables: ttf.getUint16(),
        searchRange: ttf.getUint16(),
        entrySelector: ttf.getUint16(),
        rangeShift: ttf.getUint16()
      };
    }
    function readTrueTypeCollectionHeader(ttc) {
      const ttcTag = ttc.getString(4);
      (0, _util.assert)(ttcTag === "ttcf", "Must be a TrueType Collection font.");
      const majorVersion = ttc.getUint16();
      const minorVersion = ttc.getUint16();
      const numFonts = ttc.getInt32() >>> 0;
      const offsetTable = [];
      for (let i = 0; i < numFonts; i++) {
        offsetTable.push(ttc.getInt32() >>> 0);
      }
      const header = {
        ttcTag,
        majorVersion,
        minorVersion,
        numFonts,
        offsetTable
      };
      switch (majorVersion) {
        case 1:
          return header;
        case 2:
          header.dsigTag = ttc.getInt32() >>> 0;
          header.dsigLength = ttc.getInt32() >>> 0;
          header.dsigOffset = ttc.getInt32() >>> 0;
          return header;
      }
      throw new _util.FormatError(`Invalid TrueType Collection majorVersion: ${majorVersion}.`);
    }
    function readTrueTypeCollectionData(ttc, fontName) {
      const {
        numFonts,
        offsetTable
      } = readTrueTypeCollectionHeader(ttc);
      const fontNameParts = fontName.split("+");
      let fallbackData;
      for (let i = 0; i < numFonts; i++) {
        ttc.pos = (ttc.start || 0) + offsetTable[i];
        const potentialHeader = readOpenTypeHeader(ttc);
        const potentialTables = readTables(ttc, potentialHeader.numTables);
        if (!potentialTables.name) {
          throw new _util.FormatError('TrueType Collection font must contain a "name" table.');
        }
        const [nameTable] = readNameTable(potentialTables.name);
        for (let j = 0, jj = nameTable.length; j < jj; j++) {
          for (let k = 0, kk = nameTable[j].length; k < kk; k++) {
            const nameEntry = nameTable[j][k] && nameTable[j][k].replace(/\s/g, "");
            if (!nameEntry) {
              continue;
            }
            if (nameEntry === fontName) {
              return {
                header: potentialHeader,
                tables: potentialTables
              };
            }
            if (fontNameParts.length < 2) {
              continue;
            }
            for (const part of fontNameParts) {
              if (nameEntry === part) {
                fallbackData = {
                  name: part,
                  header: potentialHeader,
                  tables: potentialTables
                };
              }
            }
          }
        }
      }
      if (fallbackData) {
        (0, _util.warn)(`TrueType Collection does not contain "${fontName}" font, ` + `falling back to "${fallbackData.name}" font instead.`);
        return {
          header: fallbackData.header,
          tables: fallbackData.tables
        };
      }
      throw new _util.FormatError(`TrueType Collection does not contain "${fontName}" font.`);
    }
    function readCmapTable(cmap, file, isSymbolicFont, hasEncoding) {
      if (!cmap) {
        (0, _util.warn)("No cmap table available.");
        return {
          platformId: -1,
          encodingId: -1,
          mappings: [],
          hasShortCmap: false
        };
      }
      let segment;
      let start = (file.start || 0) + cmap.offset;
      file.pos = start;
      file.skip(2);
      const numTables = file.getUint16();
      let potentialTable;
      let canBreak = false;
      for (let i = 0; i < numTables; i++) {
        const platformId = file.getUint16();
        const encodingId = file.getUint16();
        const offset = file.getInt32() >>> 0;
        let useTable = false;
        if (potentialTable && potentialTable.platformId === platformId && potentialTable.encodingId === encodingId) {
          continue;
        }
        if (platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 3)) {
          useTable = true;
        } else if (platformId === 1 && encodingId === 0) {
          useTable = true;
        } else if (platformId === 3 && encodingId === 1 && (hasEncoding || !potentialTable)) {
          useTable = true;
          if (!isSymbolicFont) {
            canBreak = true;
          }
        } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
          useTable = true;
          let correctlySorted = true;
          if (i < numTables - 1) {
            const nextBytes = file.peekBytes(2),
              nextPlatformId = int16(nextBytes[0], nextBytes[1]);
            if (nextPlatformId < platformId) {
              correctlySorted = false;
            }
          }
          if (correctlySorted) {
            canBreak = true;
          }
        }
        if (useTable) {
          potentialTable = {
            platformId,
            encodingId,
            offset
          };
        }
        if (canBreak) {
          break;
        }
      }
      if (potentialTable) {
        file.pos = start + potentialTable.offset;
      }
      if (!potentialTable || file.peekByte() === -1) {
        (0, _util.warn)("Could not find a preferred cmap table.");
        return {
          platformId: -1,
          encodingId: -1,
          mappings: [],
          hasShortCmap: false
        };
      }
      const format = file.getUint16();
      let hasShortCmap = false;
      const mappings = [];
      let j, glyphId;
      if (format === 0) {
        file.skip(2 + 2);
        for (j = 0; j < 256; j++) {
          const index = file.getByte();
          if (!index) {
            continue;
          }
          mappings.push({
            charCode: j,
            glyphId: index
          });
        }
        hasShortCmap = true;
      } else if (format === 2) {
        file.skip(2 + 2);
        const subHeaderKeys = [];
        let maxSubHeaderKey = 0;
        for (let i = 0; i < 256; i++) {
          const subHeaderKey = file.getUint16() >> 3;
          subHeaderKeys.push(subHeaderKey);
          maxSubHeaderKey = Math.max(subHeaderKey, maxSubHeaderKey);
        }
        const subHeaders = [];
        for (let i = 0; i <= maxSubHeaderKey; i++) {
          subHeaders.push({
            firstCode: file.getUint16(),
            entryCount: file.getUint16(),
            idDelta: signedInt16(file.getByte(), file.getByte()),
            idRangePos: file.pos + file.getUint16()
          });
        }
        for (let i = 0; i < 256; i++) {
          if (subHeaderKeys[i] === 0) {
            file.pos = subHeaders[0].idRangePos + 2 * i;
            glyphId = file.getUint16();
            mappings.push({
              charCode: i,
              glyphId
            });
          } else {
            const s = subHeaders[subHeaderKeys[i]];
            for (j = 0; j < s.entryCount; j++) {
              const charCode = (i << 8) + j + s.firstCode;
              file.pos = s.idRangePos + 2 * j;
              glyphId = file.getUint16();
              if (glyphId !== 0) {
                glyphId = (glyphId + s.idDelta) % 65536;
              }
              mappings.push({
                charCode,
                glyphId
              });
            }
          }
        }
      } else if (format === 4) {
        file.skip(2 + 2);
        const segCount = file.getUint16() >> 1;
        file.skip(6);
        const segments = [];
        let segIndex;
        for (segIndex = 0; segIndex < segCount; segIndex++) {
          segments.push({
            end: file.getUint16()
          });
        }
        file.skip(2);
        for (segIndex = 0; segIndex < segCount; segIndex++) {
          segments[segIndex].start = file.getUint16();
        }
        for (segIndex = 0; segIndex < segCount; segIndex++) {
          segments[segIndex].delta = file.getUint16();
        }
        let offsetsCount = 0,
          offsetIndex;
        for (segIndex = 0; segIndex < segCount; segIndex++) {
          segment = segments[segIndex];
          const rangeOffset = file.getUint16();
          if (!rangeOffset) {
            segment.offsetIndex = -1;
            continue;
          }
          offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
          segment.offsetIndex = offsetIndex;
          offsetsCount = Math.max(offsetsCount, offsetIndex + segment.end - segment.start + 1);
        }
        const offsets = [];
        for (j = 0; j < offsetsCount; j++) {
          offsets.push(file.getUint16());
        }
        for (segIndex = 0; segIndex < segCount; segIndex++) {
          segment = segments[segIndex];
          start = segment.start;
          const end = segment.end;
          const delta = segment.delta;
          offsetIndex = segment.offsetIndex;
          for (j = start; j <= end; j++) {
            if (j === 0xffff) {
              continue;
            }
            glyphId = offsetIndex < 0 ? j : offsets[offsetIndex + j - start];
            glyphId = glyphId + delta & 0xffff;
            mappings.push({
              charCode: j,
              glyphId
            });
          }
        }
      } else if (format === 6) {
        file.skip(2 + 2);
        const firstCode = file.getUint16();
        const entryCount = file.getUint16();
        for (j = 0; j < entryCount; j++) {
          glyphId = file.getUint16();
          const charCode = firstCode + j;
          mappings.push({
            charCode,
            glyphId
          });
        }
      } else if (format === 12) {
        file.skip(2 + 4 + 4);
        const nGroups = file.getInt32() >>> 0;
        for (j = 0; j < nGroups; j++) {
          const startCharCode = file.getInt32() >>> 0;
          const endCharCode = file.getInt32() >>> 0;
          let glyphCode = file.getInt32() >>> 0;
          for (let charCode = startCharCode; charCode <= endCharCode; charCode++) {
            mappings.push({
              charCode,
              glyphId: glyphCode++
            });
          }
        }
      } else {
        (0, _util.warn)("cmap table has unsupported format: " + format);
        return {
          platformId: -1,
          encodingId: -1,
          mappings: [],
          hasShortCmap: false
        };
      }
      mappings.sort(function (a, b) {
        return a.charCode - b.charCode;
      });
      for (let i = 1; i < mappings.length; i++) {
        if (mappings[i - 1].charCode === mappings[i].charCode) {
          mappings.splice(i, 1);
          i--;
        }
      }
      return {
        platformId: potentialTable.platformId,
        encodingId: potentialTable.encodingId,
        mappings,
        hasShortCmap
      };
    }
    function sanitizeMetrics(file, header, metrics, headTable, numGlyphs, dupFirstEntry) {
      if (!header) {
        if (metrics) {
          metrics.data = null;
        }
        return;
      }
      file.pos = (file.start || 0) + header.offset;
      file.pos += 4;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      file.pos += 2;
      const caretOffset = file.getUint16();
      file.pos += 8;
      file.pos += 2;
      let numOfMetrics = file.getUint16();
      if (caretOffset !== 0) {
        const macStyle = int16(headTable.data[44], headTable.data[45]);
        if (!(macStyle & 2)) {
          header.data[22] = 0;
          header.data[23] = 0;
        }
      }
      if (numOfMetrics > numGlyphs) {
        (0, _util.info)(`The numOfMetrics (${numOfMetrics}) should not be ` + `greater than the numGlyphs (${numGlyphs}).`);
        numOfMetrics = numGlyphs;
        header.data[34] = (numOfMetrics & 0xff00) >> 8;
        header.data[35] = numOfMetrics & 0x00ff;
      }
      const numOfSidebearings = numGlyphs - numOfMetrics;
      const numMissing = numOfSidebearings - (metrics.length - numOfMetrics * 4 >> 1);
      if (numMissing > 0) {
        const entries = new Uint8Array(metrics.length + numMissing * 2);
        entries.set(metrics.data);
        if (dupFirstEntry) {
          entries[metrics.length] = metrics.data[2];
          entries[metrics.length + 1] = metrics.data[3];
        }
        metrics.data = entries;
      }
    }
    function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart, hintsValid) {
      const glyphProfile = {
        length: 0,
        sizeOfInstructions: 0
      };
      if (sourceEnd - sourceStart <= 12) {
        return glyphProfile;
      }
      const glyf = source.subarray(sourceStart, sourceEnd);
      let contoursCount = signedInt16(glyf[0], glyf[1]);
      if (contoursCount < 0) {
        contoursCount = -1;
        writeSignedInt16(glyf, 0, contoursCount);
        dest.set(glyf, destStart);
        glyphProfile.length = glyf.length;
        return glyphProfile;
      }
      let i,
        j = 10,
        flagsCount = 0;
      for (i = 0; i < contoursCount; i++) {
        const endPoint = glyf[j] << 8 | glyf[j + 1];
        flagsCount = endPoint + 1;
        j += 2;
      }
      const instructionsStart = j;
      const instructionsLength = glyf[j] << 8 | glyf[j + 1];
      glyphProfile.sizeOfInstructions = instructionsLength;
      j += 2 + instructionsLength;
      const instructionsEnd = j;
      let coordinatesLength = 0;
      for (i = 0; i < flagsCount; i++) {
        const flag = glyf[j++];
        if (flag & 0xc0) {
          glyf[j - 1] = flag & 0x3f;
        }
        let xLength = 2;
        if (flag & 2) {
          xLength = 1;
        } else if (flag & 16) {
          xLength = 0;
        }
        let yLength = 2;
        if (flag & 4) {
          yLength = 1;
        } else if (flag & 32) {
          yLength = 0;
        }
        const xyLength = xLength + yLength;
        coordinatesLength += xyLength;
        if (flag & 8) {
          const repeat = glyf[j++];
          i += repeat;
          coordinatesLength += repeat * xyLength;
        }
      }
      if (coordinatesLength === 0) {
        return glyphProfile;
      }
      let glyphDataLength = j + coordinatesLength;
      if (glyphDataLength > glyf.length) {
        return glyphProfile;
      }
      if (!hintsValid && instructionsLength > 0) {
        dest.set(glyf.subarray(0, instructionsStart), destStart);
        dest.set([0, 0], destStart + instructionsStart);
        dest.set(glyf.subarray(instructionsEnd, glyphDataLength), destStart + instructionsStart + 2);
        glyphDataLength -= instructionsLength;
        if (glyf.length - glyphDataLength > 3) {
          glyphDataLength = glyphDataLength + 3 & ~3;
        }
        glyphProfile.length = glyphDataLength;
        return glyphProfile;
      }
      if (glyf.length - glyphDataLength > 3) {
        glyphDataLength = glyphDataLength + 3 & ~3;
        dest.set(glyf.subarray(0, glyphDataLength), destStart);
        glyphProfile.length = glyphDataLength;
        return glyphProfile;
      }
      dest.set(glyf, destStart);
      glyphProfile.length = glyf.length;
      return glyphProfile;
    }
    function sanitizeHead(head, numGlyphs, locaLength) {
      const data = head.data;
      const version = int32(data[0], data[1], data[2], data[3]);
      if (version >> 16 !== 1) {
        (0, _util.info)("Attempting to fix invalid version in head table: " + version);
        data[0] = 0;
        data[1] = 1;
        data[2] = 0;
        data[3] = 0;
      }
      const indexToLocFormat = int16(data[50], data[51]);
      if (indexToLocFormat < 0 || indexToLocFormat > 1) {
        (0, _util.info)("Attempting to fix invalid indexToLocFormat in head table: " + indexToLocFormat);
        const numGlyphsPlusOne = numGlyphs + 1;
        if (locaLength === numGlyphsPlusOne << 1) {
          data[50] = 0;
          data[51] = 0;
        } else if (locaLength === numGlyphsPlusOne << 2) {
          data[50] = 0;
          data[51] = 1;
        } else {
          throw new _util.FormatError("Could not fix indexToLocFormat: " + indexToLocFormat);
        }
      }
    }
    function sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry, maxSizeOfInstructions) {
      let itemSize, itemDecode, itemEncode;
      if (isGlyphLocationsLong) {
        itemSize = 4;
        itemDecode = function fontItemDecodeLong(data, offset) {
          return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
        };
        itemEncode = function fontItemEncodeLong(data, offset, value) {
          data[offset] = value >>> 24 & 0xff;
          data[offset + 1] = value >> 16 & 0xff;
          data[offset + 2] = value >> 8 & 0xff;
          data[offset + 3] = value & 0xff;
        };
      } else {
        itemSize = 2;
        itemDecode = function fontItemDecode(data, offset) {
          return data[offset] << 9 | data[offset + 1] << 1;
        };
        itemEncode = function fontItemEncode(data, offset, value) {
          data[offset] = value >> 9 & 0xff;
          data[offset + 1] = value >> 1 & 0xff;
        };
      }
      const numGlyphsOut = dupFirstEntry ? numGlyphs + 1 : numGlyphs;
      const locaDataSize = itemSize * (1 + numGlyphsOut);
      const locaData = new Uint8Array(locaDataSize);
      locaData.set(loca.data.subarray(0, locaDataSize));
      loca.data = locaData;
      const oldGlyfData = glyf.data;
      const oldGlyfDataLength = oldGlyfData.length;
      const newGlyfData = new Uint8Array(oldGlyfDataLength);
      let i, j;
      const locaEntries = [];
      for (i = 0, j = 0; i < numGlyphs + 1; i++, j += itemSize) {
        let offset = itemDecode(locaData, j);
        if (offset > oldGlyfDataLength) {
          offset = oldGlyfDataLength;
        }
        locaEntries.push({
          index: i,
          offset,
          endOffset: 0
        });
      }
      locaEntries.sort((a, b) => {
        return a.offset - b.offset;
      });
      for (i = 0; i < numGlyphs; i++) {
        locaEntries[i].endOffset = locaEntries[i + 1].offset;
      }
      locaEntries.sort((a, b) => {
        return a.index - b.index;
      });
      for (i = 0; i < numGlyphs; i++) {
        const {
          offset,
          endOffset
        } = locaEntries[i];
        if (offset !== 0 || endOffset !== 0) {
          break;
        }
        const nextOffset = locaEntries[i + 1].offset;
        if (nextOffset === 0) {
          continue;
        }
        locaEntries[i].endOffset = nextOffset;
        break;
      }
      const missingGlyphs = Object.create(null);
      let writeOffset = 0;
      itemEncode(locaData, 0, writeOffset);
      for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
        const glyphProfile = sanitizeGlyph(oldGlyfData, locaEntries[i].offset, locaEntries[i].endOffset, newGlyfData, writeOffset, hintsValid);
        const newLength = glyphProfile.length;
        if (newLength === 0) {
          missingGlyphs[i] = true;
        }
        if (glyphProfile.sizeOfInstructions > maxSizeOfInstructions) {
          maxSizeOfInstructions = glyphProfile.sizeOfInstructions;
        }
        writeOffset += newLength;
        itemEncode(locaData, j, writeOffset);
      }
      if (writeOffset === 0) {
        const simpleGlyph = new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
        for (i = 0, j = itemSize; i < numGlyphsOut; i++, j += itemSize) {
          itemEncode(locaData, j, simpleGlyph.length);
        }
        glyf.data = simpleGlyph;
      } else if (dupFirstEntry) {
        const firstEntryLength = itemDecode(locaData, itemSize);
        if (newGlyfData.length > firstEntryLength + writeOffset) {
          glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
        } else {
          glyf.data = new Uint8Array(firstEntryLength + writeOffset);
          glyf.data.set(newGlyfData.subarray(0, writeOffset));
        }
        glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
        itemEncode(loca.data, locaData.length - itemSize, writeOffset + firstEntryLength);
      } else {
        glyf.data = newGlyfData.subarray(0, writeOffset);
      }
      return {
        missingGlyphs,
        maxSizeOfInstructions
      };
    }
    function readPostScriptTable(post, propertiesObj, maxpNumGlyphs) {
      const start = (font.start || 0) + post.offset;
      font.pos = start;
      const length = post.length,
        end = start + length;
      const version = font.getInt32();
      font.skip(28);
      let glyphNames;
      let valid = true;
      let i;
      switch (version) {
        case 0x00010000:
          glyphNames = _fonts_utils.MacStandardGlyphOrdering;
          break;
        case 0x00020000:
          const numGlyphs = font.getUint16();
          if (numGlyphs !== maxpNumGlyphs) {
            valid = false;
            break;
          }
          const glyphNameIndexes = [];
          for (i = 0; i < numGlyphs; ++i) {
            const index = font.getUint16();
            if (index >= 32768) {
              valid = false;
              break;
            }
            glyphNameIndexes.push(index);
          }
          if (!valid) {
            break;
          }
          const customNames = [],
            strBuf = [];
          while (font.pos < end) {
            const stringLength = font.getByte();
            strBuf.length = stringLength;
            for (i = 0; i < stringLength; ++i) {
              strBuf[i] = String.fromCharCode(font.getByte());
            }
            customNames.push(strBuf.join(""));
          }
          glyphNames = [];
          for (i = 0; i < numGlyphs; ++i) {
            const j = glyphNameIndexes[i];
            if (j < 258) {
              glyphNames.push(_fonts_utils.MacStandardGlyphOrdering[j]);
              continue;
            }
            glyphNames.push(customNames[j - 258]);
          }
          break;
        case 0x00030000:
          break;
        default:
          (0, _util.warn)("Unknown/unsupported post table version " + version);
          valid = false;
          if (propertiesObj.defaultEncoding) {
            glyphNames = propertiesObj.defaultEncoding;
          }
          break;
      }
      propertiesObj.glyphNames = glyphNames;
      return valid;
    }
    function readNameTable(nameTable) {
      const start = (font.start || 0) + nameTable.offset;
      font.pos = start;
      const names = [[], []],
        records = [];
      const length = nameTable.length,
        end = start + length;
      const format = font.getUint16();
      const FORMAT_0_HEADER_LENGTH = 6;
      if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
        return [names, records];
      }
      const numRecords = font.getUint16();
      const stringsStart = font.getUint16();
      const NAME_RECORD_LENGTH = 12;
      let i, ii;
      for (i = 0; i < numRecords && font.pos + NAME_RECORD_LENGTH <= end; i++) {
        const r = {
          platform: font.getUint16(),
          encoding: font.getUint16(),
          language: font.getUint16(),
          name: font.getUint16(),
          length: font.getUint16(),
          offset: font.getUint16()
        };
        if (isMacNameRecord(r) || isWinNameRecord(r)) {
          records.push(r);
        }
      }
      for (i = 0, ii = records.length; i < ii; i++) {
        const record = records[i];
        if (record.length <= 0) {
          continue;
        }
        const pos = start + stringsStart + record.offset;
        if (pos + record.length > end) {
          continue;
        }
        font.pos = pos;
        const nameIndex = record.name;
        if (record.encoding) {
          let str = "";
          for (let j = 0, jj = record.length; j < jj; j += 2) {
            str += String.fromCharCode(font.getUint16());
          }
          names[1][nameIndex] = str;
        } else {
          names[0][nameIndex] = font.getString(record.length);
        }
      }
      return [names, records];
    }
    const TTOpsStackDeltas = [0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1, 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1, 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2, 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1, -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
    function sanitizeTTProgram(table, ttContext) {
      let data = table.data;
      let i = 0,
        j,
        n,
        b,
        funcId,
        pc,
        lastEndf = 0,
        lastDeff = 0;
      const stack = [];
      const callstack = [];
      const functionsCalled = [];
      let tooComplexToFollowFunctions = ttContext.tooComplexToFollowFunctions;
      let inFDEF = false,
        ifLevel = 0,
        inELSE = 0;
      for (let ii = data.length; i < ii;) {
        const op = data[i++];
        if (op === 0x40) {
          n = data[i++];
          if (inFDEF || inELSE) {
            i += n;
          } else {
            for (j = 0; j < n; j++) {
              stack.push(data[i++]);
            }
          }
        } else if (op === 0x41) {
          n = data[i++];
          if (inFDEF || inELSE) {
            i += n * 2;
          } else {
            for (j = 0; j < n; j++) {
              b = data[i++];
              stack.push(b << 8 | data[i++]);
            }
          }
        } else if ((op & 0xf8) === 0xb0) {
          n = op - 0xb0 + 1;
          if (inFDEF || inELSE) {
            i += n;
          } else {
            for (j = 0; j < n; j++) {
              stack.push(data[i++]);
            }
          }
        } else if ((op & 0xf8) === 0xb8) {
          n = op - 0xb8 + 1;
          if (inFDEF || inELSE) {
            i += n * 2;
          } else {
            for (j = 0; j < n; j++) {
              b = data[i++];
              stack.push(b << 8 | data[i++]);
            }
          }
        } else if (op === 0x2b && !tooComplexToFollowFunctions) {
          if (!inFDEF && !inELSE) {
            funcId = stack.at(-1);
            if (isNaN(funcId)) {
              (0, _util.info)("TT: CALL empty stack (or invalid entry).");
            } else {
              ttContext.functionsUsed[funcId] = true;
              if (funcId in ttContext.functionsStackDeltas) {
                const newStackLength = stack.length + ttContext.functionsStackDeltas[funcId];
                if (newStackLength < 0) {
                  (0, _util.warn)("TT: CALL invalid functions stack delta.");
                  ttContext.hintsValid = false;
                  return;
                }
                stack.length = newStackLength;
              } else if (funcId in ttContext.functionsDefined && !functionsCalled.includes(funcId)) {
                callstack.push({
                  data,
                  i,
                  stackTop: stack.length - 1
                });
                functionsCalled.push(funcId);
                pc = ttContext.functionsDefined[funcId];
                if (!pc) {
                  (0, _util.warn)("TT: CALL non-existent function");
                  ttContext.hintsValid = false;
                  return;
                }
                data = pc.data;
                i = pc.i;
              }
            }
          }
        } else if (op === 0x2c && !tooComplexToFollowFunctions) {
          if (inFDEF || inELSE) {
            (0, _util.warn)("TT: nested FDEFs not allowed");
            tooComplexToFollowFunctions = true;
          }
          inFDEF = true;
          lastDeff = i;
          funcId = stack.pop();
          ttContext.functionsDefined[funcId] = {
            data,
            i
          };
        } else if (op === 0x2d) {
          if (inFDEF) {
            inFDEF = false;
            lastEndf = i;
          } else {
            pc = callstack.pop();
            if (!pc) {
              (0, _util.warn)("TT: ENDF bad stack");
              ttContext.hintsValid = false;
              return;
            }
            funcId = functionsCalled.pop();
            data = pc.data;
            i = pc.i;
            ttContext.functionsStackDeltas[funcId] = stack.length - pc.stackTop;
          }
        } else if (op === 0x89) {
          if (inFDEF || inELSE) {
            (0, _util.warn)("TT: nested IDEFs not allowed");
            tooComplexToFollowFunctions = true;
          }
          inFDEF = true;
          lastDeff = i;
        } else if (op === 0x58) {
          ++ifLevel;
        } else if (op === 0x1b) {
          inELSE = ifLevel;
        } else if (op === 0x59) {
          if (inELSE === ifLevel) {
            inELSE = 0;
          }
          --ifLevel;
        } else if (op === 0x1c) {
          if (!inFDEF && !inELSE) {
            const offset = stack.at(-1);
            if (offset > 0) {
              i += offset - 1;
            }
          }
        }
        if (!inFDEF && !inELSE) {
          let stackDelta = 0;
          if (op <= 0x8e) {
            stackDelta = TTOpsStackDeltas[op];
          } else if (op >= 0xc0 && op <= 0xdf) {
            stackDelta = -1;
          } else if (op >= 0xe0) {
            stackDelta = -2;
          }
          if (op >= 0x71 && op <= 0x75) {
            n = stack.pop();
            if (!isNaN(n)) {
              stackDelta = -n * 2;
            }
          }
          while (stackDelta < 0 && stack.length > 0) {
            stack.pop();
            stackDelta++;
          }
          while (stackDelta > 0) {
            stack.push(NaN);
            stackDelta--;
          }
        }
      }
      ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
      const content = [data];
      if (i > data.length) {
        content.push(new Uint8Array(i - data.length));
      }
      if (lastDeff > lastEndf) {
        (0, _util.warn)("TT: complementing a missing function tail");
        content.push(new Uint8Array([0x22, 0x2d]));
      }
      foldTTTable(table, content);
    }
    function checkInvalidFunctions(ttContext, maxFunctionDefs) {
      if (ttContext.tooComplexToFollowFunctions) {
        return;
      }
      if (ttContext.functionsDefined.length > maxFunctionDefs) {
        (0, _util.warn)("TT: more functions defined than expected");
        ttContext.hintsValid = false;
        return;
      }
      for (let j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
        if (j > maxFunctionDefs) {
          (0, _util.warn)("TT: invalid function id: " + j);
          ttContext.hintsValid = false;
          return;
        }
        if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
          (0, _util.warn)("TT: undefined function: " + j);
          ttContext.hintsValid = false;
          return;
        }
      }
    }
    function foldTTTable(table, content) {
      if (content.length > 1) {
        let newLength = 0;
        let j, jj;
        for (j = 0, jj = content.length; j < jj; j++) {
          newLength += content[j].length;
        }
        newLength = newLength + 3 & ~3;
        const result = new Uint8Array(newLength);
        let pos = 0;
        for (j = 0, jj = content.length; j < jj; j++) {
          result.set(content[j], pos);
          pos += content[j].length;
        }
        table.data = result;
        table.length = newLength;
      }
    }
    function sanitizeTTPrograms(fpgm, prep, cvt, maxFunctionDefs) {
      const ttContext = {
        functionsDefined: [],
        functionsUsed: [],
        functionsStackDeltas: [],
        tooComplexToFollowFunctions: false,
        hintsValid: true
      };
      if (fpgm) {
        sanitizeTTProgram(fpgm, ttContext);
      }
      if (prep) {
        sanitizeTTProgram(prep, ttContext);
      }
      if (fpgm) {
        checkInvalidFunctions(ttContext, maxFunctionDefs);
      }
      if (cvt && cvt.length & 1) {
        const cvtData = new Uint8Array(cvt.length + 1);
        cvtData.set(cvt.data);
        cvt.data = cvtData;
      }
      return ttContext.hintsValid;
    }
    font = new _stream.Stream(new Uint8Array(font.getBytes()));
    let header, tables;
    if (isTrueTypeCollectionFile(font)) {
      const ttcData = readTrueTypeCollectionData(font, this.name);
      header = ttcData.header;
      tables = ttcData.tables;
    } else {
      header = readOpenTypeHeader(font);
      tables = readTables(font, header.numTables);
    }
    let cff, cffFile;
    const isTrueType = !tables["CFF "];
    if (!isTrueType) {
      const isComposite = properties.composite && ((properties.cidToGidMap || []).length > 0 || !(properties.cMap instanceof _cmap.IdentityCMap));
      if (header.version === "OTTO" && !isComposite || !tables.head || !tables.hhea || !tables.maxp || !tables.post) {
        cffFile = new _stream.Stream(tables["CFF "].data);
        cff = new _cff_font.CFFFont(cffFile, properties);
        adjustWidths(properties);
        return this.convert(name, cff, properties);
      }
      delete tables.glyf;
      delete tables.loca;
      delete tables.fpgm;
      delete tables.prep;
      delete tables["cvt "];
      this.isOpenType = true;
    } else {
      if (!tables.loca) {
        throw new _util.FormatError('Required "loca" table is not found');
      }
      if (!tables.glyf) {
        (0, _util.warn)('Required "glyf" table is not found -- trying to recover.');
        tables.glyf = {
          tag: "glyf",
          data: new Uint8Array(0)
        };
      }
      this.isOpenType = false;
    }
    if (!tables.maxp) {
      throw new _util.FormatError('Required "maxp" table is not found');
    }
    font.pos = (font.start || 0) + tables.maxp.offset;
    const version = font.getInt32();
    const numGlyphs = font.getUint16();
    if (properties.scaleFactors && properties.scaleFactors.length === numGlyphs && isTrueType) {
      const {
        scaleFactors
      } = properties;
      const isGlyphLocationsLong = int16(tables.head.data[50], tables.head.data[51]);
      const glyphs = new _glyf.GlyfTable({
        glyfTable: tables.glyf.data,
        isGlyphLocationsLong,
        locaTable: tables.loca.data,
        numGlyphs
      });
      glyphs.scale(scaleFactors);
      const {
        glyf,
        loca,
        isLocationLong
      } = glyphs.write();
      tables.glyf.data = glyf;
      tables.loca.data = loca;
      if (isLocationLong !== !!isGlyphLocationsLong) {
        tables.head.data[50] = 0;
        tables.head.data[51] = isLocationLong ? 1 : 0;
      }
      const metrics = tables.hmtx.data;
      for (let i = 0; i < numGlyphs; i++) {
        const j = 4 * i;
        const advanceWidth = Math.round(scaleFactors[i] * int16(metrics[j], metrics[j + 1]));
        metrics[j] = advanceWidth >> 8 & 0xff;
        metrics[j + 1] = advanceWidth & 0xff;
        const lsb = Math.round(scaleFactors[i] * signedInt16(metrics[j + 2], metrics[j + 3]));
        writeSignedInt16(metrics, j + 2, lsb);
      }
    }
    let numGlyphsOut = numGlyphs + 1;
    let dupFirstEntry = true;
    if (numGlyphsOut > 0xffff) {
      dupFirstEntry = false;
      numGlyphsOut = numGlyphs;
      (0, _util.warn)("Not enough space in glyfs to duplicate first glyph.");
    }
    let maxFunctionDefs = 0;
    let maxSizeOfInstructions = 0;
    if (version >= 0x00010000 && tables.maxp.length >= 22) {
      font.pos += 8;
      const maxZones = font.getUint16();
      if (maxZones > 2) {
        tables.maxp.data[14] = 0;
        tables.maxp.data[15] = 2;
      }
      font.pos += 4;
      maxFunctionDefs = font.getUint16();
      font.pos += 4;
      maxSizeOfInstructions = font.getUint16();
    }
    tables.maxp.data[4] = numGlyphsOut >> 8;
    tables.maxp.data[5] = numGlyphsOut & 255;
    const hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep, tables["cvt "], maxFunctionDefs);
    if (!hintsValid) {
      delete tables.fpgm;
      delete tables.prep;
      delete tables["cvt "];
    }
    sanitizeMetrics(font, tables.hhea, tables.hmtx, tables.head, numGlyphsOut, dupFirstEntry);
    if (!tables.head) {
      throw new _util.FormatError('Required "head" table is not found');
    }
    sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
    let missingGlyphs = Object.create(null);
    if (isTrueType) {
      const isGlyphLocationsLong = int16(tables.head.data[50], tables.head.data[51]);
      const glyphsInfo = sanitizeGlyphLocations(tables.loca, tables.glyf, numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry, maxSizeOfInstructions);
      missingGlyphs = glyphsInfo.missingGlyphs;
      if (version >= 0x00010000 && tables.maxp.length >= 22) {
        tables.maxp.data[26] = glyphsInfo.maxSizeOfInstructions >> 8;
        tables.maxp.data[27] = glyphsInfo.maxSizeOfInstructions & 255;
      }
    }
    if (!tables.hhea) {
      throw new _util.FormatError('Required "hhea" table is not found');
    }
    if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
      tables.hhea.data[10] = 0xff;
      tables.hhea.data[11] = 0xff;
    }
    const metricsOverride = {
      unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
      yMax: int16(tables.head.data[42], tables.head.data[43]),
      yMin: signedInt16(tables.head.data[38], tables.head.data[39]),
      ascent: signedInt16(tables.hhea.data[4], tables.hhea.data[5]),
      descent: signedInt16(tables.hhea.data[6], tables.hhea.data[7]),
      lineGap: signedInt16(tables.hhea.data[8], tables.hhea.data[9])
    };
    this.ascent = metricsOverride.ascent / metricsOverride.unitsPerEm;
    this.descent = metricsOverride.descent / metricsOverride.unitsPerEm;
    this.lineGap = metricsOverride.lineGap / metricsOverride.unitsPerEm;
    if (this.cssFontInfo && this.cssFontInfo.lineHeight) {
      this.lineHeight = this.cssFontInfo.metrics.lineHeight;
      this.lineGap = this.cssFontInfo.metrics.lineGap;
    } else {
      this.lineHeight = this.ascent - this.descent + this.lineGap;
    }
    if (tables.post) {
      readPostScriptTable(tables.post, properties, numGlyphs);
    }
    tables.post = {
      tag: "post",
      data: createPostTable(properties)
    };
    const charCodeToGlyphId = [];
    function hasGlyph(glyphId) {
      return !missingGlyphs[glyphId];
    }
    if (properties.composite) {
      const cidToGidMap = properties.cidToGidMap || [];
      const isCidToGidMapEmpty = cidToGidMap.length === 0;
      properties.cMap.forEach(function (charCode, cid) {
        if (typeof cid === "string") {
          cid = convertCidString(charCode, cid, true);
        }
        if (cid > 0xffff) {
          throw new _util.FormatError("Max size of CID is 65,535");
        }
        let glyphId = -1;
        if (isCidToGidMapEmpty) {
          glyphId = cid;
        } else if (cidToGidMap[cid] !== undefined) {
          glyphId = cidToGidMap[cid];
        }
        if (glyphId >= 0 && glyphId < numGlyphs && hasGlyph(glyphId)) {
          charCodeToGlyphId[charCode] = glyphId;
        }
      });
    } else {
      const cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont, properties.hasEncoding);
      const cmapPlatformId = cmapTable.platformId;
      const cmapEncodingId = cmapTable.encodingId;
      const cmapMappings = cmapTable.mappings;
      let baseEncoding = [],
        forcePostTable = false;
      if (properties.hasEncoding && (properties.baseEncodingName === "MacRomanEncoding" || properties.baseEncodingName === "WinAnsiEncoding")) {
        baseEncoding = (0, _encodings.getEncoding)(properties.baseEncodingName);
      }
      if (properties.hasEncoding && !this.isSymbolicFont && (cmapPlatformId === 3 && cmapEncodingId === 1 || cmapPlatformId === 1 && cmapEncodingId === 0)) {
        const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
        for (let charCode = 0; charCode < 256; charCode++) {
          let glyphName;
          if (this.differences[charCode] !== undefined) {
            glyphName = this.differences[charCode];
          } else if (baseEncoding.length && baseEncoding[charCode] !== "") {
            glyphName = baseEncoding[charCode];
          } else {
            glyphName = _encodings.StandardEncoding[charCode];
          }
          if (!glyphName) {
            continue;
          }
          const standardGlyphName = (0, _fonts_utils.recoverGlyphName)(glyphName, glyphsUnicodeMap);
          let unicodeOrCharCode;
          if (cmapPlatformId === 3 && cmapEncodingId === 1) {
            unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName];
          } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
            unicodeOrCharCode = _encodings.MacRomanEncoding.indexOf(standardGlyphName);
          }
          if (unicodeOrCharCode === undefined) {
            if (!properties.glyphNames && properties.hasIncludedToUnicodeMap && !(this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap)) {
              const unicode = this.toUnicode.get(charCode);
              if (unicode) {
                unicodeOrCharCode = unicode.codePointAt(0);
              }
            }
            if (unicodeOrCharCode === undefined) {
              continue;
            }
          }
          for (const mapping of cmapMappings) {
            if (mapping.charCode !== unicodeOrCharCode) {
              continue;
            }
            charCodeToGlyphId[charCode] = mapping.glyphId;
            break;
          }
        }
      } else if (cmapPlatformId === 0) {
        for (const mapping of cmapMappings) {
          charCodeToGlyphId[mapping.charCode] = mapping.glyphId;
        }
        forcePostTable = true;
      } else {
        for (const mapping of cmapMappings) {
          let charCode = mapping.charCode;
          if (cmapPlatformId === 3 && charCode >= 0xf000 && charCode <= 0xf0ff) {
            charCode &= 0xff;
          }
          charCodeToGlyphId[charCode] = mapping.glyphId;
        }
      }
      if (properties.glyphNames && (baseEncoding.length || this.differences.length)) {
        for (let i = 0; i < 256; ++i) {
          if (!forcePostTable && charCodeToGlyphId[i] !== undefined) {
            continue;
          }
          const glyphName = this.differences[i] || baseEncoding[i];
          if (!glyphName) {
            continue;
          }
          const glyphId = properties.glyphNames.indexOf(glyphName);
          if (glyphId > 0 && hasGlyph(glyphId)) {
            charCodeToGlyphId[i] = glyphId;
          }
        }
      }
    }
    if (charCodeToGlyphId.length === 0) {
      charCodeToGlyphId[0] = 0;
    }
    let glyphZeroId = numGlyphsOut - 1;
    if (!dupFirstEntry) {
      glyphZeroId = 0;
    }
    if (!properties.cssFontInfo) {
      const newMapping = adjustMapping(charCodeToGlyphId, hasGlyph, glyphZeroId, this.toUnicode);
      this.toFontChar = newMapping.toFontChar;
      tables.cmap = {
        tag: "cmap",
        data: createCmapTable(newMapping.charCodeToGlyphId, newMapping.toUnicodeExtraMap, numGlyphsOut)
      };
      if (!tables["OS/2"] || !validateOS2Table(tables["OS/2"], font)) {
        tables["OS/2"] = {
          tag: "OS/2",
          data: createOS2Table(properties, newMapping.charCodeToGlyphId, metricsOverride)
        };
      }
    }
    if (!isTrueType) {
      try {
        cffFile = new _stream.Stream(tables["CFF "].data);
        const parser = new _cff_parser.CFFParser(cffFile, properties, _fonts_utils.SEAC_ANALYSIS_ENABLED);
        cff = parser.parse();
        cff.duplicateFirstGlyph();
        const compiler = new _cff_parser.CFFCompiler(cff);
        tables["CFF "].data = compiler.compile();
      } catch (e) {
        (0, _util.warn)("Failed to compile font " + properties.loadedName);
      }
    }
    if (!tables.name) {
      tables.name = {
        tag: "name",
        data: createNameTable(this.name)
      };
    } else {
      const [namePrototype, nameRecords] = readNameTable(tables.name);
      tables.name.data = createNameTable(name, namePrototype);
      this.psName = namePrototype[0][6] || null;
      if (!properties.composite) {
        adjustTrueTypeToUnicode(properties, this.isSymbolicFont, nameRecords);
      }
    }
    const builder = new _opentype_file_builder.OpenTypeFileBuilder(header.version);
    for (const tableTag in tables) {
      builder.addTable(tableTag, tables[tableTag].data);
    }
    return builder.toArray();
  }
  convert(fontName, font, properties) {
    properties.fixedPitch = false;
    if (properties.builtInEncoding) {
      adjustType1ToUnicode(properties, properties.builtInEncoding);
    }
    let glyphZeroId = 1;
    if (font instanceof _cff_font.CFFFont) {
      glyphZeroId = font.numGlyphs - 1;
    }
    const mapping = font.getGlyphMapping(properties);
    let newMapping = null;
    let newCharCodeToGlyphId = mapping;
    let toUnicodeExtraMap = null;
    if (!properties.cssFontInfo) {
      newMapping = adjustMapping(mapping, font.hasGlyphId.bind(font), glyphZeroId, this.toUnicode);
      this.toFontChar = newMapping.toFontChar;
      newCharCodeToGlyphId = newMapping.charCodeToGlyphId;
      toUnicodeExtraMap = newMapping.toUnicodeExtraMap;
    }
    const numGlyphs = font.numGlyphs;
    function getCharCodes(charCodeToGlyphId, glyphId) {
      let charCodes = null;
      for (const charCode in charCodeToGlyphId) {
        if (glyphId === charCodeToGlyphId[charCode]) {
          if (!charCodes) {
            charCodes = [];
          }
          charCodes.push(charCode | 0);
        }
      }
      return charCodes;
    }
    function createCharCode(charCodeToGlyphId, glyphId) {
      for (const charCode in charCodeToGlyphId) {
        if (glyphId === charCodeToGlyphId[charCode]) {
          return charCode | 0;
        }
      }
      newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] = glyphId;
      return newMapping.nextAvailableFontCharCode++;
    }
    const seacs = font.seacs;
    if (newMapping && _fonts_utils.SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
      const matrix = properties.fontMatrix || _util.FONT_IDENTITY_MATRIX;
      const charset = font.getCharset();
      const seacMap = Object.create(null);
      for (let glyphId in seacs) {
        glyphId |= 0;
        const seac = seacs[glyphId];
        const baseGlyphName = _encodings.StandardEncoding[seac[2]];
        const accentGlyphName = _encodings.StandardEncoding[seac[3]];
        const baseGlyphId = charset.indexOf(baseGlyphName);
        const accentGlyphId = charset.indexOf(accentGlyphName);
        if (baseGlyphId < 0 || accentGlyphId < 0) {
          continue;
        }
        const accentOffset = {
          x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
          y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
        };
        const charCodes = getCharCodes(mapping, glyphId);
        if (!charCodes) {
          continue;
        }
        for (const charCode of charCodes) {
          const charCodeToGlyphId = newMapping.charCodeToGlyphId;
          const baseFontCharCode = createCharCode(charCodeToGlyphId, baseGlyphId);
          const accentFontCharCode = createCharCode(charCodeToGlyphId, accentGlyphId);
          seacMap[charCode] = {
            baseFontCharCode,
            accentFontCharCode,
            accentOffset
          };
        }
      }
      properties.seacMap = seacMap;
    }
    const unitsPerEm = 1 / (properties.fontMatrix || _util.FONT_IDENTITY_MATRIX)[0];
    const builder = new _opentype_file_builder.OpenTypeFileBuilder("\x4F\x54\x54\x4F");
    builder.addTable("CFF ", font.data);
    builder.addTable("OS/2", createOS2Table(properties, newCharCodeToGlyphId));
    builder.addTable("cmap", createCmapTable(newCharCodeToGlyphId, toUnicodeExtraMap, numGlyphs));
    builder.addTable("head", "\x00\x01\x00\x00" + "\x00\x00\x10\x00" + "\x00\x00\x00\x00" + "\x5F\x0F\x3C\xF5" + "\x00\x00" + safeString16(unitsPerEm) + "\x00\x00\x00\x00\x9e\x0b\x7e\x27" + "\x00\x00\x00\x00\x9e\x0b\x7e\x27" + "\x00\x00" + safeString16(properties.descent) + "\x0F\xFF" + safeString16(properties.ascent) + string16(properties.italicAngle ? 2 : 0) + "\x00\x11" + "\x00\x00" + "\x00\x00" + "\x00\x00");
    builder.addTable("hhea", "\x00\x01\x00\x00" + safeString16(properties.ascent) + safeString16(properties.descent) + "\x00\x00" + "\xFF\xFF" + "\x00\x00" + "\x00\x00" + "\x00\x00" + safeString16(properties.capHeight) + safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + "\x00\x00" + "\x00\x00" + "\x00\x00" + "\x00\x00" + "\x00\x00" + "\x00\x00" + string16(numGlyphs));
    builder.addTable("hmtx", function fontFieldsHmtx() {
      const charstrings = font.charstrings;
      const cffWidths = font.cff ? font.cff.widths : null;
      let hmtx = "\x00\x00\x00\x00";
      for (let i = 1, ii = numGlyphs; i < ii; i++) {
        let width = 0;
        if (charstrings) {
          const charstring = charstrings[i - 1];
          width = "width" in charstring ? charstring.width : 0;
        } else if (cffWidths) {
          width = Math.ceil(cffWidths[i] || 0);
        }
        hmtx += string16(width) + string16(0);
      }
      return hmtx;
    }());
    builder.addTable("maxp", "\x00\x00\x50\x00" + string16(numGlyphs));
    builder.addTable("name", createNameTable(fontName));
    builder.addTable("post", createPostTable(properties));
    return builder.toArray();
  }
  get spaceWidth() {
    const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"];
    let width;
    for (const glyphName of possibleSpaceReplacements) {
      if (glyphName in this.widths) {
        width = this.widths[glyphName];
        break;
      }
      const glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
      const glyphUnicode = glyphsUnicodeMap[glyphName];
      let charcode = 0;
      if (this.composite && this.cMap.contains(glyphUnicode)) {
        charcode = this.cMap.lookup(glyphUnicode);
        if (typeof charcode === "string") {
          charcode = convertCidString(glyphUnicode, charcode);
        }
      }
      if (!charcode && this.toUnicode) {
        charcode = this.toUnicode.charCodeOf(glyphUnicode);
      }
      if (charcode <= 0) {
        charcode = glyphUnicode;
      }
      width = this.widths[charcode];
      if (width) {
        break;
      }
    }
    width = width || this.defaultWidth;
    return (0, _util.shadow)(this, "spaceWidth", width);
  }
  _charToGlyph(charcode, isSpace = false) {
    let glyph = this._glyphCache[charcode];
    if (glyph && glyph.isSpace === isSpace) {
      return glyph;
    }
    let fontCharCode, width, operatorListId;
    let widthCode = charcode;
    if (this.cMap && this.cMap.contains(charcode)) {
      widthCode = this.cMap.lookup(charcode);
      if (typeof widthCode === "string") {
        widthCode = convertCidString(charcode, widthCode);
      }
    }
    width = this.widths[widthCode];
    if (typeof width !== "number") {
      width = this.defaultWidth;
    }
    const vmetric = this.vmetrics && this.vmetrics[widthCode];
    let unicode = this.toUnicode.get(charcode) || charcode;
    if (typeof unicode === "number") {
      unicode = String.fromCharCode(unicode);
    }
    let isInFont = this.toFontChar[charcode] !== undefined;
    fontCharCode = this.toFontChar[charcode] || charcode;
    if (this.missingFile) {
      const glyphName = this.differences[charcode] || this.defaultEncoding[charcode];
      if ((glyphName === ".notdef" || glyphName === "") && this.type === "Type1") {
        fontCharCode = 0x20;
      }
      fontCharCode = (0, _unicode.mapSpecialUnicodeValues)(fontCharCode);
    }
    if (this.isType3Font) {
      operatorListId = fontCharCode;
    }
    let accent = null;
    if (this.seacMap && this.seacMap[charcode]) {
      isInFont = true;
      const seac = this.seacMap[charcode];
      fontCharCode = seac.baseFontCharCode;
      accent = {
        fontChar: String.fromCodePoint(seac.accentFontCharCode),
        offset: seac.accentOffset
      };
    }
    let fontChar = "";
    if (typeof fontCharCode === "number") {
      if (fontCharCode <= 0x10ffff) {
        fontChar = String.fromCodePoint(fontCharCode);
      } else {
        (0, _util.warn)(`charToGlyph - invalid fontCharCode: ${fontCharCode}`);
      }
    }
    glyph = new Glyph(charcode, fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont);
    return this._glyphCache[charcode] = glyph;
  }
  charsToGlyphs(chars) {
    let glyphs = this._charsCache[chars];
    if (glyphs) {
      return glyphs;
    }
    glyphs = [];
    if (this.cMap) {
      const c = Object.create(null),
        ii = chars.length;
      let i = 0;
      while (i < ii) {
        this.cMap.readCharCode(chars, i, c);
        const {
          charcode,
          length
        } = c;
        i += length;
        const glyph = this._charToGlyph(charcode, length === 1 && chars.charCodeAt(i - 1) === 0x20);
        glyphs.push(glyph);
      }
    } else {
      for (let i = 0, ii = chars.length; i < ii; ++i) {
        const charcode = chars.charCodeAt(i);
        const glyph = this._charToGlyph(charcode, charcode === 0x20);
        glyphs.push(glyph);
      }
    }
    return this._charsCache[chars] = glyphs;
  }
  getCharPositions(chars) {
    const positions = [];
    if (this.cMap) {
      const c = Object.create(null);
      let i = 0;
      while (i < chars.length) {
        this.cMap.readCharCode(chars, i, c);
        const length = c.length;
        positions.push([i, i + length]);
        i += length;
      }
    } else {
      for (let i = 0, ii = chars.length; i < ii; ++i) {
        positions.push([i, i + 1]);
      }
    }
    return positions;
  }
  get glyphCacheValues() {
    return Object.values(this._glyphCache);
  }
  encodeString(str) {
    const buffers = [];
    const currentBuf = [];
    const hasCurrentBufErrors = () => buffers.length % 2 === 1;
    const getCharCode = this.toUnicode instanceof _to_unicode_map.IdentityToUnicodeMap ? unicode => this.toUnicode.charCodeOf(unicode) : unicode => this.toUnicode.charCodeOf(String.fromCodePoint(unicode));
    for (let i = 0, ii = str.length; i < ii; i++) {
      const unicode = str.codePointAt(i);
      if (unicode > 0xd7ff && (unicode < 0xe000 || unicode > 0xfffd)) {
        i++;
      }
      if (this.toUnicode) {
        const charCode = getCharCode(unicode);
        if (charCode !== -1) {
          if (hasCurrentBufErrors()) {
            buffers.push(currentBuf.join(""));
            currentBuf.length = 0;
          }
          const charCodeLength = this.cMap ? this.cMap.getCharCodeLength(charCode) : 1;
          for (let j = charCodeLength - 1; j >= 0; j--) {
            currentBuf.push(String.fromCharCode(charCode >> 8 * j & 0xff));
          }
          continue;
        }
      }
      if (!hasCurrentBufErrors()) {
        buffers.push(currentBuf.join(""));
        currentBuf.length = 0;
      }
      currentBuf.push(String.fromCodePoint(unicode));
    }
    buffers.push(currentBuf.join(""));
    return buffers;
  }
}
exports.Font = Font;
class ErrorFont {
  constructor(error) {
    this.error = error;
    this.loadedName = "g_font_error";
    this.missingFile = true;
  }
  charsToGlyphs() {
    return [];
  }
  encodeString(chars) {
    return [chars];
  }
  exportData(extraProperties = false) {
    return {
      error: this.error
    };
  }
}
exports.ErrorFont = ErrorFont;

/***/ }),
/* 33 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CFFTopDict = exports.CFFStrings = exports.CFFStandardStrings = exports.CFFPrivateDict = exports.CFFParser = exports.CFFIndex = exports.CFFHeader = exports.CFFFDSelect = exports.CFFCompiler = exports.CFFCharset = exports.CFF = void 0;
var _util = __w_pdfjs_require__(2);
var _charsets = __w_pdfjs_require__(34);
var _encodings = __w_pdfjs_require__(35);
const MAX_SUBR_NESTING = 10;
const CFFStandardStrings = [".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold"];
exports.CFFStandardStrings = CFFStandardStrings;
const NUM_STANDARD_CFF_STRINGS = 391;
const CharstringValidationData = [null, {
  id: "hstem",
  min: 2,
  stackClearing: true,
  stem: true
}, null, {
  id: "vstem",
  min: 2,
  stackClearing: true,
  stem: true
}, {
  id: "vmoveto",
  min: 1,
  stackClearing: true
}, {
  id: "rlineto",
  min: 2,
  resetStack: true
}, {
  id: "hlineto",
  min: 1,
  resetStack: true
}, {
  id: "vlineto",
  min: 1,
  resetStack: true
}, {
  id: "rrcurveto",
  min: 6,
  resetStack: true
}, null, {
  id: "callsubr",
  min: 1,
  undefStack: true
}, {
  id: "return",
  min: 0,
  undefStack: true
}, null, null, {
  id: "endchar",
  min: 0,
  stackClearing: true
}, null, null, null, {
  id: "hstemhm",
  min: 2,
  stackClearing: true,
  stem: true
}, {
  id: "hintmask",
  min: 0,
  stackClearing: true
}, {
  id: "cntrmask",
  min: 0,
  stackClearing: true
}, {
  id: "rmoveto",
  min: 2,
  stackClearing: true
}, {
  id: "hmoveto",
  min: 1,
  stackClearing: true
}, {
  id: "vstemhm",
  min: 2,
  stackClearing: true,
  stem: true
}, {
  id: "rcurveline",
  min: 8,
  resetStack: true
}, {
  id: "rlinecurve",
  min: 8,
  resetStack: true
}, {
  id: "vvcurveto",
  min: 4,
  resetStack: true
}, {
  id: "hhcurveto",
  min: 4,
  resetStack: true
}, null, {
  id: "callgsubr",
  min: 1,
  undefStack: true
}, {
  id: "vhcurveto",
  min: 4,
  resetStack: true
}, {
  id: "hvcurveto",
  min: 4,
  resetStack: true
}];
const CharstringValidationData12 = [null, null, null, {
  id: "and",
  min: 2,
  stackDelta: -1
}, {
  id: "or",
  min: 2,
  stackDelta: -1
}, {
  id: "not",
  min: 1,
  stackDelta: 0
}, null, null, null, {
  id: "abs",
  min: 1,
  stackDelta: 0
}, {
  id: "add",
  min: 2,
  stackDelta: -1,
  stackFn(stack, index) {
    stack[index - 2] = stack[index - 2] + stack[index - 1];
  }
}, {
  id: "sub",
  min: 2,
  stackDelta: -1,
  stackFn(stack, index) {
    stack[index - 2] = stack[index - 2] - stack[index - 1];
  }
}, {
  id: "div",
  min: 2,
  stackDelta: -1,
  stackFn(stack, index) {
    stack[index - 2] = stack[index - 2] / stack[index - 1];
  }
}, null, {
  id: "neg",
  min: 1,
  stackDelta: 0,
  stackFn(stack, index) {
    stack[index - 1] = -stack[index - 1];
  }
}, {
  id: "eq",
  min: 2,
  stackDelta: -1
}, null, null, {
  id: "drop",
  min: 1,
  stackDelta: -1
}, null, {
  id: "put",
  min: 2,
  stackDelta: -2
}, {
  id: "get",
  min: 1,
  stackDelta: 0
}, {
  id: "ifelse",
  min: 4,
  stackDelta: -3
}, {
  id: "random",
  min: 0,
  stackDelta: 1
}, {
  id: "mul",
  min: 2,
  stackDelta: -1,
  stackFn(stack, index) {
    stack[index - 2] = stack[index - 2] * stack[index - 1];
  }
}, null, {
  id: "sqrt",
  min: 1,
  stackDelta: 0
}, {
  id: "dup",
  min: 1,
  stackDelta: 1
}, {
  id: "exch",
  min: 2,
  stackDelta: 0
}, {
  id: "index",
  min: 2,
  stackDelta: 0
}, {
  id: "roll",
  min: 3,
  stackDelta: -2
}, null, null, null, {
  id: "hflex",
  min: 7,
  resetStack: true
}, {
  id: "flex",
  min: 13,
  resetStack: true
}, {
  id: "hflex1",
  min: 9,
  resetStack: true
}, {
  id: "flex1",
  min: 11,
  resetStack: true
}];
class CFFParser {
  constructor(file, properties, seacAnalysisEnabled) {
    this.bytes = file.getBytes();
    this.properties = properties;
    this.seacAnalysisEnabled = !!seacAnalysisEnabled;
  }
  parse() {
    const properties = this.properties;
    const cff = new CFF();
    this.cff = cff;
    const header = this.parseHeader();
    const nameIndex = this.parseIndex(header.endPos);
    const topDictIndex = this.parseIndex(nameIndex.endPos);
    const stringIndex = this.parseIndex(topDictIndex.endPos);
    const globalSubrIndex = this.parseIndex(stringIndex.endPos);
    const topDictParsed = this.parseDict(topDictIndex.obj.get(0));
    const topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
    cff.header = header.obj;
    cff.names = this.parseNameIndex(nameIndex.obj);
    cff.strings = this.parseStringIndex(stringIndex.obj);
    cff.topDict = topDict;
    cff.globalSubrIndex = globalSubrIndex.obj;
    this.parsePrivateDict(cff.topDict);
    cff.isCIDFont = topDict.hasName("ROS");
    const charStringOffset = topDict.getByName("CharStrings");
    const charStringIndex = this.parseIndex(charStringOffset).obj;
    const fontMatrix = topDict.getByName("FontMatrix");
    if (fontMatrix) {
      properties.fontMatrix = fontMatrix;
    }
    const fontBBox = topDict.getByName("FontBBox");
    if (fontBBox) {
      properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
      properties.descent = Math.min(fontBBox[1], fontBBox[3]);
      properties.ascentScaled = true;
    }
    let charset, encoding;
    if (cff.isCIDFont) {
      const fdArrayIndex = this.parseIndex(topDict.getByName("FDArray")).obj;
      for (let i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
        const dictRaw = fdArrayIndex.get(i);
        const fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw), cff.strings);
        this.parsePrivateDict(fontDict);
        cff.fdArray.push(fontDict);
      }
      encoding = null;
      charset = this.parseCharsets(topDict.getByName("charset"), charStringIndex.count, cff.strings, true);
      cff.fdSelect = this.parseFDSelect(topDict.getByName("FDSelect"), charStringIndex.count);
    } else {
      charset = this.parseCharsets(topDict.getByName("charset"), charStringIndex.count, cff.strings, false);
      encoding = this.parseEncoding(topDict.getByName("Encoding"), properties, cff.strings, charset.charset);
    }
    cff.charset = charset;
    cff.encoding = encoding;
    const charStringsAndSeacs = this.parseCharStrings({
      charStrings: charStringIndex,
      localSubrIndex: topDict.privateDict.subrsIndex,
      globalSubrIndex: globalSubrIndex.obj,
      fdSelect: cff.fdSelect,
      fdArray: cff.fdArray,
      privateDict: topDict.privateDict
    });
    cff.charStrings = charStringsAndSeacs.charStrings;
    cff.seacs = charStringsAndSeacs.seacs;
    cff.widths = charStringsAndSeacs.widths;
    return cff;
  }
  parseHeader() {
    let bytes = this.bytes;
    const bytesLength = bytes.length;
    let offset = 0;
    while (offset < bytesLength && bytes[offset] !== 1) {
      ++offset;
    }
    if (offset >= bytesLength) {
      throw new _util.FormatError("Invalid CFF header");
    }
    if (offset !== 0) {
      (0, _util.info)("cff data is shifted");
      bytes = bytes.subarray(offset);
      this.bytes = bytes;
    }
    const major = bytes[0];
    const minor = bytes[1];
    const hdrSize = bytes[2];
    const offSize = bytes[3];
    const header = new CFFHeader(major, minor, hdrSize, offSize);
    return {
      obj: header,
      endPos: hdrSize
    };
  }
  parseDict(dict) {
    let pos = 0;
    function parseOperand() {
      let value = dict[pos++];
      if (value === 30) {
        return parseFloatOperand();
      } else if (value === 28) {
        value = dict[pos++];
        value = (value << 24 | dict[pos++] << 16) >> 16;
        return value;
      } else if (value === 29) {
        value = dict[pos++];
        value = value << 8 | dict[pos++];
        value = value << 8 | dict[pos++];
        value = value << 8 | dict[pos++];
        return value;
      } else if (value >= 32 && value <= 246) {
        return value - 139;
      } else if (value >= 247 && value <= 250) {
        return (value - 247) * 256 + dict[pos++] + 108;
      } else if (value >= 251 && value <= 254) {
        return -((value - 251) * 256) - dict[pos++] - 108;
      }
      (0, _util.warn)('CFFParser_parseDict: "' + value + '" is a reserved command.');
      return NaN;
    }
    function parseFloatOperand() {
      let str = "";
      const eof = 15;
      const lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"];
      const length = dict.length;
      while (pos < length) {
        const b = dict[pos++];
        const b1 = b >> 4;
        const b2 = b & 15;
        if (b1 === eof) {
          break;
        }
        str += lookup[b1];
        if (b2 === eof) {
          break;
        }
        str += lookup[b2];
      }
      return parseFloat(str);
    }
    let operands = [];
    const entries = [];
    pos = 0;
    const end = dict.length;
    while (pos < end) {
      let b = dict[pos];
      if (b <= 21) {
        if (b === 12) {
          b = b << 8 | dict[++pos];
        }
        entries.push([b, operands]);
        operands = [];
        ++pos;
      } else {
        operands.push(parseOperand());
      }
    }
    return entries;
  }
  parseIndex(pos) {
    const cffIndex = new CFFIndex();
    const bytes = this.bytes;
    const count = bytes[pos++] << 8 | bytes[pos++];
    const offsets = [];
    let end = pos;
    let i, ii;
    if (count !== 0) {
      const offsetSize = bytes[pos++];
      const startPos = pos + (count + 1) * offsetSize - 1;
      for (i = 0, ii = count + 1; i < ii; ++i) {
        let offset = 0;
        for (let j = 0; j < offsetSize; ++j) {
          offset <<= 8;
          offset += bytes[pos++];
        }
        offsets.push(startPos + offset);
      }
      end = offsets[count];
    }
    for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
      const offsetStart = offsets[i];
      const offsetEnd = offsets[i + 1];
      cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
    }
    return {
      obj: cffIndex,
      endPos: end
    };
  }
  parseNameIndex(index) {
    const names = [];
    for (let i = 0, ii = index.count; i < ii; ++i) {
      const name = index.get(i);
      names.push((0, _util.bytesToString)(name));
    }
    return names;
  }
  parseStringIndex(index) {
    const strings = new CFFStrings();
    for (let i = 0, ii = index.count; i < ii; ++i) {
      const data = index.get(i);
      strings.add((0, _util.bytesToString)(data));
    }
    return strings;
  }
  createDict(Type, dict, strings) {
    const cffDict = new Type(strings);
    for (const [key, value] of dict) {
      cffDict.setByKey(key, value);
    }
    return cffDict;
  }
  parseCharString(state, data, localSubrIndex, globalSubrIndex) {
    if (!data || state.callDepth > MAX_SUBR_NESTING) {
      return false;
    }
    let stackSize = state.stackSize;
    const stack = state.stack;
    let length = data.length;
    for (let j = 0; j < length;) {
      const value = data[j++];
      let validationCommand = null;
      if (value === 12) {
        const q = data[j++];
        if (q === 0) {
          data[j - 2] = 139;
          data[j - 1] = 22;
          stackSize = 0;
        } else {
          validationCommand = CharstringValidationData12[q];
        }
      } else if (value === 28) {
        stack[stackSize] = (data[j] << 24 | data[j + 1] << 16) >> 16;
        j += 2;
        stackSize++;
      } else if (value === 14) {
        if (stackSize >= 4) {
          stackSize -= 4;
          if (this.seacAnalysisEnabled) {
            state.seac = stack.slice(stackSize, stackSize + 4);
            return false;
          }
        }
        validationCommand = CharstringValidationData[value];
      } else if (value >= 32 && value <= 246) {
        stack[stackSize] = value - 139;
        stackSize++;
      } else if (value >= 247 && value <= 254) {
        stack[stackSize] = value < 251 ? (value - 247 << 8) + data[j] + 108 : -(value - 251 << 8) - data[j] - 108;
        j++;
        stackSize++;
      } else if (value === 255) {
        stack[stackSize] = (data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3]) / 65536;
        j += 4;
        stackSize++;
      } else if (value === 19 || value === 20) {
        state.hints += stackSize >> 1;
        j += state.hints + 7 >> 3;
        stackSize %= 2;
        validationCommand = CharstringValidationData[value];
      } else if (value === 10 || value === 29) {
        let subrsIndex;
        if (value === 10) {
          subrsIndex = localSubrIndex;
        } else {
          subrsIndex = globalSubrIndex;
        }
        if (!subrsIndex) {
          validationCommand = CharstringValidationData[value];
          (0, _util.warn)("Missing subrsIndex for " + validationCommand.id);
          return false;
        }
        let bias = 32768;
        if (subrsIndex.count < 1240) {
          bias = 107;
        } else if (subrsIndex.count < 33900) {
          bias = 1131;
        }
        const subrNumber = stack[--stackSize] + bias;
        if (subrNumber < 0 || subrNumber >= subrsIndex.count || isNaN(subrNumber)) {
          validationCommand = CharstringValidationData[value];
          (0, _util.warn)("Out of bounds subrIndex for " + validationCommand.id);
          return false;
        }
        state.stackSize = stackSize;
        state.callDepth++;
        const valid = this.parseCharString(state, subrsIndex.get(subrNumber), localSubrIndex, globalSubrIndex);
        if (!valid) {
          return false;
        }
        state.callDepth--;
        stackSize = state.stackSize;
        continue;
      } else if (value === 11) {
        state.stackSize = stackSize;
        return true;
      } else if (value === 0 && j === data.length) {
        data[j - 1] = 14;
        validationCommand = CharstringValidationData[14];
      } else if (value === 9) {
        data.copyWithin(j - 1, j, -1);
        j -= 1;
        length -= 1;
        continue;
      } else {
        validationCommand = CharstringValidationData[value];
      }
      if (validationCommand) {
        if (validationCommand.stem) {
          state.hints += stackSize >> 1;
          if (value === 3 || value === 23) {
            state.hasVStems = true;
          } else if (state.hasVStems && (value === 1 || value === 18)) {
            (0, _util.warn)("CFF stem hints are in wrong order");
            data[j - 1] = value === 1 ? 3 : 23;
          }
        }
        if ("min" in validationCommand) {
          if (!state.undefStack && stackSize < validationCommand.min) {
            (0, _util.warn)("Not enough parameters for " + validationCommand.id + "; actual: " + stackSize + ", expected: " + validationCommand.min);
            if (stackSize === 0) {
              data[j - 1] = 14;
              return true;
            }
            return false;
          }
        }
        if (state.firstStackClearing && validationCommand.stackClearing) {
          state.firstStackClearing = false;
          stackSize -= validationCommand.min;
          if (stackSize >= 2 && validationCommand.stem) {
            stackSize %= 2;
          } else if (stackSize > 1) {
            (0, _util.warn)("Found too many parameters for stack-clearing command");
          }
          if (stackSize > 0) {
            state.width = stack[stackSize - 1];
          }
        }
        if ("stackDelta" in validationCommand) {
          if ("stackFn" in validationCommand) {
            validationCommand.stackFn(stack, stackSize);
          }
          stackSize += validationCommand.stackDelta;
        } else if (validationCommand.stackClearing) {
          stackSize = 0;
        } else if (validationCommand.resetStack) {
          stackSize = 0;
          state.undefStack = false;
        } else if (validationCommand.undefStack) {
          stackSize = 0;
          state.undefStack = true;
          state.firstStackClearing = false;
        }
      }
    }
    if (length < data.length) {
      data.fill(14, length);
    }
    state.stackSize = stackSize;
    return true;
  }
  parseCharStrings({
    charStrings,
    localSubrIndex,
    globalSubrIndex,
    fdSelect,
    fdArray,
    privateDict
  }) {
    const seacs = [];
    const widths = [];
    const count = charStrings.count;
    for (let i = 0; i < count; i++) {
      const charstring = charStrings.get(i);
      const state = {
        callDepth: 0,
        stackSize: 0,
        stack: [],
        undefStack: true,
        hints: 0,
        firstStackClearing: true,
        seac: null,
        width: null,
        hasVStems: false
      };
      let valid = true;
      let localSubrToUse = null;
      let privateDictToUse = privateDict;
      if (fdSelect && fdArray.length) {
        const fdIndex = fdSelect.getFDIndex(i);
        if (fdIndex === -1) {
          (0, _util.warn)("Glyph index is not in fd select.");
          valid = false;
        }
        if (fdIndex >= fdArray.length) {
          (0, _util.warn)("Invalid fd index for glyph index.");
          valid = false;
        }
        if (valid) {
          privateDictToUse = fdArray[fdIndex].privateDict;
          localSubrToUse = privateDictToUse.subrsIndex;
        }
      } else if (localSubrIndex) {
        localSubrToUse = localSubrIndex;
      }
      if (valid) {
        valid = this.parseCharString(state, charstring, localSubrToUse, globalSubrIndex);
      }
      if (state.width !== null) {
        const nominalWidth = privateDictToUse.getByName("nominalWidthX");
        widths[i] = nominalWidth + state.width;
      } else {
        const defaultWidth = privateDictToUse.getByName("defaultWidthX");
        widths[i] = defaultWidth;
      }
      if (state.seac !== null) {
        seacs[i] = state.seac;
      }
      if (!valid) {
        charStrings.set(i, new Uint8Array([14]));
      }
    }
    return {
      charStrings,
      seacs,
      widths
    };
  }
  emptyPrivateDictionary(parentDict) {
    const privateDict = this.createDict(CFFPrivateDict, [], parentDict.strings);
    parentDict.setByKey(18, [0, 0]);
    parentDict.privateDict = privateDict;
  }
  parsePrivateDict(parentDict) {
    if (!parentDict.hasName("Private")) {
      this.emptyPrivateDictionary(parentDict);
      return;
    }
    const privateOffset = parentDict.getByName("Private");
    if (!Array.isArray(privateOffset) || privateOffset.length !== 2) {
      parentDict.removeByName("Private");
      return;
    }
    const size = privateOffset[0];
    const offset = privateOffset[1];
    if (size === 0 || offset >= this.bytes.length) {
      this.emptyPrivateDictionary(parentDict);
      return;
    }
    const privateDictEnd = offset + size;
    const dictData = this.bytes.subarray(offset, privateDictEnd);
    const dict = this.parseDict(dictData);
    const privateDict = this.createDict(CFFPrivateDict, dict, parentDict.strings);
    parentDict.privateDict = privateDict;
    if (privateDict.getByName("ExpansionFactor") === 0) {
      privateDict.setByName("ExpansionFactor", 0.06);
    }
    if (!privateDict.getByName("Subrs")) {
      return;
    }
    const subrsOffset = privateDict.getByName("Subrs");
    const relativeOffset = offset + subrsOffset;
    if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
      this.emptyPrivateDictionary(parentDict);
      return;
    }
    const subrsIndex = this.parseIndex(relativeOffset);
    privateDict.subrsIndex = subrsIndex.obj;
  }
  parseCharsets(pos, length, strings, cid) {
    if (pos === 0) {
      return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, _charsets.ISOAdobeCharset);
    } else if (pos === 1) {
      return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, _charsets.ExpertCharset);
    } else if (pos === 2) {
      return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, _charsets.ExpertSubsetCharset);
    }
    const bytes = this.bytes;
    const start = pos;
    const format = bytes[pos++];
    const charset = [cid ? 0 : ".notdef"];
    let id, count, i;
    length -= 1;
    switch (format) {
      case 0:
        for (i = 0; i < length; i++) {
          id = bytes[pos++] << 8 | bytes[pos++];
          charset.push(cid ? id : strings.get(id));
        }
        break;
      case 1:
        while (charset.length <= length) {
          id = bytes[pos++] << 8 | bytes[pos++];
          count = bytes[pos++];
          for (i = 0; i <= count; i++) {
            charset.push(cid ? id++ : strings.get(id++));
          }
        }
        break;
      case 2:
        while (charset.length <= length) {
          id = bytes[pos++] << 8 | bytes[pos++];
          count = bytes[pos++] << 8 | bytes[pos++];
          for (i = 0; i <= count; i++) {
            charset.push(cid ? id++ : strings.get(id++));
          }
        }
        break;
      default:
        throw new _util.FormatError("Unknown charset format");
    }
    const end = pos;
    const raw = bytes.subarray(start, end);
    return new CFFCharset(false, format, charset, raw);
  }
  parseEncoding(pos, properties, strings, charset) {
    const encoding = Object.create(null);
    const bytes = this.bytes;
    let predefined = false;
    let format, i, ii;
    let raw = null;
    function readSupplement() {
      const supplementsCount = bytes[pos++];
      for (i = 0; i < supplementsCount; i++) {
        const code = bytes[pos++];
        const sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
        encoding[code] = charset.indexOf(strings.get(sid));
      }
    }
    if (pos === 0 || pos === 1) {
      predefined = true;
      format = pos;
      const baseEncoding = pos ? _encodings.ExpertEncoding : _encodings.StandardEncoding;
      for (i = 0, ii = charset.length; i < ii; i++) {
        const index = baseEncoding.indexOf(charset[i]);
        if (index !== -1) {
          encoding[index] = i;
        }
      }
    } else {
      const dataStart = pos;
      format = bytes[pos++];
      switch (format & 0x7f) {
        case 0:
          const glyphsCount = bytes[pos++];
          for (i = 1; i <= glyphsCount; i++) {
            encoding[bytes[pos++]] = i;
          }
          break;
        case 1:
          const rangesCount = bytes[pos++];
          let gid = 1;
          for (i = 0; i < rangesCount; i++) {
            const start = bytes[pos++];
            const left = bytes[pos++];
            for (let j = start; j <= start + left; j++) {
              encoding[j] = gid++;
            }
          }
          break;
        default:
          throw new _util.FormatError(`Unknown encoding format: ${format} in CFF`);
      }
      const dataEnd = pos;
      if (format & 0x80) {
        bytes[dataStart] &= 0x7f;
        readSupplement();
      }
      raw = bytes.subarray(dataStart, dataEnd);
    }
    format &= 0x7f;
    return new CFFEncoding(predefined, format, encoding, raw);
  }
  parseFDSelect(pos, length) {
    const bytes = this.bytes;
    const format = bytes[pos++];
    const fdSelect = [];
    let i;
    switch (format) {
      case 0:
        for (i = 0; i < length; ++i) {
          const id = bytes[pos++];
          fdSelect.push(id);
        }
        break;
      case 3:
        const rangesCount = bytes[pos++] << 8 | bytes[pos++];
        for (i = 0; i < rangesCount; ++i) {
          let first = bytes[pos++] << 8 | bytes[pos++];
          if (i === 0 && first !== 0) {
            (0, _util.warn)("parseFDSelect: The first range must have a first GID of 0" + " -- trying to recover.");
            first = 0;
          }
          const fdIndex = bytes[pos++];
          const next = bytes[pos] << 8 | bytes[pos + 1];
          for (let j = first; j < next; ++j) {
            fdSelect.push(fdIndex);
          }
        }
        pos += 2;
        break;
      default:
        throw new _util.FormatError(`parseFDSelect: Unknown format "${format}".`);
    }
    if (fdSelect.length !== length) {
      throw new _util.FormatError("parseFDSelect: Invalid font data.");
    }
    return new CFFFDSelect(format, fdSelect);
  }
}
exports.CFFParser = CFFParser;
class CFF {
  constructor() {
    this.header = null;
    this.names = [];
    this.topDict = null;
    this.strings = new CFFStrings();
    this.globalSubrIndex = null;
    this.encoding = null;
    this.charset = null;
    this.charStrings = null;
    this.fdArray = [];
    this.fdSelect = null;
    this.isCIDFont = false;
  }
  duplicateFirstGlyph() {
    if (this.charStrings.count >= 65535) {
      (0, _util.warn)("Not enough space in charstrings to duplicate first glyph.");
      return;
    }
    const glyphZero = this.charStrings.get(0);
    this.charStrings.add(glyphZero);
    if (this.isCIDFont) {
      this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0]);
    }
  }
  hasGlyphId(id) {
    if (id < 0 || id >= this.charStrings.count) {
      return false;
    }
    const glyph = this.charStrings.get(id);
    return glyph.length > 0;
  }
}
exports.CFF = CFF;
class CFFHeader {
  constructor(major, minor, hdrSize, offSize) {
    this.major = major;
    this.minor = minor;
    this.hdrSize = hdrSize;
    this.offSize = offSize;
  }
}
exports.CFFHeader = CFFHeader;
class CFFStrings {
  constructor() {
    this.strings = [];
  }
  get(index) {
    if (index >= 0 && index <= NUM_STANDARD_CFF_STRINGS - 1) {
      return CFFStandardStrings[index];
    }
    if (index - NUM_STANDARD_CFF_STRINGS <= this.strings.length) {
      return this.strings[index - NUM_STANDARD_CFF_STRINGS];
    }
    return CFFStandardStrings[0];
  }
  getSID(str) {
    let index = CFFStandardStrings.indexOf(str);
    if (index !== -1) {
      return index;
    }
    index = this.strings.indexOf(str);
    if (index !== -1) {
      return index + NUM_STANDARD_CFF_STRINGS;
    }
    return -1;
  }
  add(value) {
    this.strings.push(value);
  }
  get count() {
    return this.strings.length;
  }
}
exports.CFFStrings = CFFStrings;
class CFFIndex {
  constructor() {
    this.objects = [];
    this.length = 0;
  }
  add(data) {
    this.length += data.length;
    this.objects.push(data);
  }
  set(index, data) {
    this.length += data.length - this.objects[index].length;
    this.objects[index] = data;
  }
  get(index) {
    return this.objects[index];
  }
  get count() {
    return this.objects.length;
  }
}
exports.CFFIndex = CFFIndex;
class CFFDict {
  constructor(tables, strings) {
    this.keyToNameMap = tables.keyToNameMap;
    this.nameToKeyMap = tables.nameToKeyMap;
    this.defaults = tables.defaults;
    this.types = tables.types;
    this.opcodes = tables.opcodes;
    this.order = tables.order;
    this.strings = strings;
    this.values = Object.create(null);
  }
  setByKey(key, value) {
    if (!(key in this.keyToNameMap)) {
      return false;
    }
    if (value.length === 0) {
      return true;
    }
    for (const val of value) {
      if (isNaN(val)) {
        (0, _util.warn)(`Invalid CFFDict value: "${value}" for key "${key}".`);
        return true;
      }
    }
    const type = this.types[key];
    if (type === "num" || type === "sid" || type === "offset") {
      value = value[0];
    }
    this.values[key] = value;
    return true;
  }
  setByName(name, value) {
    if (!(name in this.nameToKeyMap)) {
      throw new _util.FormatError(`Invalid dictionary name "${name}"`);
    }
    this.values[this.nameToKeyMap[name]] = value;
  }
  hasName(name) {
    return this.nameToKeyMap[name] in this.values;
  }
  getByName(name) {
    if (!(name in this.nameToKeyMap)) {
      throw new _util.FormatError(`Invalid dictionary name ${name}"`);
    }
    const key = this.nameToKeyMap[name];
    if (!(key in this.values)) {
      return this.defaults[key];
    }
    return this.values[key];
  }
  removeByName(name) {
    delete this.values[this.nameToKeyMap[name]];
  }
  static createTables(layout) {
    const tables = {
      keyToNameMap: {},
      nameToKeyMap: {},
      defaults: {},
      types: {},
      opcodes: {},
      order: []
    };
    for (const entry of layout) {
      const key = Array.isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
      tables.keyToNameMap[key] = entry[1];
      tables.nameToKeyMap[entry[1]] = key;
      tables.types[key] = entry[2];
      tables.defaults[key] = entry[3];
      tables.opcodes[key] = Array.isArray(entry[0]) ? entry[0] : [entry[0]];
      tables.order.push(key);
    }
    return tables;
  }
}
const CFFTopDictLayout = [[[12, 30], "ROS", ["sid", "sid", "num"], null], [[12, 20], "SyntheticBase", "num", null], [0, "version", "sid", null], [1, "Notice", "sid", null], [[12, 0], "Copyright", "sid", null], [2, "FullName", "sid", null], [3, "FamilyName", "sid", null], [4, "Weight", "sid", null], [[12, 1], "isFixedPitch", "num", 0], [[12, 2], "ItalicAngle", "num", 0], [[12, 3], "UnderlinePosition", "num", -100], [[12, 4], "UnderlineThickness", "num", 50], [[12, 5], "PaintType", "num", 0], [[12, 6], "CharstringType", "num", 2], [[12, 7], "FontMatrix", ["num", "num", "num", "num", "num", "num"], [0.001, 0, 0, 0.001, 0, 0]], [13, "UniqueID", "num", null], [5, "FontBBox", ["num", "num", "num", "num"], [0, 0, 0, 0]], [[12, 8], "StrokeWidth", "num", 0], [14, "XUID", "array", null], [15, "charset", "offset", 0], [16, "Encoding", "offset", 0], [17, "CharStrings", "offset", 0], [18, "Private", ["offset", "offset"], null], [[12, 21], "PostScript", "sid", null], [[12, 22], "BaseFontName", "sid", null], [[12, 23], "BaseFontBlend", "delta", null], [[12, 31], "CIDFontVersion", "num", 0], [[12, 32], "CIDFontRevision", "num", 0], [[12, 33], "CIDFontType", "num", 0], [[12, 34], "CIDCount", "num", 8720], [[12, 35], "UIDBase", "num", null], [[12, 37], "FDSelect", "offset", null], [[12, 36], "FDArray", "offset", null], [[12, 38], "FontName", "sid", null]];
class CFFTopDict extends CFFDict {
  static get tables() {
    return (0, _util.shadow)(this, "tables", this.createTables(CFFTopDictLayout));
  }
  constructor(strings) {
    super(CFFTopDict.tables, strings);
    this.privateDict = null;
  }
}
exports.CFFTopDict = CFFTopDict;
const CFFPrivateDictLayout = [[6, "BlueValues", "delta", null], [7, "OtherBlues", "delta", null], [8, "FamilyBlues", "delta", null], [9, "FamilyOtherBlues", "delta", null], [[12, 9], "BlueScale", "num", 0.039625], [[12, 10], "BlueShift", "num", 7], [[12, 11], "BlueFuzz", "num", 1], [10, "StdHW", "num", null], [11, "StdVW", "num", null], [[12, 12], "StemSnapH", "delta", null], [[12, 13], "StemSnapV", "delta", null], [[12, 14], "ForceBold", "num", 0], [[12, 17], "LanguageGroup", "num", 0], [[12, 18], "ExpansionFactor", "num", 0.06], [[12, 19], "initialRandomSeed", "num", 0], [20, "defaultWidthX", "num", 0], [21, "nominalWidthX", "num", 0], [19, "Subrs", "offset", null]];
class CFFPrivateDict extends CFFDict {
  static get tables() {
    return (0, _util.shadow)(this, "tables", this.createTables(CFFPrivateDictLayout));
  }
  constructor(strings) {
    super(CFFPrivateDict.tables, strings);
    this.subrsIndex = null;
  }
}
exports.CFFPrivateDict = CFFPrivateDict;
const CFFCharsetPredefinedTypes = {
  ISO_ADOBE: 0,
  EXPERT: 1,
  EXPERT_SUBSET: 2
};
class CFFCharset {
  constructor(predefined, format, charset, raw) {
    this.predefined = predefined;
    this.format = format;
    this.charset = charset;
    this.raw = raw;
  }
}
exports.CFFCharset = CFFCharset;
class CFFEncoding {
  constructor(predefined, format, encoding, raw) {
    this.predefined = predefined;
    this.format = format;
    this.encoding = encoding;
    this.raw = raw;
  }
}
class CFFFDSelect {
  constructor(format, fdSelect) {
    this.format = format;
    this.fdSelect = fdSelect;
  }
  getFDIndex(glyphIndex) {
    if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
      return -1;
    }
    return this.fdSelect[glyphIndex];
  }
}
exports.CFFFDSelect = CFFFDSelect;
class CFFOffsetTracker {
  constructor() {
    this.offsets = Object.create(null);
  }
  isTracking(key) {
    return key in this.offsets;
  }
  track(key, location) {
    if (key in this.offsets) {
      throw new _util.FormatError(`Already tracking location of ${key}`);
    }
    this.offsets[key] = location;
  }
  offset(value) {
    for (const key in this.offsets) {
      this.offsets[key] += value;
    }
  }
  setEntryLocation(key, values, output) {
    if (!(key in this.offsets)) {
      throw new _util.FormatError(`Not tracking location of ${key}`);
    }
    const data = output.data;
    const dataOffset = this.offsets[key];
    const size = 5;
    for (let i = 0, ii = values.length; i < ii; ++i) {
      const offset0 = i * size + dataOffset;
      const offset1 = offset0 + 1;
      const offset2 = offset0 + 2;
      const offset3 = offset0 + 3;
      const offset4 = offset0 + 4;
      if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
        throw new _util.FormatError("writing to an offset that is not empty");
      }
      const value = values[i];
      data[offset0] = 0x1d;
      data[offset1] = value >> 24 & 0xff;
      data[offset2] = value >> 16 & 0xff;
      data[offset3] = value >> 8 & 0xff;
      data[offset4] = value & 0xff;
    }
  }
}
class CFFCompiler {
  constructor(cff) {
    this.cff = cff;
  }
  compile() {
    const cff = this.cff;
    const output = {
      data: [],
      length: 0,
      add(data) {
        this.data = this.data.concat(data);
        this.length = this.data.length;
      }
    };
    const header = this.compileHeader(cff.header);
    output.add(header);
    const nameIndex = this.compileNameIndex(cff.names);
    output.add(nameIndex);
    if (cff.isCIDFont) {
      if (cff.topDict.hasName("FontMatrix")) {
        const base = cff.topDict.getByName("FontMatrix");
        cff.topDict.removeByName("FontMatrix");
        for (const subDict of cff.fdArray) {
          let matrix = base.slice(0);
          if (subDict.hasName("FontMatrix")) {
            matrix = _util.Util.transform(matrix, subDict.getByName("FontMatrix"));
          }
          subDict.setByName("FontMatrix", matrix);
        }
      }
    }
    const xuid = cff.topDict.getByName("XUID");
    if (xuid && xuid.length > 16) {
      cff.topDict.removeByName("XUID");
    }
    cff.topDict.setByName("charset", 0);
    let compiled = this.compileTopDicts([cff.topDict], output.length, cff.isCIDFont);
    output.add(compiled.output);
    const topDictTracker = compiled.trackers[0];
    const stringIndex = this.compileStringIndex(cff.strings.strings);
    output.add(stringIndex);
    const globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
    output.add(globalSubrIndex);
    if (cff.encoding && cff.topDict.hasName("Encoding")) {
      if (cff.encoding.predefined) {
        topDictTracker.setEntryLocation("Encoding", [cff.encoding.format], output);
      } else {
        const encoding = this.compileEncoding(cff.encoding);
        topDictTracker.setEntryLocation("Encoding", [output.length], output);
        output.add(encoding);
      }
    }
    const charset = this.compileCharset(cff.charset, cff.charStrings.count, cff.strings, cff.isCIDFont);
    topDictTracker.setEntryLocation("charset", [output.length], output);
    output.add(charset);
    const charStrings = this.compileCharStrings(cff.charStrings);
    topDictTracker.setEntryLocation("CharStrings", [output.length], output);
    output.add(charStrings);
    if (cff.isCIDFont) {
      topDictTracker.setEntryLocation("FDSelect", [output.length], output);
      const fdSelect = this.compileFDSelect(cff.fdSelect);
      output.add(fdSelect);
      compiled = this.compileTopDicts(cff.fdArray, output.length, true);
      topDictTracker.setEntryLocation("FDArray", [output.length], output);
      output.add(compiled.output);
      const fontDictTrackers = compiled.trackers;
      this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
    }
    this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
    output.add([0]);
    return output.data;
  }
  encodeNumber(value) {
    if (Number.isInteger(value)) {
      return this.encodeInteger(value);
    }
    return this.encodeFloat(value);
  }
  static get EncodeFloatRegExp() {
    return (0, _util.shadow)(this, "EncodeFloatRegExp", /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/);
  }
  encodeFloat(num) {
    let value = num.toString();
    const m = CFFCompiler.EncodeFloatRegExp.exec(value);
    if (m) {
      const epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
      value = (Math.round(num * epsilon) / epsilon).toString();
    }
    let nibbles = "";
    let i, ii;
    for (i = 0, ii = value.length; i < ii; ++i) {
      const a = value[i];
      if (a === "e") {
        nibbles += value[++i] === "-" ? "c" : "b";
      } else if (a === ".") {
        nibbles += "a";
      } else if (a === "-") {
        nibbles += "e";
      } else {
        nibbles += a;
      }
    }
    nibbles += nibbles.length & 1 ? "f" : "ff";
    const out = [30];
    for (i = 0, ii = nibbles.length; i < ii; i += 2) {
      out.push(parseInt(nibbles.substring(i, i + 2), 16));
    }
    return out;
  }
  encodeInteger(value) {
    let code;
    if (value >= -107 && value <= 107) {
      code = [value + 139];
    } else if (value >= 108 && value <= 1131) {
      value -= 108;
      code = [(value >> 8) + 247, value & 0xff];
    } else if (value >= -1131 && value <= -108) {
      value = -value - 108;
      code = [(value >> 8) + 251, value & 0xff];
    } else if (value >= -32768 && value <= 32767) {
      code = [0x1c, value >> 8 & 0xff, value & 0xff];
    } else {
      code = [0x1d, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff];
    }
    return code;
  }
  compileHeader(header) {
    return [header.major, header.minor, 4, header.offSize];
  }
  compileNameIndex(names) {
    const nameIndex = new CFFIndex();
    for (const name of names) {
      const length = Math.min(name.length, 127);
      let sanitizedName = new Array(length);
      for (let j = 0; j < length; j++) {
        let char = name[j];
        if (char < "!" || char > "~" || char === "[" || char === "]" || char === "(" || char === ")" || char === "{" || char === "}" || char === "<" || char === ">" || char === "/" || char === "%") {
          char = "_";
        }
        sanitizedName[j] = char;
      }
      sanitizedName = sanitizedName.join("");
      if (sanitizedName === "") {
        sanitizedName = "Bad_Font_Name";
      }
      nameIndex.add((0, _util.stringToBytes)(sanitizedName));
    }
    return this.compileIndex(nameIndex);
  }
  compileTopDicts(dicts, length, removeCidKeys) {
    const fontDictTrackers = [];
    let fdArrayIndex = new CFFIndex();
    for (const fontDict of dicts) {
      if (removeCidKeys) {
        fontDict.removeByName("CIDFontVersion");
        fontDict.removeByName("CIDFontRevision");
        fontDict.removeByName("CIDFontType");
        fontDict.removeByName("CIDCount");
        fontDict.removeByName("UIDBase");
      }
      const fontDictTracker = new CFFOffsetTracker();
      const fontDictData = this.compileDict(fontDict, fontDictTracker);
      fontDictTrackers.push(fontDictTracker);
      fdArrayIndex.add(fontDictData);
      fontDictTracker.offset(length);
    }
    fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
    return {
      trackers: fontDictTrackers,
      output: fdArrayIndex
    };
  }
  compilePrivateDicts(dicts, trackers, output) {
    for (let i = 0, ii = dicts.length; i < ii; ++i) {
      const fontDict = dicts[i];
      const privateDict = fontDict.privateDict;
      if (!privateDict || !fontDict.hasName("Private")) {
        throw new _util.FormatError("There must be a private dictionary.");
      }
      const privateDictTracker = new CFFOffsetTracker();
      const privateDictData = this.compileDict(privateDict, privateDictTracker);
      let outputLength = output.length;
      privateDictTracker.offset(outputLength);
      if (!privateDictData.length) {
        outputLength = 0;
      }
      trackers[i].setEntryLocation("Private", [privateDictData.length, outputLength], output);
      output.add(privateDictData);
      if (privateDict.subrsIndex && privateDict.hasName("Subrs")) {
        const subrs = this.compileIndex(privateDict.subrsIndex);
        privateDictTracker.setEntryLocation("Subrs", [privateDictData.length], output);
        output.add(subrs);
      }
    }
  }
  compileDict(dict, offsetTracker) {
    const out = [];
    for (const key of dict.order) {
      if (!(key in dict.values)) {
        continue;
      }
      let values = dict.values[key];
      let types = dict.types[key];
      if (!Array.isArray(types)) {
        types = [types];
      }
      if (!Array.isArray(values)) {
        values = [values];
      }
      if (values.length === 0) {
        continue;
      }
      for (let j = 0, jj = types.length; j < jj; ++j) {
        const type = types[j];
        const value = values[j];
        switch (type) {
          case "num":
          case "sid":
            out.push(...this.encodeNumber(value));
            break;
          case "offset":
            const name = dict.keyToNameMap[key];
            if (!offsetTracker.isTracking(name)) {
              offsetTracker.track(name, out.length);
            }
            out.push(0x1d, 0, 0, 0, 0);
            break;
          case "array":
          case "delta":
            out.push(...this.encodeNumber(value));
            for (let k = 1, kk = values.length; k < kk; ++k) {
              out.push(...this.encodeNumber(values[k]));
            }
            break;
          default:
            throw new _util.FormatError(`Unknown data type of ${type}`);
        }
      }
      out.push(...dict.opcodes[key]);
    }
    return out;
  }
  compileStringIndex(strings) {
    const stringIndex = new CFFIndex();
    for (const string of strings) {
      stringIndex.add((0, _util.stringToBytes)(string));
    }
    return this.compileIndex(stringIndex);
  }
  compileGlobalSubrIndex() {
    const globalSubrIndex = this.cff.globalSubrIndex;
    this.out.writeByteArray(this.compileIndex(globalSubrIndex));
  }
  compileCharStrings(charStrings) {
    const charStringsIndex = new CFFIndex();
    for (let i = 0; i < charStrings.count; i++) {
      const glyph = charStrings.get(i);
      if (glyph.length === 0) {
        charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
        continue;
      }
      charStringsIndex.add(glyph);
    }
    return this.compileIndex(charStringsIndex);
  }
  compileCharset(charset, numGlyphs, strings, isCIDFont) {
    let out;
    const numGlyphsLessNotDef = numGlyphs - 1;
    if (isCIDFont) {
      out = new Uint8Array([2, 0, 0, numGlyphsLessNotDef >> 8 & 0xff, numGlyphsLessNotDef & 0xff]);
    } else {
      const length = 1 + numGlyphsLessNotDef * 2;
      out = new Uint8Array(length);
      out[0] = 0;
      let charsetIndex = 0;
      const numCharsets = charset.charset.length;
      let warned = false;
      for (let i = 1; i < out.length; i += 2) {
        let sid = 0;
        if (charsetIndex < numCharsets) {
          const name = charset.charset[charsetIndex++];
          sid = strings.getSID(name);
          if (sid === -1) {
            sid = 0;
            if (!warned) {
              warned = true;
              (0, _util.warn)(`Couldn't find ${name} in CFF strings`);
            }
          }
        }
        out[i] = sid >> 8 & 0xff;
        out[i + 1] = sid & 0xff;
      }
    }
    return this.compileTypedArray(out);
  }
  compileEncoding(encoding) {
    return this.compileTypedArray(encoding.raw);
  }
  compileFDSelect(fdSelect) {
    const format = fdSelect.format;
    let out, i;
    switch (format) {
      case 0:
        out = new Uint8Array(1 + fdSelect.fdSelect.length);
        out[0] = format;
        for (i = 0; i < fdSelect.fdSelect.length; i++) {
          out[i + 1] = fdSelect.fdSelect[i];
        }
        break;
      case 3:
        const start = 0;
        let lastFD = fdSelect.fdSelect[0];
        const ranges = [format, 0, 0, start >> 8 & 0xff, start & 0xff, lastFD];
        for (i = 1; i < fdSelect.fdSelect.length; i++) {
          const currentFD = fdSelect.fdSelect[i];
          if (currentFD !== lastFD) {
            ranges.push(i >> 8 & 0xff, i & 0xff, currentFD);
            lastFD = currentFD;
          }
        }
        const numRanges = (ranges.length - 3) / 3;
        ranges[1] = numRanges >> 8 & 0xff;
        ranges[2] = numRanges & 0xff;
        ranges.push(i >> 8 & 0xff, i & 0xff);
        out = new Uint8Array(ranges);
        break;
    }
    return this.compileTypedArray(out);
  }
  compileTypedArray(data) {
    const out = [];
    for (let i = 0, ii = data.length; i < ii; ++i) {
      out[i] = data[i];
    }
    return out;
  }
  compileIndex(index, trackers = []) {
    const objects = index.objects;
    const count = objects.length;
    if (count === 0) {
      return [0, 0];
    }
    const data = [count >> 8 & 0xff, count & 0xff];
    let lastOffset = 1,
      i;
    for (i = 0; i < count; ++i) {
      lastOffset += objects[i].length;
    }
    let offsetSize;
    if (lastOffset < 0x100) {
      offsetSize = 1;
    } else if (lastOffset < 0x10000) {
      offsetSize = 2;
    } else if (lastOffset < 0x1000000) {
      offsetSize = 3;
    } else {
      offsetSize = 4;
    }
    data.push(offsetSize);
    let relativeOffset = 1;
    for (i = 0; i < count + 1; i++) {
      if (offsetSize === 1) {
        data.push(relativeOffset & 0xff);
      } else if (offsetSize === 2) {
        data.push(relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
      } else if (offsetSize === 3) {
        data.push(relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
      } else {
        data.push(relativeOffset >>> 24 & 0xff, relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
      }
      if (objects[i]) {
        relativeOffset += objects[i].length;
      }
    }
    for (i = 0; i < count; i++) {
      if (trackers[i]) {
        trackers[i].offset(data.length);
      }
      data.push(...objects[i]);
    }
    return data;
  }
}
exports.CFFCompiler = CFFCompiler;

/***/ }),
/* 34 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ISOAdobeCharset = exports.ExpertSubsetCharset = exports.ExpertCharset = void 0;
const ISOAdobeCharset = [".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron"];
exports.ISOAdobeCharset = ISOAdobeCharset;
const ExpertCharset = [".notdef", "space", "exclamsmall", "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "comma", "hyphen", "period", "fraction", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "colon", "semicolon", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "fi", "fl", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "onequarter", "onehalf", "threequarters", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "onesuperior", "twosuperior", "threesuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall"];
exports.ExpertCharset = ExpertCharset;
const ExpertSubsetCharset = [".notdef", "space", "dollaroldstyle", "dollarsuperior", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "comma", "hyphen", "period", "fraction", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "colon", "semicolon", "commasuperior", "threequartersemdash", "periodsuperior", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "fi", "fl", "ffi", "ffl", "parenleftinferior", "parenrightinferior", "hyphensuperior", "colonmonetary", "onefitted", "rupiah", "centoldstyle", "figuredash", "hypheninferior", "onequarter", "onehalf", "threequarters", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "onesuperior", "twosuperior", "threesuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior"];
exports.ExpertSubsetCharset = ExpertSubsetCharset;

/***/ }),
/* 35 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ZapfDingbatsEncoding = exports.WinAnsiEncoding = exports.SymbolSetEncoding = exports.StandardEncoding = exports.MacRomanEncoding = exports.ExpertEncoding = void 0;
exports.getEncoding = getEncoding;
const ExpertEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclamsmall", "Hungarumlautsmall", "", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "comma", "hyphen", "period", "fraction", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "colon", "semicolon", "commasuperior", "threequartersemdash", "periodsuperior", "questionsmall", "", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "", "", "", "isuperior", "", "", "lsuperior", "msuperior", "nsuperior", "osuperior", "", "", "rsuperior", "ssuperior", "tsuperior", "", "ff", "fi", "fl", "ffi", "ffl", "parenleftinferior", "", "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "exclamdownsmall", "centoldstyle", "Lslashsmall", "", "", "Scaronsmall", "Zcaronsmall", "Dieresissmall", "Brevesmall", "Caronsmall", "", "Dotaccentsmall", "", "", "Macronsmall", "", "", "figuredash", "hypheninferior", "", "", "Ogoneksmall", "Ringsmall", "Cedillasmall", "", "", "", "onequarter", "onehalf", "threequarters", "questiondownsmall", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "", "", "zerosuperior", "onesuperior", "twosuperior", "threesuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall"];
exports.ExpertEncoding = ExpertEncoding;
const MacExpertEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclamsmall", "Hungarumlautsmall", "centoldstyle", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "comma", "hyphen", "period", "fraction", "zerooldstyle", "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "colon", "semicolon", "", "threequartersemdash", "", "questionsmall", "", "", "", "", "Ethsmall", "", "", "onequarter", "onehalf", "threequarters", "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "", "", "", "", "", "", "ff", "fi", "fl", "ffi", "ffl", "parenleftinferior", "", "parenrightinferior", "Circumflexsmall", "hypheninferior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", "colonmonetary", "onefitted", "rupiah", "Tildesmall", "", "", "asuperior", "centsuperior", "", "", "", "", "Aacutesmall", "Agravesmall", "Acircumflexsmall", "Adieresissmall", "Atildesmall", "Aringsmall", "Ccedillasmall", "Eacutesmall", "Egravesmall", "Ecircumflexsmall", "Edieresissmall", "Iacutesmall", "Igravesmall", "Icircumflexsmall", "Idieresissmall", "Ntildesmall", "Oacutesmall", "Ogravesmall", "Ocircumflexsmall", "Odieresissmall", "Otildesmall", "Uacutesmall", "Ugravesmall", "Ucircumflexsmall", "Udieresissmall", "", "eightsuperior", "fourinferior", "threeinferior", "sixinferior", "eightinferior", "seveninferior", "Scaronsmall", "", "centinferior", "twoinferior", "", "Dieresissmall", "", "Caronsmall", "osuperior", "fiveinferior", "", "commainferior", "periodinferior", "Yacutesmall", "", "dollarinferior", "", "", "Thornsmall", "", "nineinferior", "zeroinferior", "Zcaronsmall", "AEsmall", "Oslashsmall", "questiondownsmall", "oneinferior", "Lslashsmall", "", "", "", "", "", "", "Cedillasmall", "", "", "", "", "", "OEsmall", "figuredash", "hyphensuperior", "", "", "", "", "exclamdownsmall", "", "Ydieresissmall", "", "onesuperior", "twosuperior", "threesuperior", "foursuperior", "fivesuperior", "sixsuperior", "sevensuperior", "ninesuperior", "zerosuperior", "", "esuperior", "rsuperior", "tsuperior", "", "", "isuperior", "ssuperior", "dsuperior", "", "", "", "", "", "lsuperior", "Ogoneksmall", "Brevesmall", "Macronsmall", "bsuperior", "nsuperior", "msuperior", "commasuperior", "periodsuperior", "Dotaccentsmall", "Ringsmall", "", "", "", ""];
const MacRomanEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "", "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", "registered", "copyright", "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", "guillemotright", "ellipsis", "space", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve", "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron"];
exports.MacRomanEncoding = MacRomanEncoding;
const StandardEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", "", "endash", "dagger", "daggerdbl", "periodcentered", "", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", "", "questiondown", "", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", "", "ring", "cedilla", "", "hungarumlaut", "ogonek", "caron", "emdash", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "AE", "", "ordfeminine", "", "", "", "", "Lslash", "Oslash", "OE", "ordmasculine", "", "", "", "", "", "ae", "", "", "", "dotlessi", "", "", "lslash", "oslash", "oe", "germandbls", "", "", "", ""];
exports.StandardEncoding = StandardEncoding;
const WinAnsiEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "bullet", "Euro", "bullet", "quotesinglbase", "florin", "quotedblbase", "ellipsis", "dagger", "daggerdbl", "circumflex", "perthousand", "Scaron", "guilsinglleft", "OE", "bullet", "Zcaron", "bullet", "bullet", "quoteleft", "quoteright", "quotedblleft", "quotedblright", "bullet", "endash", "emdash", "tilde", "trademark", "scaron", "guilsinglright", "oe", "bullet", "zcaron", "Ydieresis", "space", "exclamdown", "cent", "sterling", "currency", "yen", "brokenbar", "section", "dieresis", "copyright", "ordfeminine", "guillemotleft", "logicalnot", "hyphen", "registered", "macron", "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu", "paragraph", "periodcentered", "cedilla", "onesuperior", "ordmasculine", "guillemotright", "onequarter", "onehalf", "threequarters", "questiondown", "Agrave", "Aacute", "Acircumflex", "Atilde", "Adieresis", "Aring", "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex", "Edieresis", "Igrave", "Iacute", "Icircumflex", "Idieresis", "Eth", "Ntilde", "Ograve", "Oacute", "Ocircumflex", "Otilde", "Odieresis", "multiply", "Oslash", "Ugrave", "Uacute", "Ucircumflex", "Udieresis", "Yacute", "Thorn", "germandbls", "agrave", "aacute", "acircumflex", "atilde", "adieresis", "aring", "ae", "ccedilla", "egrave", "eacute", "ecircumflex", "edieresis", "igrave", "iacute", "icircumflex", "idieresis", "eth", "ntilde", "ograve", "oacute", "ocircumflex", "otilde", "odieresis", "divide", "oslash", "ugrave", "uacute", "ucircumflex", "udieresis", "yacute", "thorn", "ydieresis"];
exports.WinAnsiEncoding = WinAnsiEncoding;
const SymbolSetEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "exclam", "universal", "numbersign", "existential", "percent", "ampersand", "suchthat", "parenleft", "parenright", "asteriskmath", "plus", "comma", "minus", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "congruent", "Alpha", "Beta", "Chi", "Delta", "Epsilon", "Phi", "Gamma", "Eta", "Iota", "theta1", "Kappa", "Lambda", "Mu", "Nu", "Omicron", "Pi", "Theta", "Rho", "Sigma", "Tau", "Upsilon", "sigma1", "Omega", "Xi", "Psi", "Zeta", "bracketleft", "therefore", "bracketright", "perpendicular", "underscore", "radicalex", "alpha", "beta", "chi", "delta", "epsilon", "phi", "gamma", "eta", "iota", "phi1", "kappa", "lambda", "mu", "nu", "omicron", "pi", "theta", "rho", "sigma", "tau", "upsilon", "omega1", "omega", "xi", "psi", "zeta", "braceleft", "bar", "braceright", "similar", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Euro", "Upsilon1", "minute", "lessequal", "fraction", "infinity", "florin", "club", "diamond", "heart", "spade", "arrowboth", "arrowleft", "arrowup", "arrowright", "arrowdown", "degree", "plusminus", "second", "greaterequal", "multiply", "proportional", "partialdiff", "bullet", "divide", "notequal", "equivalence", "approxequal", "ellipsis", "arrowvertex", "arrowhorizex", "carriagereturn", "aleph", "Ifraktur", "Rfraktur", "weierstrass", "circlemultiply", "circleplus", "emptyset", "intersection", "union", "propersuperset", "reflexsuperset", "notsubset", "propersubset", "reflexsubset", "element", "notelement", "angle", "gradient", "registerserif", "copyrightserif", "trademarkserif", "product", "radical", "dotmath", "logicalnot", "logicaland", "logicalor", "arrowdblboth", "arrowdblleft", "arrowdblup", "arrowdblright", "arrowdbldown", "lozenge", "angleleft", "registersans", "copyrightsans", "trademarksans", "summation", "parenlefttp", "parenleftex", "parenleftbt", "bracketlefttp", "bracketleftex", "bracketleftbt", "bracelefttp", "braceleftmid", "braceleftbt", "braceex", "", "angleright", "integral", "integraltp", "integralex", "integralbt", "parenrighttp", "parenrightex", "parenrightbt", "bracketrighttp", "bracketrightex", "bracketrightbt", "bracerighttp", "bracerightmid", "bracerightbt", ""];
exports.SymbolSetEncoding = SymbolSetEncoding;
const ZapfDingbatsEncoding = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "space", "a1", "a2", "a202", "a3", "a4", "a5", "a119", "a118", "a117", "a11", "a12", "a13", "a14", "a15", "a16", "a105", "a17", "a18", "a19", "a20", "a21", "a22", "a23", "a24", "a25", "a26", "a27", "a28", "a6", "a7", "a8", "a9", "a10", "a29", "a30", "a31", "a32", "a33", "a34", "a35", "a36", "a37", "a38", "a39", "a40", "a41", "a42", "a43", "a44", "a45", "a46", "a47", "a48", "a49", "a50", "a51", "a52", "a53", "a54", "a55", "a56", "a57", "a58", "a59", "a60", "a61", "a62", "a63", "a64", "a65", "a66", "a67", "a68", "a69", "a70", "a71", "a72", "a73", "a74", "a203", "a75", "a204", "a76", "a77", "a78", "a79", "a81", "a82", "a83", "a84", "a97", "a98", "a99", "a100", "", "a89", "a90", "a93", "a94", "a91", "a92", "a205", "a85", "a206", "a86", "a87", "a88", "a95", "a96", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "a101", "a102", "a103", "a104", "a106", "a107", "a108", "a112", "a111", "a110", "a109", "a120", "a121", "a122", "a123", "a124", "a125", "a126", "a127", "a128", "a129", "a130", "a131", "a132", "a133", "a134", "a135", "a136", "a137", "a138", "a139", "a140", "a141", "a142", "a143", "a144", "a145", "a146", "a147", "a148", "a149", "a150", "a151", "a152", "a153", "a154", "a155", "a156", "a157", "a158", "a159", "a160", "a161", "a163", "a164", "a196", "a165", "a192", "a166", "a167", "a168", "a169", "a170", "a171", "a172", "a173", "a162", "a174", "a175", "a176", "a177", "a178", "a179", "a193", "a180", "a199", "a181", "a200", "a182", "", "a201", "a183", "a184", "a197", "a185", "a194", "a198", "a186", "a195", "a187", "a188", "a189", "a190", "a191", ""];
exports.ZapfDingbatsEncoding = ZapfDingbatsEncoding;
function getEncoding(encodingName) {
  switch (encodingName) {
    case "WinAnsiEncoding":
      return WinAnsiEncoding;
    case "StandardEncoding":
      return StandardEncoding;
    case "MacRomanEncoding":
      return MacRomanEncoding;
    case "SymbolSetEncoding":
      return SymbolSetEncoding;
    case "ZapfDingbatsEncoding":
      return ZapfDingbatsEncoding;
    case "ExpertEncoding":
      return ExpertEncoding;
    case "MacExpertEncoding":
      return MacExpertEncoding;
    default:
      return null;
  }
}

/***/ }),
/* 36 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.SEAC_ANALYSIS_ENABLED = exports.MacStandardGlyphOrdering = exports.FontFlags = void 0;
exports.normalizeFontName = normalizeFontName;
exports.recoverGlyphName = recoverGlyphName;
exports.type1FontGlyphMapping = type1FontGlyphMapping;
var _encodings = __w_pdfjs_require__(35);
var _glyphlist = __w_pdfjs_require__(37);
var _unicode = __w_pdfjs_require__(38);
var _util = __w_pdfjs_require__(2);
const SEAC_ANALYSIS_ENABLED = true;
exports.SEAC_ANALYSIS_ENABLED = SEAC_ANALYSIS_ENABLED;
const FontFlags = {
  FixedPitch: 1,
  Serif: 2,
  Symbolic: 4,
  Script: 8,
  Nonsymbolic: 32,
  Italic: 64,
  AllCap: 65536,
  SmallCap: 131072,
  ForceBold: 262144
};
exports.FontFlags = FontFlags;
const MacStandardGlyphOrdering = [".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", "registered", "copyright", "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve", "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn", "thorn", "minus", "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf", "onequarter", "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron", "ccaron", "dcroat"];
exports.MacStandardGlyphOrdering = MacStandardGlyphOrdering;
function recoverGlyphName(name, glyphsUnicodeMap) {
  if (glyphsUnicodeMap[name] !== undefined) {
    return name;
  }
  const unicode = (0, _unicode.getUnicodeForGlyph)(name, glyphsUnicodeMap);
  if (unicode !== -1) {
    for (const key in glyphsUnicodeMap) {
      if (glyphsUnicodeMap[key] === unicode) {
        return key;
      }
    }
  }
  (0, _util.info)("Unable to recover a standard glyph name for: " + name);
  return name;
}
function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  const charCodeToGlyphId = Object.create(null);
  let glyphId, charCode, baseEncoding;
  const isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  if (properties.isInternalFont) {
    baseEncoding = builtInEncoding;
    for (charCode = 0; charCode < baseEncoding.length; charCode++) {
      glyphId = glyphNames.indexOf(baseEncoding[charCode]);
      if (glyphId >= 0) {
        charCodeToGlyphId[charCode] = glyphId;
      } else {
        charCodeToGlyphId[charCode] = 0;
      }
    }
  } else if (properties.baseEncodingName) {
    baseEncoding = (0, _encodings.getEncoding)(properties.baseEncodingName);
    for (charCode = 0; charCode < baseEncoding.length; charCode++) {
      glyphId = glyphNames.indexOf(baseEncoding[charCode]);
      if (glyphId >= 0) {
        charCodeToGlyphId[charCode] = glyphId;
      } else {
        charCodeToGlyphId[charCode] = 0;
      }
    }
  } else if (isSymbolicFont) {
    for (charCode in builtInEncoding) {
      charCodeToGlyphId[charCode] = builtInEncoding[charCode];
    }
  } else {
    baseEncoding = _encodings.StandardEncoding;
    for (charCode = 0; charCode < baseEncoding.length; charCode++) {
      glyphId = glyphNames.indexOf(baseEncoding[charCode]);
      if (glyphId >= 0) {
        charCodeToGlyphId[charCode] = glyphId;
      } else {
        charCodeToGlyphId[charCode] = 0;
      }
    }
  }
  const differences = properties.differences;
  let glyphsUnicodeMap;
  if (differences) {
    for (charCode in differences) {
      const glyphName = differences[charCode];
      glyphId = glyphNames.indexOf(glyphName);
      if (glyphId === -1) {
        if (!glyphsUnicodeMap) {
          glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
        }
        const standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
        if (standardGlyphName !== glyphName) {
          glyphId = glyphNames.indexOf(standardGlyphName);
        }
      }
      if (glyphId >= 0) {
        charCodeToGlyphId[charCode] = glyphId;
      } else {
        charCodeToGlyphId[charCode] = 0;
      }
    }
  }
  return charCodeToGlyphId;
}
function normalizeFontName(name) {
  return name.replace(/[,_]/g, "-").replace(/\s/g, "");
}

/***/ }),
/* 37 */
/***/ ((__unused_webpack_module, __webpack_exports__, __w_pdfjs_require__) => {

__w_pdfjs_require__.r(__webpack_exports__);
/* harmony export */ __w_pdfjs_require__.d(__webpack_exports__, {
/* harmony export */   "getDingbatsGlyphsUnicode": () => (/* binding */ getDingbatsGlyphsUnicode),
/* harmony export */   "getGlyphsUnicode": () => (/* binding */ getGlyphsUnicode)
/* harmony export */ });
/* harmony import */ var _core_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __w_pdfjs_require__(4);

const getGlyphsUnicode = (0,_core_utils_js__WEBPACK_IMPORTED_MODULE_0__.getArrayLookupTableFactory)(function () {
 return [
  "A",
  0x0041,
  "AE",
  0x00c6,
  "AEacute",
  0x01fc,
  "AEmacron",
  0x01e2,
  "AEsmall",
  0xf7e6,
  "Aacute",
  0x00c1,
  "Aacutesmall",
  0xf7e1,
  "Abreve",
  0x0102,
  "Abreveacute",
  0x1eae,
  "Abrevecyrillic",
  0x04d0,
  "Abrevedotbelow",
  0x1eb6,
  "Abrevegrave",
  0x1eb0,
  "Abrevehookabove",
  0x1eb2,
  "Abrevetilde",
  0x1eb4,
  "Acaron",
  0x01cd,
  "Acircle",
  0x24b6,
  "Acircumflex",
  0x00c2,
  "Acircumflexacute",
  0x1ea4,
  "Acircumflexdotbelow",
  0x1eac,
  "Acircumflexgrave",
  0x1ea6,
  "Acircumflexhookabove",
  0x1ea8,
  "Acircumflexsmall",
  0xf7e2,
  "Acircumflextilde",
  0x1eaa,
  "Acute",
  0xf6c9,
  "Acutesmall",
  0xf7b4,
  "Acyrillic",
  0x0410,
  "Adblgrave",
  0x0200,
  "Adieresis",
  0x00c4,
  "Adieresiscyrillic",
  0x04d2,
  "Adieresismacron",
  0x01de,
  "Adieresissmall",
  0xf7e4,
  "Adotbelow",
  0x1ea0,
  "Adotmacron",
  0x01e0,
  "Agrave",
  0x00c0,
  "Agravesmall",
  0xf7e0,
  "Ahookabove",
  0x1ea2,
  "Aiecyrillic",
  0x04d4,
  "Ainvertedbreve",
  0x0202,
  "Alpha",
  0x0391,
  "Alphatonos",
  0x0386,
  "Amacron",
  0x0100,
  "Amonospace",
  0xff21,
  "Aogonek",
  0x0104,
  "Aring",
  0x00c5,
  "Aringacute",
  0x01fa,
  "Aringbelow",
  0x1e00,
  "Aringsmall",
  0xf7e5,
  "Asmall",
  0xf761,
  "Atilde",
  0x00c3,
  "Atildesmall",
  0xf7e3,
  "Aybarmenian",
  0x0531,
  "B",
  0x0042,
  "Bcircle",
  0x24b7,
  "Bdotaccent",
  0x1e02,
  "Bdotbelow",
  0x1e04,
  "Becyrillic",
  0x0411,
  "Benarmenian",
  0x0532,
  "Beta",
  0x0392,
  "Bhook",
  0x0181,
  "Blinebelow",
  0x1e06,
  "Bmonospace",
  0xff22,
  "Brevesmall",
  0xf6f4,
  "Bsmall",
  0xf762,
  "Btopbar",
  0x0182,
  "C",
  0x0043,
  "Caarmenian",
  0x053e,
  "Cacute",
  0x0106,
  "Caron",
  0xf6ca,
  "Caronsmall",
  0xf6f5,
  "Ccaron",
  0x010c,
  "Ccedilla",
  0x00c7,
  "Ccedillaacute",
  0x1e08,
  "Ccedillasmall",
  0xf7e7,
  "Ccircle",
  0x24b8,
  "Ccircumflex",
  0x0108,
  "Cdot",
  0x010a,
  "Cdotaccent",
  0x010a,
  "Cedillasmall",
  0xf7b8,
  "Chaarmenian",
  0x0549,
  "Cheabkhasiancyrillic",
  0x04bc,
  "Checyrillic",
  0x0427,
  "Chedescenderabkhasiancyrillic",
  0x04be,
  "Chedescendercyrillic",
  0x04b6,
  "Chedieresiscyrillic",
  0x04f4,
  "Cheharmenian",
  0x0543,
  "Chekhakassiancyrillic",
  0x04cb,
  "Cheverticalstrokecyrillic",
  0x04b8,
  "Chi",
  0x03a7,
  "Chook",
  0x0187,
  "Circumflexsmall",
  0xf6f6,
  "Cmonospace",
  0xff23,
  "Coarmenian",
  0x0551,
  "Csmall",
  0xf763,
  "D",
  0x0044,
  "DZ",
  0x01f1,
  "DZcaron",
  0x01c4,
  "Daarmenian",
  0x0534,
  "Dafrican",
  0x0189,
  "Dcaron",
  0x010e,
  "Dcedilla",
  0x1e10,
  "Dcircle",
  0x24b9,
  "Dcircumflexbelow",
  0x1e12,
  "Dcroat",
  0x0110,
  "Ddotaccent",
  0x1e0a,
  "Ddotbelow",
  0x1e0c,
  "Decyrillic",
  0x0414,
  "Deicoptic",
  0x03ee,
  "Delta",
  0x2206,
  "Deltagreek",
  0x0394,
  "Dhook",
  0x018a,
  "Dieresis",
  0xf6cb,
  "DieresisAcute",
  0xf6cc,
  "DieresisGrave",
  0xf6cd,
  "Dieresissmall",
  0xf7a8,
  "Digammagreek",
  0x03dc,
  "Djecyrillic",
  0x0402,
  "Dlinebelow",
  0x1e0e,
  "Dmonospace",
  0xff24,
  "Dotaccentsmall",
  0xf6f7,
  "Dslash",
  0x0110,
  "Dsmall",
  0xf764,
  "Dtopbar",
  0x018b,
  "Dz",
  0x01f2,
  "Dzcaron",
  0x01c5,
  "Dzeabkhasiancyrillic",
  0x04e0,
  "Dzecyrillic",
  0x0405,
  "Dzhecyrillic",
  0x040f,
  "E",
  0x0045,
  "Eacute",
  0x00c9,
  "Eacutesmall",
  0xf7e9,
  "Ebreve",
  0x0114,
  "Ecaron",
  0x011a,
  "Ecedillabreve",
  0x1e1c,
  "Echarmenian",
  0x0535,
  "Ecircle",
  0x24ba,
  "Ecircumflex",
  0x00ca,
  "Ecircumflexacute",
  0x1ebe,
  "Ecircumflexbelow",
  0x1e18,
  "Ecircumflexdotbelow",
  0x1ec6,
  "Ecircumflexgrave",
  0x1ec0,
  "Ecircumflexhookabove",
  0x1ec2,
  "Ecircumflexsmall",
  0xf7ea,
  "Ecircumflextilde",
  0x1ec4,
  "Ecyrillic",
  0x0404,
  "Edblgrave",
  0x0204,
  "Edieresis",
  0x00cb,
  "Edieresissmall",
  0xf7eb,
  "Edot",
  0x0116,
  "Edotaccent",
  0x0116,
  "Edotbelow",
  0x1eb8,
  "Efcyrillic",
  0x0424,
  "Egrave",
  0x00c8,
  "Egravesmall",
  0xf7e8,
  "Eharmenian",
  0x0537,
  "Ehookabove",
  0x1eba,
  "Eightroman",
  0x2167,
  "Einvertedbreve",
  0x0206,
  "Eiotifiedcyrillic",
  0x0464,
  "Elcyrillic",
  0x041b,
  "Elevenroman",
  0x216a,
  "Emacron",
  0x0112,
  "Emacronacute",
  0x1e16,
  "Emacrongrave",
  0x1e14,
  "Emcyrillic",
  0x041c,
  "Emonospace",
  0xff25,
  "Encyrillic",
  0x041d,
  "Endescendercyrillic",
  0x04a2,
  "Eng",
  0x014a,
  "Enghecyrillic",
  0x04a4,
  "Enhookcyrillic",
  0x04c7,
  "Eogonek",
  0x0118,
  "Eopen",
  0x0190,
  "Epsilon",
  0x0395,
  "Epsilontonos",
  0x0388,
  "Ercyrillic",
  0x0420,
  "Ereversed",
  0x018e,
  "Ereversedcyrillic",
  0x042d,
  "Escyrillic",
  0x0421,
  "Esdescendercyrillic",
  0x04aa,
  "Esh",
  0x01a9,
  "Esmall",
  0xf765,
  "Eta",
  0x0397,
  "Etarmenian",
  0x0538,
  "Etatonos",
  0x0389,
  "Eth",
  0x00d0,
  "Ethsmall",
  0xf7f0,
  "Etilde",
  0x1ebc,
  "Etildebelow",
  0x1e1a,
  "Euro",
  0x20ac,
  "Ezh",
  0x01b7,
  "Ezhcaron",
  0x01ee,
  "Ezhreversed",
  0x01b8,
  "F",
  0x0046,
  "Fcircle",
  0x24bb,
  "Fdotaccent",
  0x1e1e,
  "Feharmenian",
  0x0556,
  "Feicoptic",
  0x03e4,
  "Fhook",
  0x0191,
  "Fitacyrillic",
  0x0472,
  "Fiveroman",
  0x2164,
  "Fmonospace",
  0xff26,
  "Fourroman",
  0x2163,
  "Fsmall",
  0xf766,
  "G",
  0x0047,
  "GBsquare",
  0x3387,
  "Gacute",
  0x01f4,
  "Gamma",
  0x0393,
  "Gammaafrican",
  0x0194,
  "Gangiacoptic",
  0x03ea,
  "Gbreve",
  0x011e,
  "Gcaron",
  0x01e6,
  "Gcedilla",
  0x0122,
  "Gcircle",
  0x24bc,
  "Gcircumflex",
  0x011c,
  "Gcommaaccent",
  0x0122,
  "Gdot",
  0x0120,
  "Gdotaccent",
  0x0120,
  "Gecyrillic",
  0x0413,
  "Ghadarmenian",
  0x0542,
  "Ghemiddlehookcyrillic",
  0x0494,
  "Ghestrokecyrillic",
  0x0492,
  "Gheupturncyrillic",
  0x0490,
  "Ghook",
  0x0193,
  "Gimarmenian",
  0x0533,
  "Gjecyrillic",
  0x0403,
  "Gmacron",
  0x1e20,
  "Gmonospace",
  0xff27,
  "Grave",
  0xf6ce,
  "Gravesmall",
  0xf760,
  "Gsmall",
  0xf767,
  "Gsmallhook",
  0x029b,
  "Gstroke",
  0x01e4,
  "H",
  0x0048,
  "H18533",
  0x25cf,
  "H18543",
  0x25aa,
  "H18551",
  0x25ab,
  "H22073",
  0x25a1,
  "HPsquare",
  0x33cb,
  "Haabkhasiancyrillic",
  0x04a8,
  "Hadescendercyrillic",
  0x04b2,
  "Hardsigncyrillic",
  0x042a,
  "Hbar",
  0x0126,
  "Hbrevebelow",
  0x1e2a,
  "Hcedilla",
  0x1e28,
  "Hcircle",
  0x24bd,
  "Hcircumflex",
  0x0124,
  "Hdieresis",
  0x1e26,
  "Hdotaccent",
  0x1e22,
  "Hdotbelow",
  0x1e24,
  "Hmonospace",
  0xff28,
  "Hoarmenian",
  0x0540,
  "Horicoptic",
  0x03e8,
  "Hsmall",
  0xf768,
  "Hungarumlaut",
  0xf6cf,
  "Hungarumlautsmall",
  0xf6f8,
  "Hzsquare",
  0x3390,
  "I",
  0x0049,
  "IAcyrillic",
  0x042f,
  "IJ",
  0x0132,
  "IUcyrillic",
  0x042e,
  "Iacute",
  0x00cd,
  "Iacutesmall",
  0xf7ed,
  "Ibreve",
  0x012c,
  "Icaron",
  0x01cf,
  "Icircle",
  0x24be,
  "Icircumflex",
  0x00ce,
  "Icircumflexsmall",
  0xf7ee,
  "Icyrillic",
  0x0406,
  "Idblgrave",
  0x0208,
  "Idieresis",
  0x00cf,
  "Idieresisacute",
  0x1e2e,
  "Idieresiscyrillic",
  0x04e4,
  "Idieresissmall",
  0xf7ef,
  "Idot",
  0x0130,
  "Idotaccent",
  0x0130,
  "Idotbelow",
  0x1eca,
  "Iebrevecyrillic",
  0x04d6,
  "Iecyrillic",
  0x0415,
  "Ifraktur",
  0x2111,
  "Igrave",
  0x00cc,
  "Igravesmall",
  0xf7ec,
  "Ihookabove",
  0x1ec8,
  "Iicyrillic",
  0x0418,
  "Iinvertedbreve",
  0x020a,
  "Iishortcyrillic",
  0x0419,
  "Imacron",
  0x012a,
  "Imacroncyrillic",
  0x04e2,
  "Imonospace",
  0xff29,
  "Iniarmenian",
  0x053b,
  "Iocyrillic",
  0x0401,
  "Iogonek",
  0x012e,
  "Iota",
  0x0399,
  "Iotaafrican",
  0x0196,
  "Iotadieresis",
  0x03aa,
  "Iotatonos",
  0x038a,
  "Ismall",
  0xf769,
  "Istroke",
  0x0197,
  "Itilde",
  0x0128,
  "Itildebelow",
  0x1e2c,
  "Izhitsacyrillic",
  0x0474,
  "Izhitsadblgravecyrillic",
  0x0476,
  "J",
  0x004a,
  "Jaarmenian",
  0x0541,
  "Jcircle",
  0x24bf,
  "Jcircumflex",
  0x0134,
  "Jecyrillic",
  0x0408,
  "Jheharmenian",
  0x054b,
  "Jmonospace",
  0xff2a,
  "Jsmall",
  0xf76a,
  "K",
  0x004b,
  "KBsquare",
  0x3385,
  "KKsquare",
  0x33cd,
  "Kabashkircyrillic",
  0x04a0,
  "Kacute",
  0x1e30,
  "Kacyrillic",
  0x041a,
  "Kadescendercyrillic",
  0x049a,
  "Kahookcyrillic",
  0x04c3,
  "Kappa",
  0x039a,
  "Kastrokecyrillic",
  0x049e,
  "Kaverticalstrokecyrillic",
  0x049c,
  "Kcaron",
  0x01e8,
  "Kcedilla",
  0x0136,
  "Kcircle",
  0x24c0,
  "Kcommaaccent",
  0x0136,
  "Kdotbelow",
  0x1e32,
  "Keharmenian",
  0x0554,
  "Kenarmenian",
  0x053f,
  "Khacyrillic",
  0x0425,
  "Kheicoptic",
  0x03e6,
  "Khook",
  0x0198,
  "Kjecyrillic",
  0x040c,
  "Klinebelow",
  0x1e34,
  "Kmonospace",
  0xff2b,
  "Koppacyrillic",
  0x0480,
  "Koppagreek",
  0x03de,
  "Ksicyrillic",
  0x046e,
  "Ksmall",
  0xf76b,
  "L",
  0x004c,
  "LJ",
  0x01c7,
  "LL",
  0xf6bf,
  "Lacute",
  0x0139,
  "Lambda",
  0x039b,
  "Lcaron",
  0x013d,
  "Lcedilla",
  0x013b,
  "Lcircle",
  0x24c1,
  "Lcircumflexbelow",
  0x1e3c,
  "Lcommaaccent",
  0x013b,
  "Ldot",
  0x013f,
  "Ldotaccent",
  0x013f,
  "Ldotbelow",
  0x1e36,
  "Ldotbelowmacron",
  0x1e38,
  "Liwnarmenian",
  0x053c,
  "Lj",
  0x01c8,
  "Ljecyrillic",
  0x0409,
  "Llinebelow",
  0x1e3a,
  "Lmonospace",
  0xff2c,
  "Lslash",
  0x0141,
  "Lslashsmall",
  0xf6f9,
  "Lsmall",
  0xf76c,
  "M",
  0x004d,
  "MBsquare",
  0x3386,
  "Macron",
  0xf6d0,
  "Macronsmall",
  0xf7af,
  "Macute",
  0x1e3e,
  "Mcircle",
  0x24c2,
  "Mdotaccent",
  0x1e40,
  "Mdotbelow",
  0x1e42,
  "Menarmenian",
  0x0544,
  "Mmonospace",
  0xff2d,
  "Msmall",
  0xf76d,
  "Mturned",
  0x019c,
  "Mu",
  0x039c,
  "N",
  0x004e,
  "NJ",
  0x01ca,
  "Nacute",
  0x0143,
  "Ncaron",
  0x0147,
  "Ncedilla",
  0x0145,
  "Ncircle",
  0x24c3,
  "Ncircumflexbelow",
  0x1e4a,
  "Ncommaaccent",
  0x0145,
  "Ndotaccent",
  0x1e44,
  "Ndotbelow",
  0x1e46,
  "Nhookleft",
  0x019d,
  "Nineroman",
  0x2168,
  "Nj",
  0x01cb,
  "Njecyrillic",
  0x040a,
  "Nlinebelow",
  0x1e48,
  "Nmonospace",
  0xff2e,
  "Nowarmenian",
  0x0546,
  "Nsmall",
  0xf76e,
  "Ntilde",
  0x00d1,
  "Ntildesmall",
  0xf7f1,
  "Nu",
  0x039d,
  "O",
  0x004f,
  "OE",
  0x0152,
  "OEsmall",
  0xf6fa,
  "Oacute",
  0x00d3,
  "Oacutesmall",
  0xf7f3,
  "Obarredcyrillic",
  0x04e8,
  "Obarreddieresiscyrillic",
  0x04ea,
  "Obreve",
  0x014e,
  "Ocaron",
  0x01d1,
  "Ocenteredtilde",
  0x019f,
  "Ocircle",
  0x24c4,
  "Ocircumflex",
  0x00d4,
  "Ocircumflexacute",
  0x1ed0,
  "Ocircumflexdotbelow",
  0x1ed8,
  "Ocircumflexgrave",
  0x1ed2,
  "Ocircumflexhookabove",
  0x1ed4,
  "Ocircumflexsmall",
  0xf7f4,
  "Ocircumflextilde",
  0x1ed6,
  "Ocyrillic",
  0x041e,
  "Odblacute",
  0x0150,
  "Odblgrave",
  0x020c,
  "Odieresis",
  0x00d6,
  "Odieresiscyrillic",
  0x04e6,
  "Odieresissmall",
  0xf7f6,
  "Odotbelow",
  0x1ecc,
  "Ogoneksmall",
  0xf6fb,
  "Ograve",
  0x00d2,
  "Ogravesmall",
  0xf7f2,
  "Oharmenian",
  0x0555,
  "Ohm",
  0x2126,
  "Ohookabove",
  0x1ece,
  "Ohorn",
  0x01a0,
  "Ohornacute",
  0x1eda,
  "Ohorndotbelow",
  0x1ee2,
  "Ohorngrave",
  0x1edc,
  "Ohornhookabove",
  0x1ede,
  "Ohorntilde",
  0x1ee0,
  "Ohungarumlaut",
  0x0150,
  "Oi",
  0x01a2,
  "Oinvertedbreve",
  0x020e,
  "Omacron",
  0x014c,
  "Omacronacute",
  0x1e52,
  "Omacrongrave",
  0x1e50,
  "Omega",
  0x2126,
  "Omegacyrillic",
  0x0460,
  "Omegagreek",
  0x03a9,
  "Omegaroundcyrillic",
  0x047a,
  "Omegatitlocyrillic",
  0x047c,
  "Omegatonos",
  0x038f,
  "Omicron",
  0x039f,
  "Omicrontonos",
  0x038c,
  "Omonospace",
  0xff2f,
  "Oneroman",
  0x2160,
  "Oogonek",
  0x01ea,
  "Oogonekmacron",
  0x01ec,
  "Oopen",
  0x0186,
  "Oslash",
  0x00d8,
  "Oslashacute",
  0x01fe,
  "Oslashsmall",
  0xf7f8,
  "Osmall",
  0xf76f,
  "Ostrokeacute",
  0x01fe,
  "Otcyrillic",
  0x047e,
  "Otilde",
  0x00d5,
  "Otildeacute",
  0x1e4c,
  "Otildedieresis",
  0x1e4e,
  "Otildesmall",
  0xf7f5,
  "P",
  0x0050,
  "Pacute",
  0x1e54,
  "Pcircle",
  0x24c5,
  "Pdotaccent",
  0x1e56,
  "Pecyrillic",
  0x041f,
  "Peharmenian",
  0x054a,
  "Pemiddlehookcyrillic",
  0x04a6,
  "Phi",
  0x03a6,
  "Phook",
  0x01a4,
  "Pi",
  0x03a0,
  "Piwrarmenian",
  0x0553,
  "Pmonospace",
  0xff30,
  "Psi",
  0x03a8,
  "Psicyrillic",
  0x0470,
  "Psmall",
  0xf770,
  "Q",
  0x0051,
  "Qcircle",
  0x24c6,
  "Qmonospace",
  0xff31,
  "Qsmall",
  0xf771,
  "R",
  0x0052,
  "Raarmenian",
  0x054c,
  "Racute",
  0x0154,
  "Rcaron",
  0x0158,
  "Rcedilla",
  0x0156,
  "Rcircle",
  0x24c7,
  "Rcommaaccent",
  0x0156,
  "Rdblgrave",
  0x0210,
  "Rdotaccent",
  0x1e58,
  "Rdotbelow",
  0x1e5a,
  "Rdotbelowmacron",
  0x1e5c,
  "Reharmenian",
  0x0550,
  "Rfraktur",
  0x211c,
  "Rho",
  0x03a1,
  "Ringsmall",
  0xf6fc,
  "Rinvertedbreve",
  0x0212,
  "Rlinebelow",
  0x1e5e,
  "Rmonospace",
  0xff32,
  "Rsmall",
  0xf772,
  "Rsmallinverted",
  0x0281,
  "Rsmallinvertedsuperior",
  0x02b6,
  "S",
  0x0053,
  "SF010000",
  0x250c,
  "SF020000",
  0x2514,
  "SF030000",
  0x2510,
  "SF040000",
  0x2518,
  "SF050000",
  0x253c,
  "SF060000",
  0x252c,
  "SF070000",
  0x2534,
  "SF080000",
  0x251c,
  "SF090000",
  0x2524,
  "SF100000",
  0x2500,
  "SF110000",
  0x2502,
  "SF190000",
  0x2561,
  "SF200000",
  0x2562,
  "SF210000",
  0x2556,
  "SF220000",
  0x2555,
  "SF230000",
  0x2563,
  "SF240000",
  0x2551,
  "SF250000",
  0x2557,
  "SF260000",
  0x255d,
  "SF270000",
  0x255c,
  "SF280000",
  0x255b,
  "SF360000",
  0x255e,
  "SF370000",
  0x255f,
  "SF380000",
  0x255a,
  "SF390000",
  0x2554,
  "SF400000",
  0x2569,
  "SF410000",
  0x2566,
  "SF420000",
  0x2560,
  "SF430000",
  0x2550,
  "SF440000",
  0x256c,
  "SF450000",
  0x2567,
  "SF460000",
  0x2568,
  "SF470000",
  0x2564,
  "SF480000",
  0x2565,
  "SF490000",
  0x2559,
  "SF500000",
  0x2558,
  "SF510000",
  0x2552,
  "SF520000",
  0x2553,
  "SF530000",
  0x256b,
  "SF540000",
  0x256a,
  "Sacute",
  0x015a,
  "Sacutedotaccent",
  0x1e64,
  "Sampigreek",
  0x03e0,
  "Scaron",
  0x0160,
  "Scarondotaccent",
  0x1e66,
  "Scaronsmall",
  0xf6fd,
  "Scedilla",
  0x015e,
  "Schwa",
  0x018f,
  "Schwacyrillic",
  0x04d8,
  "Schwadieresiscyrillic",
  0x04da,
  "Scircle",
  0x24c8,
  "Scircumflex",
  0x015c,
  "Scommaaccent",
  0x0218,
  "Sdotaccent",
  0x1e60,
  "Sdotbelow",
  0x1e62,
  "Sdotbelowdotaccent",
  0x1e68,
  "Seharmenian",
  0x054d,
  "Sevenroman",
  0x2166,
  "Shaarmenian",
  0x0547,
  "Shacyrillic",
  0x0428,
  "Shchacyrillic",
  0x0429,
  "Sheicoptic",
  0x03e2,
  "Shhacyrillic",
  0x04ba,
  "Shimacoptic",
  0x03ec,
  "Sigma",
  0x03a3,
  "Sixroman",
  0x2165,
  "Smonospace",
  0xff33,
  "Softsigncyrillic",
  0x042c,
  "Ssmall",
  0xf773,
  "Stigmagreek",
  0x03da,
  "T",
  0x0054,
  "Tau",
  0x03a4,
  "Tbar",
  0x0166,
  "Tcaron",
  0x0164,
  "Tcedilla",
  0x0162,
  "Tcircle",
  0x24c9,
  "Tcircumflexbelow",
  0x1e70,
  "Tcommaaccent",
  0x0162,
  "Tdotaccent",
  0x1e6a,
  "Tdotbelow",
  0x1e6c,
  "Tecyrillic",
  0x0422,
  "Tedescendercyrillic",
  0x04ac,
  "Tenroman",
  0x2169,
  "Tetsecyrillic",
  0x04b4,
  "Theta",
  0x0398,
  "Thook",
  0x01ac,
  "Thorn",
  0x00de,
  "Thornsmall",
  0xf7fe,
  "Threeroman",
  0x2162,
  "Tildesmall",
  0xf6fe,
  "Tiwnarmenian",
  0x054f,
  "Tlinebelow",
  0x1e6e,
  "Tmonospace",
  0xff34,
  "Toarmenian",
  0x0539,
  "Tonefive",
  0x01bc,
  "Tonesix",
  0x0184,
  "Tonetwo",
  0x01a7,
  "Tretroflexhook",
  0x01ae,
  "Tsecyrillic",
  0x0426,
  "Tshecyrillic",
  0x040b,
  "Tsmall",
  0xf774,
  "Twelveroman",
  0x216b,
  "Tworoman",
  0x2161,
  "U",
  0x0055,
  "Uacute",
  0x00da,
  "Uacutesmall",
  0xf7fa,
  "Ubreve",
  0x016c,
  "Ucaron",
  0x01d3,
  "Ucircle",
  0x24ca,
  "Ucircumflex",
  0x00db,
  "Ucircumflexbelow",
  0x1e76,
  "Ucircumflexsmall",
  0xf7fb,
  "Ucyrillic",
  0x0423,
  "Udblacute",
  0x0170,
  "Udblgrave",
  0x0214,
  "Udieresis",
  0x00dc,
  "Udieresisacute",
  0x01d7,
  "Udieresisbelow",
  0x1e72,
  "Udieresiscaron",
  0x01d9,
  "Udieresiscyrillic",
  0x04f0,
  "Udieresisgrave",
  0x01db,
  "Udieresismacron",
  0x01d5,
  "Udieresissmall",
  0xf7fc,
  "Udotbelow",
  0x1ee4,
  "Ugrave",
  0x00d9,
  "Ugravesmall",
  0xf7f9,
  "Uhookabove",
  0x1ee6,
  "Uhorn",
  0x01af,
  "Uhornacute",
  0x1ee8,
  "Uhorndotbelow",
  0x1ef0,
  "Uhorngrave",
  0x1eea,
  "Uhornhookabove",
  0x1eec,
  "Uhorntilde",
  0x1eee,
  "Uhungarumlaut",
  0x0170,
  "Uhungarumlautcyrillic",
  0x04f2,
  "Uinvertedbreve",
  0x0216,
  "Ukcyrillic",
  0x0478,
  "Umacron",
  0x016a,
  "Umacroncyrillic",
  0x04ee,
  "Umacrondieresis",
  0x1e7a,
  "Umonospace",
  0xff35,
  "Uogonek",
  0x0172,
  "Upsilon",
  0x03a5,
  "Upsilon1",
  0x03d2,
  "Upsilonacutehooksymbolgreek",
  0x03d3,
  "Upsilonafrican",
  0x01b1,
  "Upsilondieresis",
  0x03ab,
  "Upsilondieresishooksymbolgreek",
  0x03d4,
  "Upsilonhooksymbol",
  0x03d2,
  "Upsilontonos",
  0x038e,
  "Uring",
  0x016e,
  "Ushortcyrillic",
  0x040e,
  "Usmall",
  0xf775,
  "Ustraightcyrillic",
  0x04ae,
  "Ustraightstrokecyrillic",
  0x04b0,
  "Utilde",
  0x0168,
  "Utildeacute",
  0x1e78,
  "Utildebelow",
  0x1e74,
  "V",
  0x0056,
  "Vcircle",
  0x24cb,
  "Vdotbelow",
  0x1e7e,
  "Vecyrillic",
  0x0412,
  "Vewarmenian",
  0x054e,
  "Vhook",
  0x01b2,
  "Vmonospace",
  0xff36,
  "Voarmenian",
  0x0548,
  "Vsmall",
  0xf776,
  "Vtilde",
  0x1e7c,
  "W",
  0x0057,
  "Wacute",
  0x1e82,
  "Wcircle",
  0x24cc,
  "Wcircumflex",
  0x0174,
  "Wdieresis",
  0x1e84,
  "Wdotaccent",
  0x1e86,
  "Wdotbelow",
  0x1e88,
  "Wgrave",
  0x1e80,
  "Wmonospace",
  0xff37,
  "Wsmall",
  0xf777,
  "X",
  0x0058,
  "Xcircle",
  0x24cd,
  "Xdieresis",
  0x1e8c,
  "Xdotaccent",
  0x1e8a,
  "Xeharmenian",
  0x053d,
  "Xi",
  0x039e,
  "Xmonospace",
  0xff38,
  "Xsmall",
  0xf778,
  "Y",
  0x0059,
  "Yacute",
  0x00dd,
  "Yacutesmall",
  0xf7fd,
  "Yatcyrillic",
  0x0462,
  "Ycircle",
  0x24ce,
  "Ycircumflex",
  0x0176,
  "Ydieresis",
  0x0178,
  "Ydieresissmall",
  0xf7ff,
  "Ydotaccent",
  0x1e8e,
  "Ydotbelow",
  0x1ef4,
  "Yericyrillic",
  0x042b,
  "Yerudieresiscyrillic",
  0x04f8,
  "Ygrave",
  0x1ef2,
  "Yhook",
  0x01b3,
  "Yhookabove",
  0x1ef6,
  "Yiarmenian",
  0x0545,
  "Yicyrillic",
  0x0407,
  "Yiwnarmenian",
  0x0552,
  "Ymonospace",
  0xff39,
  "Ysmall",
  0xf779,
  "Ytilde",
  0x1ef8,
  "Yusbigcyrillic",
  0x046a,
  "Yusbigiotifiedcyrillic",
  0x046c,
  "Yuslittlecyrillic",
  0x0466,
  "Yuslittleiotifiedcyrillic",
  0x0468,
  "Z",
  0x005a,
  "Zaarmenian",
  0x0536,
  "Zacute",
  0x0179,
  "Zcaron",
  0x017d,
  "Zcaronsmall",
  0xf6ff,
  "Zcircle",
  0x24cf,
  "Zcircumflex",
  0x1e90,
  "Zdot",
  0x017b,
  "Zdotaccent",
  0x017b,
  "Zdotbelow",
  0x1e92,
  "Zecyrillic",
  0x0417,
  "Zedescendercyrillic",
  0x0498,
  "Zedieresiscyrillic",
  0x04de,
  "Zeta",
  0x0396,
  "Zhearmenian",
  0x053a,
  "Zhebrevecyrillic",
  0x04c1,
  "Zhecyrillic",
  0x0416,
  "Zhedescendercyrillic",
  0x0496,
  "Zhedieresiscyrillic",
  0x04dc,
  "Zlinebelow",
  0x1e94,
  "Zmonospace",
  0xff3a,
  "Zsmall",
  0xf77a,
  "Zstroke",
  0x01b5,
  "a",
  0x0061,
  "aabengali",
  0x0986,
  "aacute",
  0x00e1,
  "aadeva",
  0x0906,
  "aagujarati",
  0x0a86,
  "aagurmukhi",
  0x0a06,
  "aamatragurmukhi",
  0x0a3e,
  "aarusquare",
  0x3303,
  "aavowelsignbengali",
  0x09be,
  "aavowelsigndeva",
  0x093e,
  "aavowelsigngujarati",
  0x0abe,
  "abbreviationmarkarmenian",
  0x055f,
  "abbreviationsigndeva",
  0x0970,
  "abengali",
  0x0985,
  "abopomofo",
  0x311a,
  "abreve",
  0x0103,
  "abreveacute",
  0x1eaf,
  "abrevecyrillic",
  0x04d1,
  "abrevedotbelow",
  0x1eb7,
  "abrevegrave",
  0x1eb1,
  "abrevehookabove",
  0x1eb3,
  "abrevetilde",
  0x1eb5,
  "acaron",
  0x01ce,
  "acircle",
  0x24d0,
  "acircumflex",
  0x00e2,
  "acircumflexacute",
  0x1ea5,
  "acircumflexdotbelow",
  0x1ead,
  "acircumflexgrave",
  0x1ea7,
  "acircumflexhookabove",
  0x1ea9,
  "acircumflextilde",
  0x1eab,
  "acute",
  0x00b4,
  "acutebelowcmb",
  0x0317,
  "acutecmb",
  0x0301,
  "acutecomb",
  0x0301,
  "acutedeva",
  0x0954,
  "acutelowmod",
  0x02cf,
  "acutetonecmb",
  0x0341,
  "acyrillic",
  0x0430,
  "adblgrave",
  0x0201,
  "addakgurmukhi",
  0x0a71,
  "adeva",
  0x0905,
  "adieresis",
  0x00e4,
  "adieresiscyrillic",
  0x04d3,
  "adieresismacron",
  0x01df,
  "adotbelow",
  0x1ea1,
  "adotmacron",
  0x01e1,
  "ae",
  0x00e6,
  "aeacute",
  0x01fd,
  "aekorean",
  0x3150,
  "aemacron",
  0x01e3,
  "afii00208",
  0x2015,
  "afii08941",
  0x20a4,
  "afii10017",
  0x0410,
  "afii10018",
  0x0411,
  "afii10019",
  0x0412,
  "afii10020",
  0x0413,
  "afii10021",
  0x0414,
  "afii10022",
  0x0415,
  "afii10023",
  0x0401,
  "afii10024",
  0x0416,
  "afii10025",
  0x0417,
  "afii10026",
  0x0418,
  "afii10027",
  0x0419,
  "afii10028",
  0x041a,
  "afii10029",
  0x041b,
  "afii10030",
  0x041c,
  "afii10031",
  0x041d,
  "afii10032",
  0x041e,
  "afii10033",
  0x041f,
  "afii10034",
  0x0420,
  "afii10035",
  0x0421,
  "afii10036",
  0x0422,
  "afii10037",
  0x0423,
  "afii10038",
  0x0424,
  "afii10039",
  0x0425,
  "afii10040",
  0x0426,
  "afii10041",
  0x0427,
  "afii10042",
  0x0428,
  "afii10043",
  0x0429,
  "afii10044",
  0x042a,
  "afii10045",
  0x042b,
  "afii10046",
  0x042c,
  "afii10047",
  0x042d,
  "afii10048",
  0x042e,
  "afii10049",
  0x042f,
  "afii10050",
  0x0490,
  "afii10051",
  0x0402,
  "afii10052",
  0x0403,
  "afii10053",
  0x0404,
  "afii10054",
  0x0405,
  "afii10055",
  0x0406,
  "afii10056",
  0x0407,
  "afii10057",
  0x0408,
  "afii10058",
  0x0409,
  "afii10059",
  0x040a,
  "afii10060",
  0x040b,
  "afii10061",
  0x040c,
  "afii10062",
  0x040e,
  "afii10063",
  0xf6c4,
  "afii10064",
  0xf6c5,
  "afii10065",
  0x0430,
  "afii10066",
  0x0431,
  "afii10067",
  0x0432,
  "afii10068",
  0x0433,
  "afii10069",
  0x0434,
  "afii10070",
  0x0435,
  "afii10071",
  0x0451,
  "afii10072",
  0x0436,
  "afii10073",
  0x0437,
  "afii10074",
  0x0438,
  "afii10075",
  0x0439,
  "afii10076",
  0x043a,
  "afii10077",
  0x043b,
  "afii10078",
  0x043c,
  "afii10079",
  0x043d,
  "afii10080",
  0x043e,
  "afii10081",
  0x043f,
  "afii10082",
  0x0440,
  "afii10083",
  0x0441,
  "afii10084",
  0x0442,
  "afii10085",
  0x0443,
  "afii10086",
  0x0444,
  "afii10087",
  0x0445,
  "afii10088",
  0x0446,
  "afii10089",
  0x0447,
  "afii10090",
  0x0448,
  "afii10091",
  0x0449,
  "afii10092",
  0x044a,
  "afii10093",
  0x044b,
  "afii10094",
  0x044c,
  "afii10095",
  0x044d,
  "afii10096",
  0x044e,
  "afii10097",
  0x044f,
  "afii10098",
  0x0491,
  "afii10099",
  0x0452,
  "afii10100",
  0x0453,
  "afii10101",
  0x0454,
  "afii10102",
  0x0455,
  "afii10103",
  0x0456,
  "afii10104",
  0x0457,
  "afii10105",
  0x0458,
  "afii10106",
  0x0459,
  "afii10107",
  0x045a,
  "afii10108",
  0x045b,
  "afii10109",
  0x045c,
  "afii10110",
  0x045e,
  "afii10145",
  0x040f,
  "afii10146",
  0x0462,
  "afii10147",
  0x0472,
  "afii10148",
  0x0474,
  "afii10192",
  0xf6c6,
  "afii10193",
  0x045f,
  "afii10194",
  0x0463,
  "afii10195",
  0x0473,
  "afii10196",
  0x0475,
  "afii10831",
  0xf6c7,
  "afii10832",
  0xf6c8,
  "afii10846",
  0x04d9,
  "afii299",
  0x200e,
  "afii300",
  0x200f,
  "afii301",
  0x200d,
  "afii57381",
  0x066a,
  "afii57388",
  0x060c,
  "afii57392",
  0x0660,
  "afii57393",
  0x0661,
  "afii57394",
  0x0662,
  "afii57395",
  0x0663,
  "afii57396",
  0x0664,
  "afii57397",
  0x0665,
  "afii57398",
  0x0666,
  "afii57399",
  0x0667,
  "afii57400",
  0x0668,
  "afii57401",
  0x0669,
  "afii57403",
  0x061b,
  "afii57407",
  0x061f,
  "afii57409",
  0x0621,
  "afii57410",
  0x0622,
  "afii57411",
  0x0623,
  "afii57412",
  0x0624,
  "afii57413",
  0x0625,
  "afii57414",
  0x0626,
  "afii57415",
  0x0627,
  "afii57416",
  0x0628,
  "afii57417",
  0x0629,
  "afii57418",
  0x062a,
  "afii57419",
  0x062b,
  "afii57420",
  0x062c,
  "afii57421",
  0x062d,
  "afii57422",
  0x062e,
  "afii57423",
  0x062f,
  "afii57424",
  0x0630,
  "afii57425",
  0x0631,
  "afii57426",
  0x0632,
  "afii57427",
  0x0633,
  "afii57428",
  0x0634,
  "afii57429",
  0x0635,
  "afii57430",
  0x0636,
  "afii57431",
  0x0637,
  "afii57432",
  0x0638,
  "afii57433",
  0x0639,
  "afii57434",
  0x063a,
  "afii57440",
  0x0640,
  "afii57441",
  0x0641,
  "afii57442",
  0x0642,
  "afii57443",
  0x0643,
  "afii57444",
  0x0644,
  "afii57445",
  0x0645,
  "afii57446",
  0x0646,
  "afii57448",
  0x0648,
  "afii57449",
  0x0649,
  "afii57450",
  0x064a,
  "afii57451",
  0x064b,
  "afii57452",
  0x064c,
  "afii57453",
  0x064d,
  "afii57454",
  0x064e,
  "afii57455",
  0x064f,
  "afii57456",
  0x0650,
  "afii57457",
  0x0651,
  "afii57458",
  0x0652,
  "afii57470",
  0x0647,
  "afii57505",
  0x06a4,
  "afii57506",
  0x067e,
  "afii57507",
  0x0686,
  "afii57508",
  0x0698,
  "afii57509",
  0x06af,
  "afii57511",
  0x0679,
  "afii57512",
  0x0688,
  "afii57513",
  0x0691,
  "afii57514",
  0x06ba,
  "afii57519",
  0x06d2,
  "afii57534",
  0x06d5,
  "afii57636",
  0x20aa,
  "afii57645",
  0x05be,
  "afii57658",
  0x05c3,
  "afii57664",
  0x05d0,
  "afii57665",
  0x05d1,
  "afii57666",
  0x05d2,
  "afii57667",
  0x05d3,
  "afii57668",
  0x05d4,
  "afii57669",
  0x05d5,
  "afii57670",
  0x05d6,
  "afii57671",
  0x05d7,
  "afii57672",
  0x05d8,
  "afii57673",
  0x05d9,
  "afii57674",
  0x05da,
  "afii57675",
  0x05db,
  "afii57676",
  0x05dc,
  "afii57677",
  0x05dd,
  "afii57678",
  0x05de,
  "afii57679",
  0x05df,
  "afii57680",
  0x05e0,
  "afii57681",
  0x05e1,
  "afii57682",
  0x05e2,
  "afii57683",
  0x05e3,
  "afii57684",
  0x05e4,
  "afii57685",
  0x05e5,
  "afii57686",
  0x05e6,
  "afii57687",
  0x05e7,
  "afii57688",
  0x05e8,
  "afii57689",
  0x05e9,
  "afii57690",
  0x05ea,
  "afii57694",
  0xfb2a,
  "afii57695",
  0xfb2b,
  "afii57700",
  0xfb4b,
  "afii57705",
  0xfb1f,
  "afii57716",
  0x05f0,
  "afii57717",
  0x05f1,
  "afii57718",
  0x05f2,
  "afii57723",
  0xfb35,
  "afii57793",
  0x05b4,
  "afii57794",
  0x05b5,
  "afii57795",
  0x05b6,
  "afii57796",
  0x05bb,
  "afii57797",
  0x05b8,
  "afii57798",
  0x05b7,
  "afii57799",
  0x05b0,
  "afii57800",
  0x05b2,
  "afii57801",
  0x05b1,
  "afii57802",
  0x05b3,
  "afii57803",
  0x05c2,
  "afii57804",
  0x05c1,
  "afii57806",
  0x05b9,
  "afii57807",
  0x05bc,
  "afii57839",
  0x05bd,
  "afii57841",
  0x05bf,
  "afii57842",
  0x05c0,
  "afii57929",
  0x02bc,
  "afii61248",
  0x2105,
  "afii61289",
  0x2113,
  "afii61352",
  0x2116,
  "afii61573",
  0x202c,
  "afii61574",
  0x202d,
  "afii61575",
  0x202e,
  "afii61664",
  0x200c,
  "afii63167",
  0x066d,
  "afii64937",
  0x02bd,
  "agrave",
  0x00e0,
  "agujarati",
  0x0a85,
  "agurmukhi",
  0x0a05,
  "ahiragana",
  0x3042,
  "ahookabove",
  0x1ea3,
  "aibengali",
  0x0990,
  "aibopomofo",
  0x311e,
  "aideva",
  0x0910,
  "aiecyrillic",
  0x04d5,
  "aigujarati",
  0x0a90,
  "aigurmukhi",
  0x0a10,
  "aimatragurmukhi",
  0x0a48,
  "ainarabic",
  0x0639,
  "ainfinalarabic",
  0xfeca,
  "aininitialarabic",
  0xfecb,
  "ainmedialarabic",
  0xfecc,
  "ainvertedbreve",
  0x0203,
  "aivowelsignbengali",
  0x09c8,
  "aivowelsigndeva",
  0x0948,
  "aivowelsigngujarati",
  0x0ac8,
  "akatakana",
  0x30a2,
  "akatakanahalfwidth",
  0xff71,
  "akorean",
  0x314f,
  "alef",
  0x05d0,
  "alefarabic",
  0x0627,
  "alefdageshhebrew",
  0xfb30,
  "aleffinalarabic",
  0xfe8e,
  "alefhamzaabovearabic",
  0x0623,
  "alefhamzaabovefinalarabic",
  0xfe84,
  "alefhamzabelowarabic",
  0x0625,
  "alefhamzabelowfinalarabic",
  0xfe88,
  "alefhebrew",
  0x05d0,
  "aleflamedhebrew",
  0xfb4f,
  "alefmaddaabovearabic",
  0x0622,
  "alefmaddaabovefinalarabic",
  0xfe82,
  "alefmaksuraarabic",
  0x0649,
  "alefmaksurafinalarabic",
  0xfef0,
  "alefmaksurainitialarabic",
  0xfef3,
  "alefmaksuramedialarabic",
  0xfef4,
  "alefpatahhebrew",
  0xfb2e,
  "alefqamatshebrew",
  0xfb2f,
  "aleph",
  0x2135,
  "allequal",
  0x224c,
  "alpha",
  0x03b1,
  "alphatonos",
  0x03ac,
  "amacron",
  0x0101,
  "amonospace",
  0xff41,
  "ampersand",
  0x0026,
  "ampersandmonospace",
  0xff06,
  "ampersandsmall",
  0xf726,
  "amsquare",
  0x33c2,
  "anbopomofo",
  0x3122,
  "angbopomofo",
  0x3124,
  "angbracketleft",
  0x3008,
  "angbracketright",
  0x3009,
  "angkhankhuthai",
  0x0e5a,
  "angle",
  0x2220,
  "anglebracketleft",
  0x3008,
  "anglebracketleftvertical",
  0xfe3f,
  "anglebracketright",
  0x3009,
  "anglebracketrightvertical",
  0xfe40,
  "angleleft",
  0x2329,
  "angleright",
  0x232a,
  "angstrom",
  0x212b,
  "anoteleia",
  0x0387,
  "anudattadeva",
  0x0952,
  "anusvarabengali",
  0x0982,
  "anusvaradeva",
  0x0902,
  "anusvaragujarati",
  0x0a82,
  "aogonek",
  0x0105,
  "apaatosquare",
  0x3300,
  "aparen",
  0x249c,
  "apostrophearmenian",
  0x055a,
  "apostrophemod",
  0x02bc,
  "apple",
  0xf8ff,
  "approaches",
  0x2250,
  "approxequal",
  0x2248,
  "approxequalorimage",
  0x2252,
  "approximatelyequal",
  0x2245,
  "araeaekorean",
  0x318e,
  "araeakorean",
  0x318d,
  "arc",
  0x2312,
  "arighthalfring",
  0x1e9a,
  "aring",
  0x00e5,
  "aringacute",
  0x01fb,
  "aringbelow",
  0x1e01,
  "arrowboth",
  0x2194,
  "arrowdashdown",
  0x21e3,
  "arrowdashleft",
  0x21e0,
  "arrowdashright",
  0x21e2,
  "arrowdashup",
  0x21e1,
  "arrowdblboth",
  0x21d4,
  "arrowdbldown",
  0x21d3,
  "arrowdblleft",
  0x21d0,
  "arrowdblright",
  0x21d2,
  "arrowdblup",
  0x21d1,
  "arrowdown",
  0x2193,
  "arrowdownleft",
  0x2199,
  "arrowdownright",
  0x2198,
  "arrowdownwhite",
  0x21e9,
  "arrowheaddownmod",
  0x02c5,
  "arrowheadleftmod",
  0x02c2,
  "arrowheadrightmod",
  0x02c3,
  "arrowheadupmod",
  0x02c4,
  "arrowhorizex",
  0xf8e7,
  "arrowleft",
  0x2190,
  "arrowleftdbl",
  0x21d0,
  "arrowleftdblstroke",
  0x21cd,
  "arrowleftoverright",
  0x21c6,
  "arrowleftwhite",
  0x21e6,
  "arrowright",
  0x2192,
  "arrowrightdblstroke",
  0x21cf,
  "arrowrightheavy",
  0x279e,
  "arrowrightoverleft",
  0x21c4,
  "arrowrightwhite",
  0x21e8,
  "arrowtableft",
  0x21e4,
  "arrowtabright",
  0x21e5,
  "arrowup",
  0x2191,
  "arrowupdn",
  0x2195,
  "arrowupdnbse",
  0x21a8,
  "arrowupdownbase",
  0x21a8,
  "arrowupleft",
  0x2196,
  "arrowupleftofdown",
  0x21c5,
  "arrowupright",
  0x2197,
  "arrowupwhite",
  0x21e7,
  "arrowvertex",
  0xf8e6,
  "asciicircum",
  0x005e,
  "asciicircummonospace",
  0xff3e,
  "asciitilde",
  0x007e,
  "asciitildemonospace",
  0xff5e,
  "ascript",
  0x0251,
  "ascriptturned",
  0x0252,
  "asmallhiragana",
  0x3041,
  "asmallkatakana",
  0x30a1,
  "asmallkatakanahalfwidth",
  0xff67,
  "asterisk",
  0x002a,
  "asteriskaltonearabic",
  0x066d,
  "asteriskarabic",
  0x066d,
  "asteriskmath",
  0x2217,
  "asteriskmonospace",
  0xff0a,
  "asterisksmall",
  0xfe61,
  "asterism",
  0x2042,
  "asuperior",
  0xf6e9,
  "asymptoticallyequal",
  0x2243,
  "at",
  0x0040,
  "atilde",
  0x00e3,
  "atmonospace",
  0xff20,
  "atsmall",
  0xfe6b,
  "aturned",
  0x0250,
  "aubengali",
  0x0994,
  "aubopomofo",
  0x3120,
  "audeva",
  0x0914,
  "augujarati",
  0x0a94,
  "augurmukhi",
  0x0a14,
  "aulengthmarkbengali",
  0x09d7,
  "aumatragurmukhi",
  0x0a4c,
  "auvowelsignbengali",
  0x09cc,
  "auvowelsigndeva",
  0x094c,
  "auvowelsigngujarati",
  0x0acc,
  "avagrahadeva",
  0x093d,
  "aybarmenian",
  0x0561,
  "ayin",
  0x05e2,
  "ayinaltonehebrew",
  0xfb20,
  "ayinhebrew",
  0x05e2,
  "b",
  0x0062,
  "babengali",
  0x09ac,
  "backslash",
  0x005c,
  "backslashmonospace",
  0xff3c,
  "badeva",
  0x092c,
  "bagujarati",
  0x0aac,
  "bagurmukhi",
  0x0a2c,
  "bahiragana",
  0x3070,
  "bahtthai",
  0x0e3f,
  "bakatakana",
  0x30d0,
  "bar",
  0x007c,
  "barmonospace",
  0xff5c,
  "bbopomofo",
  0x3105,
  "bcircle",
  0x24d1,
  "bdotaccent",
  0x1e03,
  "bdotbelow",
  0x1e05,
  "beamedsixteenthnotes",
  0x266c,
  "because",
  0x2235,
  "becyrillic",
  0x0431,
  "beharabic",
  0x0628,
  "behfinalarabic",
  0xfe90,
  "behinitialarabic",
  0xfe91,
  "behiragana",
  0x3079,
  "behmedialarabic",
  0xfe92,
  "behmeeminitialarabic",
  0xfc9f,
  "behmeemisolatedarabic",
  0xfc08,
  "behnoonfinalarabic",
  0xfc6d,
  "bekatakana",
  0x30d9,
  "benarmenian",
  0x0562,
  "bet",
  0x05d1,
  "beta",
  0x03b2,
  "betasymbolgreek",
  0x03d0,
  "betdagesh",
  0xfb31,
  "betdageshhebrew",
  0xfb31,
  "bethebrew",
  0x05d1,
  "betrafehebrew",
  0xfb4c,
  "bhabengali",
  0x09ad,
  "bhadeva",
  0x092d,
  "bhagujarati",
  0x0aad,
  "bhagurmukhi",
  0x0a2d,
  "bhook",
  0x0253,
  "bihiragana",
  0x3073,
  "bikatakana",
  0x30d3,
  "bilabialclick",
  0x0298,
  "bindigurmukhi",
  0x0a02,
  "birusquare",
  0x3331,
  "blackcircle",
  0x25cf,
  "blackdiamond",
  0x25c6,
  "blackdownpointingtriangle",
  0x25bc,
  "blackleftpointingpointer",
  0x25c4,
  "blackleftpointingtriangle",
  0x25c0,
  "blacklenticularbracketleft",
  0x3010,
  "blacklenticularbracketleftvertical",
  0xfe3b,
  "blacklenticularbracketright",
  0x3011,
  "blacklenticularbracketrightvertical",
  0xfe3c,
  "blacklowerlefttriangle",
  0x25e3,
  "blacklowerrighttriangle",
  0x25e2,
  "blackrectangle",
  0x25ac,
  "blackrightpointingpointer",
  0x25ba,
  "blackrightpointingtriangle",
  0x25b6,
  "blacksmallsquare",
  0x25aa,
  "blacksmilingface",
  0x263b,
  "blacksquare",
  0x25a0,
  "blackstar",
  0x2605,
  "blackupperlefttriangle",
  0x25e4,
  "blackupperrighttriangle",
  0x25e5,
  "blackuppointingsmalltriangle",
  0x25b4,
  "blackuppointingtriangle",
  0x25b2,
  "blank",
  0x2423,
  "blinebelow",
  0x1e07,
  "block",
  0x2588,
  "bmonospace",
  0xff42,
  "bobaimaithai",
  0x0e1a,
  "bohiragana",
  0x307c,
  "bokatakana",
  0x30dc,
  "bparen",
  0x249d,
  "bqsquare",
  0x33c3,
  "braceex",
  0xf8f4,
  "braceleft",
  0x007b,
  "braceleftbt",
  0xf8f3,
  "braceleftmid",
  0xf8f2,
  "braceleftmonospace",
  0xff5b,
  "braceleftsmall",
  0xfe5b,
  "bracelefttp",
  0xf8f1,
  "braceleftvertical",
  0xfe37,
  "braceright",
  0x007d,
  "bracerightbt",
  0xf8fe,
  "bracerightmid",
  0xf8fd,
  "bracerightmonospace",
  0xff5d,
  "bracerightsmall",
  0xfe5c,
  "bracerighttp",
  0xf8fc,
  "bracerightvertical",
  0xfe38,
  "bracketleft",
  0x005b,
  "bracketleftbt",
  0xf8f0,
  "bracketleftex",
  0xf8ef,
  "bracketleftmonospace",
  0xff3b,
  "bracketlefttp",
  0xf8ee,
  "bracketright",
  0x005d,
  "bracketrightbt",
  0xf8fb,
  "bracketrightex",
  0xf8fa,
  "bracketrightmonospace",
  0xff3d,
  "bracketrighttp",
  0xf8f9,
  "breve",
  0x02d8,
  "brevebelowcmb",
  0x032e,
  "brevecmb",
  0x0306,
  "breveinvertedbelowcmb",
  0x032f,
  "breveinvertedcmb",
  0x0311,
  "breveinverteddoublecmb",
  0x0361,
  "bridgebelowcmb",
  0x032a,
  "bridgeinvertedbelowcmb",
  0x033a,
  "brokenbar",
  0x00a6,
  "bstroke",
  0x0180,
  "bsuperior",
  0xf6ea,
  "btopbar",
  0x0183,
  "buhiragana",
  0x3076,
  "bukatakana",
  0x30d6,
  "bullet",
  0x2022,
  "bulletinverse",
  0x25d8,
  "bulletoperator",
  0x2219,
  "bullseye",
  0x25ce,
  "c",
  0x0063,
  "caarmenian",
  0x056e,
  "cabengali",
  0x099a,
  "cacute",
  0x0107,
  "cadeva",
  0x091a,
  "cagujarati",
  0x0a9a,
  "cagurmukhi",
  0x0a1a,
  "calsquare",
  0x3388,
  "candrabindubengali",
  0x0981,
  "candrabinducmb",
  0x0310,
  "candrabindudeva",
  0x0901,
  "candrabindugujarati",
  0x0a81,
  "capslock",
  0x21ea,
  "careof",
  0x2105,
  "caron",
  0x02c7,
  "caronbelowcmb",
  0x032c,
  "caroncmb",
  0x030c,
  "carriagereturn",
  0x21b5,
  "cbopomofo",
  0x3118,
  "ccaron",
  0x010d,
  "ccedilla",
  0x00e7,
  "ccedillaacute",
  0x1e09,
  "ccircle",
  0x24d2,
  "ccircumflex",
  0x0109,
  "ccurl",
  0x0255,
  "cdot",
  0x010b,
  "cdotaccent",
  0x010b,
  "cdsquare",
  0x33c5,
  "cedilla",
  0x00b8,
  "cedillacmb",
  0x0327,
  "cent",
  0x00a2,
  "centigrade",
  0x2103,
  "centinferior",
  0xf6df,
  "centmonospace",
  0xffe0,
  "centoldstyle",
  0xf7a2,
  "centsuperior",
  0xf6e0,
  "chaarmenian",
  0x0579,
  "chabengali",
  0x099b,
  "chadeva",
  0x091b,
  "chagujarati",
  0x0a9b,
  "chagurmukhi",
  0x0a1b,
  "chbopomofo",
  0x3114,
  "cheabkhasiancyrillic",
  0x04bd,
  "checkmark",
  0x2713,
  "checyrillic",
  0x0447,
  "chedescenderabkhasiancyrillic",
  0x04bf,
  "chedescendercyrillic",
  0x04b7,
  "chedieresiscyrillic",
  0x04f5,
  "cheharmenian",
  0x0573,
  "chekhakassiancyrillic",
  0x04cc,
  "cheverticalstrokecyrillic",
  0x04b9,
  "chi",
  0x03c7,
  "chieuchacirclekorean",
  0x3277,
  "chieuchaparenkorean",
  0x3217,
  "chieuchcirclekorean",
  0x3269,
  "chieuchkorean",
  0x314a,
  "chieuchparenkorean",
  0x3209,
  "chochangthai",
  0x0e0a,
  "chochanthai",
  0x0e08,
  "chochingthai",
  0x0e09,
  "chochoethai",
  0x0e0c,
  "chook",
  0x0188,
  "cieucacirclekorean",
  0x3276,
  "cieucaparenkorean",
  0x3216,
  "cieuccirclekorean",
  0x3268,
  "cieuckorean",
  0x3148,
  "cieucparenkorean",
  0x3208,
  "cieucuparenkorean",
  0x321c,
  "circle",
  0x25cb,
  "circlecopyrt",
  0x00a9,
  "circlemultiply",
  0x2297,
  "circleot",
  0x2299,
  "circleplus",
  0x2295,
  "circlepostalmark",
  0x3036,
  "circlewithlefthalfblack",
  0x25d0,
  "circlewithrighthalfblack",
  0x25d1,
  "circumflex",
  0x02c6,
  "circumflexbelowcmb",
  0x032d,
  "circumflexcmb",
  0x0302,
  "clear",
  0x2327,
  "clickalveolar",
  0x01c2,
  "clickdental",
  0x01c0,
  "clicklateral",
  0x01c1,
  "clickretroflex",
  0x01c3,
  "club",
  0x2663,
  "clubsuitblack",
  0x2663,
  "clubsuitwhite",
  0x2667,
  "cmcubedsquare",
  0x33a4,
  "cmonospace",
  0xff43,
  "cmsquaredsquare",
  0x33a0,
  "coarmenian",
  0x0581,
  "colon",
  0x003a,
  "colonmonetary",
  0x20a1,
  "colonmonospace",
  0xff1a,
  "colonsign",
  0x20a1,
  "colonsmall",
  0xfe55,
  "colontriangularhalfmod",
  0x02d1,
  "colontriangularmod",
  0x02d0,
  "comma",
  0x002c,
  "commaabovecmb",
  0x0313,
  "commaaboverightcmb",
  0x0315,
  "commaaccent",
  0xf6c3,
  "commaarabic",
  0x060c,
  "commaarmenian",
  0x055d,
  "commainferior",
  0xf6e1,
  "commamonospace",
  0xff0c,
  "commareversedabovecmb",
  0x0314,
  "commareversedmod",
  0x02bd,
  "commasmall",
  0xfe50,
  "commasuperior",
  0xf6e2,
  "commaturnedabovecmb",
  0x0312,
  "commaturnedmod",
  0x02bb,
  "compass",
  0x263c,
  "congruent",
  0x2245,
  "contourintegral",
  0x222e,
  "control",
  0x2303,
  "controlACK",
  0x0006,
  "controlBEL",
  0x0007,
  "controlBS",
  0x0008,
  "controlCAN",
  0x0018,
  "controlCR",
  0x000d,
  "controlDC1",
  0x0011,
  "controlDC2",
  0x0012,
  "controlDC3",
  0x0013,
  "controlDC4",
  0x0014,
  "controlDEL",
  0x007f,
  "controlDLE",
  0x0010,
  "controlEM",
  0x0019,
  "controlENQ",
  0x0005,
  "controlEOT",
  0x0004,
  "controlESC",
  0x001b,
  "controlETB",
  0x0017,
  "controlETX",
  0x0003,
  "controlFF",
  0x000c,
  "controlFS",
  0x001c,
  "controlGS",
  0x001d,
  "controlHT",
  0x0009,
  "controlLF",
  0x000a,
  "controlNAK",
  0x0015,
  "controlNULL",
  0x0000,
  "controlRS",
  0x001e,
  "controlSI",
  0x000f,
  "controlSO",
  0x000e,
  "controlSOT",
  0x0002,
  "controlSTX",
  0x0001,
  "controlSUB",
  0x001a,
  "controlSYN",
  0x0016,
  "controlUS",
  0x001f,
  "controlVT",
  0x000b,
  "copyright",
  0x00a9,
  "copyrightsans",
  0xf8e9,
  "copyrightserif",
  0xf6d9,
  "cornerbracketleft",
  0x300c,
  "cornerbracketlefthalfwidth",
  0xff62,
  "cornerbracketleftvertical",
  0xfe41,
  "cornerbracketright",
  0x300d,
  "cornerbracketrighthalfwidth",
  0xff63,
  "cornerbracketrightvertical",
  0xfe42,
  "corporationsquare",
  0x337f,
  "cosquare",
  0x33c7,
  "coverkgsquare",
  0x33c6,
  "cparen",
  0x249e,
  "cruzeiro",
  0x20a2,
  "cstretched",
  0x0297,
  "curlyand",
  0x22cf,
  "curlyor",
  0x22ce,
  "currency",
  0x00a4,
  "cyrBreve",
  0xf6d1,
  "cyrFlex",
  0xf6d2,
  "cyrbreve",
  0xf6d4,
  "cyrflex",
  0xf6d5,
  "d",
  0x0064,
  "daarmenian",
  0x0564,
  "dabengali",
  0x09a6,
  "dadarabic",
  0x0636,
  "dadeva",
  0x0926,
  "dadfinalarabic",
  0xfebe,
  "dadinitialarabic",
  0xfebf,
  "dadmedialarabic",
  0xfec0,
  "dagesh",
  0x05bc,
  "dageshhebrew",
  0x05bc,
  "dagger",
  0x2020,
  "daggerdbl",
  0x2021,
  "dagujarati",
  0x0aa6,
  "dagurmukhi",
  0x0a26,
  "dahiragana",
  0x3060,
  "dakatakana",
  0x30c0,
  "dalarabic",
  0x062f,
  "dalet",
  0x05d3,
  "daletdagesh",
  0xfb33,
  "daletdageshhebrew",
  0xfb33,
  "dalethebrew",
  0x05d3,
  "dalfinalarabic",
  0xfeaa,
  "dammaarabic",
  0x064f,
  "dammalowarabic",
  0x064f,
  "dammatanaltonearabic",
  0x064c,
  "dammatanarabic",
  0x064c,
  "danda",
  0x0964,
  "dargahebrew",
  0x05a7,
  "dargalefthebrew",
  0x05a7,
  "dasiapneumatacyrilliccmb",
  0x0485,
  "dblGrave",
  0xf6d3,
  "dblanglebracketleft",
  0x300a,
  "dblanglebracketleftvertical",
  0xfe3d,
  "dblanglebracketright",
  0x300b,
  "dblanglebracketrightvertical",
  0xfe3e,
  "dblarchinvertedbelowcmb",
  0x032b,
  "dblarrowleft",
  0x21d4,
  "dblarrowright",
  0x21d2,
  "dbldanda",
  0x0965,
  "dblgrave",
  0xf6d6,
  "dblgravecmb",
  0x030f,
  "dblintegral",
  0x222c,
  "dbllowline",
  0x2017,
  "dbllowlinecmb",
  0x0333,
  "dbloverlinecmb",
  0x033f,
  "dblprimemod",
  0x02ba,
  "dblverticalbar",
  0x2016,
  "dblverticallineabovecmb",
  0x030e,
  "dbopomofo",
  0x3109,
  "dbsquare",
  0x33c8,
  "dcaron",
  0x010f,
  "dcedilla",
  0x1e11,
  "dcircle",
  0x24d3,
  "dcircumflexbelow",
  0x1e13,
  "dcroat",
  0x0111,
  "ddabengali",
  0x09a1,
  "ddadeva",
  0x0921,
  "ddagujarati",
  0x0aa1,
  "ddagurmukhi",
  0x0a21,
  "ddalarabic",
  0x0688,
  "ddalfinalarabic",
  0xfb89,
  "dddhadeva",
  0x095c,
  "ddhabengali",
  0x09a2,
  "ddhadeva",
  0x0922,
  "ddhagujarati",
  0x0aa2,
  "ddhagurmukhi",
  0x0a22,
  "ddotaccent",
  0x1e0b,
  "ddotbelow",
  0x1e0d,
  "decimalseparatorarabic",
  0x066b,
  "decimalseparatorpersian",
  0x066b,
  "decyrillic",
  0x0434,
  "degree",
  0x00b0,
  "dehihebrew",
  0x05ad,
  "dehiragana",
  0x3067,
  "deicoptic",
  0x03ef,
  "dekatakana",
  0x30c7,
  "deleteleft",
  0x232b,
  "deleteright",
  0x2326,
  "delta",
  0x03b4,
  "deltaturned",
  0x018d,
  "denominatorminusonenumeratorbengali",
  0x09f8,
  "dezh",
  0x02a4,
  "dhabengali",
  0x09a7,
  "dhadeva",
  0x0927,
  "dhagujarati",
  0x0aa7,
  "dhagurmukhi",
  0x0a27,
  "dhook",
  0x0257,
  "dialytikatonos",
  0x0385,
  "dialytikatonoscmb",
  0x0344,
  "diamond",
  0x2666,
  "diamondsuitwhite",
  0x2662,
  "dieresis",
  0x00a8,
  "dieresisacute",
  0xf6d7,
  "dieresisbelowcmb",
  0x0324,
  "dieresiscmb",
  0x0308,
  "dieresisgrave",
  0xf6d8,
  "dieresistonos",
  0x0385,
  "dihiragana",
  0x3062,
  "dikatakana",
  0x30c2,
  "dittomark",
  0x3003,
  "divide",
  0x00f7,
  "divides",
  0x2223,
  "divisionslash",
  0x2215,
  "djecyrillic",
  0x0452,
  "dkshade",
  0x2593,
  "dlinebelow",
  0x1e0f,
  "dlsquare",
  0x3397,
  "dmacron",
  0x0111,
  "dmonospace",
  0xff44,
  "dnblock",
  0x2584,
  "dochadathai",
  0x0e0e,
  "dodekthai",
  0x0e14,
  "dohiragana",
  0x3069,
  "dokatakana",
  0x30c9,
  "dollar",
  0x0024,
  "dollarinferior",
  0xf6e3,
  "dollarmonospace",
  0xff04,
  "dollaroldstyle",
  0xf724,
  "dollarsmall",
  0xfe69,
  "dollarsuperior",
  0xf6e4,
  "dong",
  0x20ab,
  "dorusquare",
  0x3326,
  "dotaccent",
  0x02d9,
  "dotaccentcmb",
  0x0307,
  "dotbelowcmb",
  0x0323,
  "dotbelowcomb",
  0x0323,
  "dotkatakana",
  0x30fb,
  "dotlessi",
  0x0131,
  "dotlessj",
  0xf6be,
  "dotlessjstrokehook",
  0x0284,
  "dotmath",
  0x22c5,
  "dottedcircle",
  0x25cc,
  "doubleyodpatah",
  0xfb1f,
  "doubleyodpatahhebrew",
  0xfb1f,
  "downtackbelowcmb",
  0x031e,
  "downtackmod",
  0x02d5,
  "dparen",
  0x249f,
  "dsuperior",
  0xf6eb,
  "dtail",
  0x0256,
  "dtopbar",
  0x018c,
  "duhiragana",
  0x3065,
  "dukatakana",
  0x30c5,
  "dz",
  0x01f3,
  "dzaltone",
  0x02a3,
  "dzcaron",
  0x01c6,
  "dzcurl",
  0x02a5,
  "dzeabkhasiancyrillic",
  0x04e1,
  "dzecyrillic",
  0x0455,
  "dzhecyrillic",
  0x045f,
  "e",
  0x0065,
  "eacute",
  0x00e9,
  "earth",
  0x2641,
  "ebengali",
  0x098f,
  "ebopomofo",
  0x311c,
  "ebreve",
  0x0115,
  "ecandradeva",
  0x090d,
  "ecandragujarati",
  0x0a8d,
  "ecandravowelsigndeva",
  0x0945,
  "ecandravowelsigngujarati",
  0x0ac5,
  "ecaron",
  0x011b,
  "ecedillabreve",
  0x1e1d,
  "echarmenian",
  0x0565,
  "echyiwnarmenian",
  0x0587,
  "ecircle",
  0x24d4,
  "ecircumflex",
  0x00ea,
  "ecircumflexacute",
  0x1ebf,
  "ecircumflexbelow",
  0x1e19,
  "ecircumflexdotbelow",
  0x1ec7,
  "ecircumflexgrave",
  0x1ec1,
  "ecircumflexhookabove",
  0x1ec3,
  "ecircumflextilde",
  0x1ec5,
  "ecyrillic",
  0x0454,
  "edblgrave",
  0x0205,
  "edeva",
  0x090f,
  "edieresis",
  0x00eb,
  "edot",
  0x0117,
  "edotaccent",
  0x0117,
  "edotbelow",
  0x1eb9,
  "eegurmukhi",
  0x0a0f,
  "eematragurmukhi",
  0x0a47,
  "efcyrillic",
  0x0444,
  "egrave",
  0x00e8,
  "egujarati",
  0x0a8f,
  "eharmenian",
  0x0567,
  "ehbopomofo",
  0x311d,
  "ehiragana",
  0x3048,
  "ehookabove",
  0x1ebb,
  "eibopomofo",
  0x311f,
  "eight",
  0x0038,
  "eightarabic",
  0x0668,
  "eightbengali",
  0x09ee,
  "eightcircle",
  0x2467,
  "eightcircleinversesansserif",
  0x2791,
  "eightdeva",
  0x096e,
  "eighteencircle",
  0x2471,
  "eighteenparen",
  0x2485,
  "eighteenperiod",
  0x2499,
  "eightgujarati",
  0x0aee,
  "eightgurmukhi",
  0x0a6e,
  "eighthackarabic",
  0x0668,
  "eighthangzhou",
  0x3028,
  "eighthnotebeamed",
  0x266b,
  "eightideographicparen",
  0x3227,
  "eightinferior",
  0x2088,
  "eightmonospace",
  0xff18,
  "eightoldstyle",
  0xf738,
  "eightparen",
  0x247b,
  "eightperiod",
  0x248f,
  "eightpersian",
  0x06f8,
  "eightroman",
  0x2177,
  "eightsuperior",
  0x2078,
  "eightthai",
  0x0e58,
  "einvertedbreve",
  0x0207,
  "eiotifiedcyrillic",
  0x0465,
  "ekatakana",
  0x30a8,
  "ekatakanahalfwidth",
  0xff74,
  "ekonkargurmukhi",
  0x0a74,
  "ekorean",
  0x3154,
  "elcyrillic",
  0x043b,
  "element",
  0x2208,
  "elevencircle",
  0x246a,
  "elevenparen",
  0x247e,
  "elevenperiod",
  0x2492,
  "elevenroman",
  0x217a,
  "ellipsis",
  0x2026,
  "ellipsisvertical",
  0x22ee,
  "emacron",
  0x0113,
  "emacronacute",
  0x1e17,
  "emacrongrave",
  0x1e15,
  "emcyrillic",
  0x043c,
  "emdash",
  0x2014,
  "emdashvertical",
  0xfe31,
  "emonospace",
  0xff45,
  "emphasismarkarmenian",
  0x055b,
  "emptyset",
  0x2205,
  "enbopomofo",
  0x3123,
  "encyrillic",
  0x043d,
  "endash",
  0x2013,
  "endashvertical",
  0xfe32,
  "endescendercyrillic",
  0x04a3,
  "eng",
  0x014b,
  "engbopomofo",
  0x3125,
  "enghecyrillic",
  0x04a5,
  "enhookcyrillic",
  0x04c8,
  "enspace",
  0x2002,
  "eogonek",
  0x0119,
  "eokorean",
  0x3153,
  "eopen",
  0x025b,
  "eopenclosed",
  0x029a,
  "eopenreversed",
  0x025c,
  "eopenreversedclosed",
  0x025e,
  "eopenreversedhook",
  0x025d,
  "eparen",
  0x24a0,
  "epsilon",
  0x03b5,
  "epsilontonos",
  0x03ad,
  "equal",
  0x003d,
  "equalmonospace",
  0xff1d,
  "equalsmall",
  0xfe66,
  "equalsuperior",
  0x207c,
  "equivalence",
  0x2261,
  "erbopomofo",
  0x3126,
  "ercyrillic",
  0x0440,
  "ereversed",
  0x0258,
  "ereversedcyrillic",
  0x044d,
  "escyrillic",
  0x0441,
  "esdescendercyrillic",
  0x04ab,
  "esh",
  0x0283,
  "eshcurl",
  0x0286,
  "eshortdeva",
  0x090e,
  "eshortvowelsigndeva",
  0x0946,
  "eshreversedloop",
  0x01aa,
  "eshsquatreversed",
  0x0285,
  "esmallhiragana",
  0x3047,
  "esmallkatakana",
  0x30a7,
  "esmallkatakanahalfwidth",
  0xff6a,
  "estimated",
  0x212e,
  "esuperior",
  0xf6ec,
  "eta",
  0x03b7,
  "etarmenian",
  0x0568,
  "etatonos",
  0x03ae,
  "eth",
  0x00f0,
  "etilde",
  0x1ebd,
  "etildebelow",
  0x1e1b,
  "etnahtafoukhhebrew",
  0x0591,
  "etnahtafoukhlefthebrew",
  0x0591,
  "etnahtahebrew",
  0x0591,
  "etnahtalefthebrew",
  0x0591,
  "eturned",
  0x01dd,
  "eukorean",
  0x3161,
  "euro",
  0x20ac,
  "evowelsignbengali",
  0x09c7,
  "evowelsigndeva",
  0x0947,
  "evowelsigngujarati",
  0x0ac7,
  "exclam",
  0x0021,
  "exclamarmenian",
  0x055c,
  "exclamdbl",
  0x203c,
  "exclamdown",
  0x00a1,
  "exclamdownsmall",
  0xf7a1,
  "exclammonospace",
  0xff01,
  "exclamsmall",
  0xf721,
  "existential",
  0x2203,
  "ezh",
  0x0292,
  "ezhcaron",
  0x01ef,
  "ezhcurl",
  0x0293,
  "ezhreversed",
  0x01b9,
  "ezhtail",
  0x01ba,
  "f",
  0x0066,
  "fadeva",
  0x095e,
  "fagurmukhi",
  0x0a5e,
  "fahrenheit",
  0x2109,
  "fathaarabic",
  0x064e,
  "fathalowarabic",
  0x064e,
  "fathatanarabic",
  0x064b,
  "fbopomofo",
  0x3108,
  "fcircle",
  0x24d5,
  "fdotaccent",
  0x1e1f,
  "feharabic",
  0x0641,
  "feharmenian",
  0x0586,
  "fehfinalarabic",
  0xfed2,
  "fehinitialarabic",
  0xfed3,
  "fehmedialarabic",
  0xfed4,
  "feicoptic",
  0x03e5,
  "female",
  0x2640,
  "ff",
  0xfb00,
  "f_f",
  0xfb00,
  "ffi",
  0xfb03,
  "f_f_i",
  0xfb03,
  "ffl",
  0xfb04,
  "f_f_l",
  0xfb04,
  "fi",
  0xfb01,
  "f_i",
  0xfb01,
  "fifteencircle",
  0x246e,
  "fifteenparen",
  0x2482,
  "fifteenperiod",
  0x2496,
  "figuredash",
  0x2012,
  "filledbox",
  0x25a0,
  "filledrect",
  0x25ac,
  "finalkaf",
  0x05da,
  "finalkafdagesh",
  0xfb3a,
  "finalkafdageshhebrew",
  0xfb3a,
  "finalkafhebrew",
  0x05da,
  "finalmem",
  0x05dd,
  "finalmemhebrew",
  0x05dd,
  "finalnun",
  0x05df,
  "finalnunhebrew",
  0x05df,
  "finalpe",
  0x05e3,
  "finalpehebrew",
  0x05e3,
  "finaltsadi",
  0x05e5,
  "finaltsadihebrew",
  0x05e5,
  "firsttonechinese",
  0x02c9,
  "fisheye",
  0x25c9,
  "fitacyrillic",
  0x0473,
  "five",
  0x0035,
  "fivearabic",
  0x0665,
  "fivebengali",
  0x09eb,
  "fivecircle",
  0x2464,
  "fivecircleinversesansserif",
  0x278e,
  "fivedeva",
  0x096b,
  "fiveeighths",
  0x215d,
  "fivegujarati",
  0x0aeb,
  "fivegurmukhi",
  0x0a6b,
  "fivehackarabic",
  0x0665,
  "fivehangzhou",
  0x3025,
  "fiveideographicparen",
  0x3224,
  "fiveinferior",
  0x2085,
  "fivemonospace",
  0xff15,
  "fiveoldstyle",
  0xf735,
  "fiveparen",
  0x2478,
  "fiveperiod",
  0x248c,
  "fivepersian",
  0x06f5,
  "fiveroman",
  0x2174,
  "fivesuperior",
  0x2075,
  "fivethai",
  0x0e55,
  "fl",
  0xfb02,
  "f_l",
  0xfb02,
  "florin",
  0x0192,
  "fmonospace",
  0xff46,
  "fmsquare",
  0x3399,
  "fofanthai",
  0x0e1f,
  "fofathai",
  0x0e1d,
  "fongmanthai",
  0x0e4f,
  "forall",
  0x2200,
  "four",
  0x0034,
  "fourarabic",
  0x0664,
  "fourbengali",
  0x09ea,
  "fourcircle",
  0x2463,
  "fourcircleinversesansserif",
  0x278d,
  "fourdeva",
  0x096a,
  "fourgujarati",
  0x0aea,
  "fourgurmukhi",
  0x0a6a,
  "fourhackarabic",
  0x0664,
  "fourhangzhou",
  0x3024,
  "fourideographicparen",
  0x3223,
  "fourinferior",
  0x2084,
  "fourmonospace",
  0xff14,
  "fournumeratorbengali",
  0x09f7,
  "fouroldstyle",
  0xf734,
  "fourparen",
  0x2477,
  "fourperiod",
  0x248b,
  "fourpersian",
  0x06f4,
  "fourroman",
  0x2173,
  "foursuperior",
  0x2074,
  "fourteencircle",
  0x246d,
  "fourteenparen",
  0x2481,
  "fourteenperiod",
  0x2495,
  "fourthai",
  0x0e54,
  "fourthtonechinese",
  0x02cb,
  "fparen",
  0x24a1,
  "fraction",
  0x2044,
  "franc",
  0x20a3,
  "g",
  0x0067,
  "gabengali",
  0x0997,
  "gacute",
  0x01f5,
  "gadeva",
  0x0917,
  "gafarabic",
  0x06af,
  "gaffinalarabic",
  0xfb93,
  "gafinitialarabic",
  0xfb94,
  "gafmedialarabic",
  0xfb95,
  "gagujarati",
  0x0a97,
  "gagurmukhi",
  0x0a17,
  "gahiragana",
  0x304c,
  "gakatakana",
  0x30ac,
  "gamma",
  0x03b3,
  "gammalatinsmall",
  0x0263,
  "gammasuperior",
  0x02e0,
  "gangiacoptic",
  0x03eb,
  "gbopomofo",
  0x310d,
  "gbreve",
  0x011f,
  "gcaron",
  0x01e7,
  "gcedilla",
  0x0123,
  "gcircle",
  0x24d6,
  "gcircumflex",
  0x011d,
  "gcommaaccent",
  0x0123,
  "gdot",
  0x0121,
  "gdotaccent",
  0x0121,
  "gecyrillic",
  0x0433,
  "gehiragana",
  0x3052,
  "gekatakana",
  0x30b2,
  "geometricallyequal",
  0x2251,
  "gereshaccenthebrew",
  0x059c,
  "gereshhebrew",
  0x05f3,
  "gereshmuqdamhebrew",
  0x059d,
  "germandbls",
  0x00df,
  "gershayimaccenthebrew",
  0x059e,
  "gershayimhebrew",
  0x05f4,
  "getamark",
  0x3013,
  "ghabengali",
  0x0998,
  "ghadarmenian",
  0x0572,
  "ghadeva",
  0x0918,
  "ghagujarati",
  0x0a98,
  "ghagurmukhi",
  0x0a18,
  "ghainarabic",
  0x063a,
  "ghainfinalarabic",
  0xfece,
  "ghaininitialarabic",
  0xfecf,
  "ghainmedialarabic",
  0xfed0,
  "ghemiddlehookcyrillic",
  0x0495,
  "ghestrokecyrillic",
  0x0493,
  "gheupturncyrillic",
  0x0491,
  "ghhadeva",
  0x095a,
  "ghhagurmukhi",
  0x0a5a,
  "ghook",
  0x0260,
  "ghzsquare",
  0x3393,
  "gihiragana",
  0x304e,
  "gikatakana",
  0x30ae,
  "gimarmenian",
  0x0563,
  "gimel",
  0x05d2,
  "gimeldagesh",
  0xfb32,
  "gimeldageshhebrew",
  0xfb32,
  "gimelhebrew",
  0x05d2,
  "gjecyrillic",
  0x0453,
  "glottalinvertedstroke",
  0x01be,
  "glottalstop",
  0x0294,
  "glottalstopinverted",
  0x0296,
  "glottalstopmod",
  0x02c0,
  "glottalstopreversed",
  0x0295,
  "glottalstopreversedmod",
  0x02c1,
  "glottalstopreversedsuperior",
  0x02e4,
  "glottalstopstroke",
  0x02a1,
  "glottalstopstrokereversed",
  0x02a2,
  "gmacron",
  0x1e21,
  "gmonospace",
  0xff47,
  "gohiragana",
  0x3054,
  "gokatakana",
  0x30b4,
  "gparen",
  0x24a2,
  "gpasquare",
  0x33ac,
  "gradient",
  0x2207,
  "grave",
  0x0060,
  "gravebelowcmb",
  0x0316,
  "gravecmb",
  0x0300,
  "gravecomb",
  0x0300,
  "gravedeva",
  0x0953,
  "gravelowmod",
  0x02ce,
  "gravemonospace",
  0xff40,
  "gravetonecmb",
  0x0340,
  "greater",
  0x003e,
  "greaterequal",
  0x2265,
  "greaterequalorless",
  0x22db,
  "greatermonospace",
  0xff1e,
  "greaterorequivalent",
  0x2273,
  "greaterorless",
  0x2277,
  "greateroverequal",
  0x2267,
  "greatersmall",
  0xfe65,
  "gscript",
  0x0261,
  "gstroke",
  0x01e5,
  "guhiragana",
  0x3050,
  "guillemotleft",
  0x00ab,
  "guillemotright",
  0x00bb,
  "guilsinglleft",
  0x2039,
  "guilsinglright",
  0x203a,
  "gukatakana",
  0x30b0,
  "guramusquare",
  0x3318,
  "gysquare",
  0x33c9,
  "h",
  0x0068,
  "haabkhasiancyrillic",
  0x04a9,
  "haaltonearabic",
  0x06c1,
  "habengali",
  0x09b9,
  "hadescendercyrillic",
  0x04b3,
  "hadeva",
  0x0939,
  "hagujarati",
  0x0ab9,
  "hagurmukhi",
  0x0a39,
  "haharabic",
  0x062d,
  "hahfinalarabic",
  0xfea2,
  "hahinitialarabic",
  0xfea3,
  "hahiragana",
  0x306f,
  "hahmedialarabic",
  0xfea4,
  "haitusquare",
  0x332a,
  "hakatakana",
  0x30cf,
  "hakatakanahalfwidth",
  0xff8a,
  "halantgurmukhi",
  0x0a4d,
  "hamzaarabic",
  0x0621,
  "hamzalowarabic",
  0x0621,
  "hangulfiller",
  0x3164,
  "hardsigncyrillic",
  0x044a,
  "harpoonleftbarbup",
  0x21bc,
  "harpoonrightbarbup",
  0x21c0,
  "hasquare",
  0x33ca,
  "hatafpatah",
  0x05b2,
  "hatafpatah16",
  0x05b2,
  "hatafpatah23",
  0x05b2,
  "hatafpatah2f",
  0x05b2,
  "hatafpatahhebrew",
  0x05b2,
  "hatafpatahnarrowhebrew",
  0x05b2,
  "hatafpatahquarterhebrew",
  0x05b2,
  "hatafpatahwidehebrew",
  0x05b2,
  "hatafqamats",
  0x05b3,
  "hatafqamats1b",
  0x05b3,
  "hatafqamats28",
  0x05b3,
  "hatafqamats34",
  0x05b3,
  "hatafqamatshebrew",
  0x05b3,
  "hatafqamatsnarrowhebrew",
  0x05b3,
  "hatafqamatsquarterhebrew",
  0x05b3,
  "hatafqamatswidehebrew",
  0x05b3,
  "hatafsegol",
  0x05b1,
  "hatafsegol17",
  0x05b1,
  "hatafsegol24",
  0x05b1,
  "hatafsegol30",
  0x05b1,
  "hatafsegolhebrew",
  0x05b1,
  "hatafsegolnarrowhebrew",
  0x05b1,
  "hatafsegolquarterhebrew",
  0x05b1,
  "hatafsegolwidehebrew",
  0x05b1,
  "hbar",
  0x0127,
  "hbopomofo",
  0x310f,
  "hbrevebelow",
  0x1e2b,
  "hcedilla",
  0x1e29,
  "hcircle",
  0x24d7,
  "hcircumflex",
  0x0125,
  "hdieresis",
  0x1e27,
  "hdotaccent",
  0x1e23,
  "hdotbelow",
  0x1e25,
  "he",
  0x05d4,
  "heart",
  0x2665,
  "heartsuitblack",
  0x2665,
  "heartsuitwhite",
  0x2661,
  "hedagesh",
  0xfb34,
  "hedageshhebrew",
  0xfb34,
  "hehaltonearabic",
  0x06c1,
  "heharabic",
  0x0647,
  "hehebrew",
  0x05d4,
  "hehfinalaltonearabic",
  0xfba7,
  "hehfinalalttwoarabic",
  0xfeea,
  "hehfinalarabic",
  0xfeea,
  "hehhamzaabovefinalarabic",
  0xfba5,
  "hehhamzaaboveisolatedarabic",
  0xfba4,
  "hehinitialaltonearabic",
  0xfba8,
  "hehinitialarabic",
  0xfeeb,
  "hehiragana",
  0x3078,
  "hehmedialaltonearabic",
  0xfba9,
  "hehmedialarabic",
  0xfeec,
  "heiseierasquare",
  0x337b,
  "hekatakana",
  0x30d8,
  "hekatakanahalfwidth",
  0xff8d,
  "hekutaarusquare",
  0x3336,
  "henghook",
  0x0267,
  "herutusquare",
  0x3339,
  "het",
  0x05d7,
  "hethebrew",
  0x05d7,
  "hhook",
  0x0266,
  "hhooksuperior",
  0x02b1,
  "hieuhacirclekorean",
  0x327b,
  "hieuhaparenkorean",
  0x321b,
  "hieuhcirclekorean",
  0x326d,
  "hieuhkorean",
  0x314e,
  "hieuhparenkorean",
  0x320d,
  "hihiragana",
  0x3072,
  "hikatakana",
  0x30d2,
  "hikatakanahalfwidth",
  0xff8b,
  "hiriq",
  0x05b4,
  "hiriq14",
  0x05b4,
  "hiriq21",
  0x05b4,
  "hiriq2d",
  0x05b4,
  "hiriqhebrew",
  0x05b4,
  "hiriqnarrowhebrew",
  0x05b4,
  "hiriqquarterhebrew",
  0x05b4,
  "hiriqwidehebrew",
  0x05b4,
  "hlinebelow",
  0x1e96,
  "hmonospace",
  0xff48,
  "hoarmenian",
  0x0570,
  "hohipthai",
  0x0e2b,
  "hohiragana",
  0x307b,
  "hokatakana",
  0x30db,
  "hokatakanahalfwidth",
  0xff8e,
  "holam",
  0x05b9,
  "holam19",
  0x05b9,
  "holam26",
  0x05b9,
  "holam32",
  0x05b9,
  "holamhebrew",
  0x05b9,
  "holamnarrowhebrew",
  0x05b9,
  "holamquarterhebrew",
  0x05b9,
  "holamwidehebrew",
  0x05b9,
  "honokhukthai",
  0x0e2e,
  "hookabovecomb",
  0x0309,
  "hookcmb",
  0x0309,
  "hookpalatalizedbelowcmb",
  0x0321,
  "hookretroflexbelowcmb",
  0x0322,
  "hoonsquare",
  0x3342,
  "horicoptic",
  0x03e9,
  "horizontalbar",
  0x2015,
  "horncmb",
  0x031b,
  "hotsprings",
  0x2668,
  "house",
  0x2302,
  "hparen",
  0x24a3,
  "hsuperior",
  0x02b0,
  "hturned",
  0x0265,
  "huhiragana",
  0x3075,
  "huiitosquare",
  0x3333,
  "hukatakana",
  0x30d5,
  "hukatakanahalfwidth",
  0xff8c,
  "hungarumlaut",
  0x02dd,
  "hungarumlautcmb",
  0x030b,
  "hv",
  0x0195,
  "hyphen",
  0x002d,
  "hypheninferior",
  0xf6e5,
  "hyphenmonospace",
  0xff0d,
  "hyphensmall",
  0xfe63,
  "hyphensuperior",
  0xf6e6,
  "hyphentwo",
  0x2010,
  "i",
  0x0069,
  "iacute",
  0x00ed,
  "iacyrillic",
  0x044f,
  "ibengali",
  0x0987,
  "ibopomofo",
  0x3127,
  "ibreve",
  0x012d,
  "icaron",
  0x01d0,
  "icircle",
  0x24d8,
  "icircumflex",
  0x00ee,
  "icyrillic",
  0x0456,
  "idblgrave",
  0x0209,
  "ideographearthcircle",
  0x328f,
  "ideographfirecircle",
  0x328b,
  "ideographicallianceparen",
  0x323f,
  "ideographiccallparen",
  0x323a,
  "ideographiccentrecircle",
  0x32a5,
  "ideographicclose",
  0x3006,
  "ideographiccomma",
  0x3001,
  "ideographiccommaleft",
  0xff64,
  "ideographiccongratulationparen",
  0x3237,
  "ideographiccorrectcircle",
  0x32a3,
  "ideographicearthparen",
  0x322f,
  "ideographicenterpriseparen",
  0x323d,
  "ideographicexcellentcircle",
  0x329d,
  "ideographicfestivalparen",
  0x3240,
  "ideographicfinancialcircle",
  0x3296,
  "ideographicfinancialparen",
  0x3236,
  "ideographicfireparen",
  0x322b,
  "ideographichaveparen",
  0x3232,
  "ideographichighcircle",
  0x32a4,
  "ideographiciterationmark",
  0x3005,
  "ideographiclaborcircle",
  0x3298,
  "ideographiclaborparen",
  0x3238,
  "ideographicleftcircle",
  0x32a7,
  "ideographiclowcircle",
  0x32a6,
  "ideographicmedicinecircle",
  0x32a9,
  "ideographicmetalparen",
  0x322e,
  "ideographicmoonparen",
  0x322a,
  "ideographicnameparen",
  0x3234,
  "ideographicperiod",
  0x3002,
  "ideographicprintcircle",
  0x329e,
  "ideographicreachparen",
  0x3243,
  "ideographicrepresentparen",
  0x3239,
  "ideographicresourceparen",
  0x323e,
  "ideographicrightcircle",
  0x32a8,
  "ideographicsecretcircle",
  0x3299,
  "ideographicselfparen",
  0x3242,
  "ideographicsocietyparen",
  0x3233,
  "ideographicspace",
  0x3000,
  "ideographicspecialparen",
  0x3235,
  "ideographicstockparen",
  0x3231,
  "ideographicstudyparen",
  0x323b,
  "ideographicsunparen",
  0x3230,
  "ideographicsuperviseparen",
  0x323c,
  "ideographicwaterparen",
  0x322c,
  "ideographicwoodparen",
  0x322d,
  "ideographiczero",
  0x3007,
  "ideographmetalcircle",
  0x328e,
  "ideographmooncircle",
  0x328a,
  "ideographnamecircle",
  0x3294,
  "ideographsuncircle",
  0x3290,
  "ideographwatercircle",
  0x328c,
  "ideographwoodcircle",
  0x328d,
  "ideva",
  0x0907,
  "idieresis",
  0x00ef,
  "idieresisacute",
  0x1e2f,
  "idieresiscyrillic",
  0x04e5,
  "idotbelow",
  0x1ecb,
  "iebrevecyrillic",
  0x04d7,
  "iecyrillic",
  0x0435,
  "ieungacirclekorean",
  0x3275,
  "ieungaparenkorean",
  0x3215,
  "ieungcirclekorean",
  0x3267,
  "ieungkorean",
  0x3147,
  "ieungparenkorean",
  0x3207,
  "igrave",
  0x00ec,
  "igujarati",
  0x0a87,
  "igurmukhi",
  0x0a07,
  "ihiragana",
  0x3044,
  "ihookabove",
  0x1ec9,
  "iibengali",
  0x0988,
  "iicyrillic",
  0x0438,
  "iideva",
  0x0908,
  "iigujarati",
  0x0a88,
  "iigurmukhi",
  0x0a08,
  "iimatragurmukhi",
  0x0a40,
  "iinvertedbreve",
  0x020b,
  "iishortcyrillic",
  0x0439,
  "iivowelsignbengali",
  0x09c0,
  "iivowelsigndeva",
  0x0940,
  "iivowelsigngujarati",
  0x0ac0,
  "ij",
  0x0133,
  "ikatakana",
  0x30a4,
  "ikatakanahalfwidth",
  0xff72,
  "ikorean",
  0x3163,
  "ilde",
  0x02dc,
  "iluyhebrew",
  0x05ac,
  "imacron",
  0x012b,
  "imacroncyrillic",
  0x04e3,
  "imageorapproximatelyequal",
  0x2253,
  "imatragurmukhi",
  0x0a3f,
  "imonospace",
  0xff49,
  "increment",
  0x2206,
  "infinity",
  0x221e,
  "iniarmenian",
  0x056b,
  "integral",
  0x222b,
  "integralbottom",
  0x2321,
  "integralbt",
  0x2321,
  "integralex",
  0xf8f5,
  "integraltop",
  0x2320,
  "integraltp",
  0x2320,
  "intersection",
  0x2229,
  "intisquare",
  0x3305,
  "invbullet",
  0x25d8,
  "invcircle",
  0x25d9,
  "invsmileface",
  0x263b,
  "iocyrillic",
  0x0451,
  "iogonek",
  0x012f,
  "iota",
  0x03b9,
  "iotadieresis",
  0x03ca,
  "iotadieresistonos",
  0x0390,
  "iotalatin",
  0x0269,
  "iotatonos",
  0x03af,
  "iparen",
  0x24a4,
  "irigurmukhi",
  0x0a72,
  "ismallhiragana",
  0x3043,
  "ismallkatakana",
  0x30a3,
  "ismallkatakanahalfwidth",
  0xff68,
  "issharbengali",
  0x09fa,
  "istroke",
  0x0268,
  "isuperior",
  0xf6ed,
  "iterationhiragana",
  0x309d,
  "iterationkatakana",
  0x30fd,
  "itilde",
  0x0129,
  "itildebelow",
  0x1e2d,
  "iubopomofo",
  0x3129,
  "iucyrillic",
  0x044e,
  "ivowelsignbengali",
  0x09bf,
  "ivowelsigndeva",
  0x093f,
  "ivowelsigngujarati",
  0x0abf,
  "izhitsacyrillic",
  0x0475,
  "izhitsadblgravecyrillic",
  0x0477,
  "j",
  0x006a,
  "jaarmenian",
  0x0571,
  "jabengali",
  0x099c,
  "jadeva",
  0x091c,
  "jagujarati",
  0x0a9c,
  "jagurmukhi",
  0x0a1c,
  "jbopomofo",
  0x3110,
  "jcaron",
  0x01f0,
  "jcircle",
  0x24d9,
  "jcircumflex",
  0x0135,
  "jcrossedtail",
  0x029d,
  "jdotlessstroke",
  0x025f,
  "jecyrillic",
  0x0458,
  "jeemarabic",
  0x062c,
  "jeemfinalarabic",
  0xfe9e,
  "jeeminitialarabic",
  0xfe9f,
  "jeemmedialarabic",
  0xfea0,
  "jeharabic",
  0x0698,
  "jehfinalarabic",
  0xfb8b,
  "jhabengali",
  0x099d,
  "jhadeva",
  0x091d,
  "jhagujarati",
  0x0a9d,
  "jhagurmukhi",
  0x0a1d,
  "jheharmenian",
  0x057b,
  "jis",
  0x3004,
  "jmonospace",
  0xff4a,
  "jparen",
  0x24a5,
  "jsuperior",
  0x02b2,
  "k",
  0x006b,
  "kabashkircyrillic",
  0x04a1,
  "kabengali",
  0x0995,
  "kacute",
  0x1e31,
  "kacyrillic",
  0x043a,
  "kadescendercyrillic",
  0x049b,
  "kadeva",
  0x0915,
  "kaf",
  0x05db,
  "kafarabic",
  0x0643,
  "kafdagesh",
  0xfb3b,
  "kafdageshhebrew",
  0xfb3b,
  "kaffinalarabic",
  0xfeda,
  "kafhebrew",
  0x05db,
  "kafinitialarabic",
  0xfedb,
  "kafmedialarabic",
  0xfedc,
  "kafrafehebrew",
  0xfb4d,
  "kagujarati",
  0x0a95,
  "kagurmukhi",
  0x0a15,
  "kahiragana",
  0x304b,
  "kahookcyrillic",
  0x04c4,
  "kakatakana",
  0x30ab,
  "kakatakanahalfwidth",
  0xff76,
  "kappa",
  0x03ba,
  "kappasymbolgreek",
  0x03f0,
  "kapyeounmieumkorean",
  0x3171,
  "kapyeounphieuphkorean",
  0x3184,
  "kapyeounpieupkorean",
  0x3178,
  "kapyeounssangpieupkorean",
  0x3179,
  "karoriisquare",
  0x330d,
  "kashidaautoarabic",
  0x0640,
  "kashidaautonosidebearingarabic",
  0x0640,
  "kasmallkatakana",
  0x30f5,
  "kasquare",
  0x3384,
  "kasraarabic",
  0x0650,
  "kasratanarabic",
  0x064d,
  "kastrokecyrillic",
  0x049f,
  "katahiraprolongmarkhalfwidth",
  0xff70,
  "kaverticalstrokecyrillic",
  0x049d,
  "kbopomofo",
  0x310e,
  "kcalsquare",
  0x3389,
  "kcaron",
  0x01e9,
  "kcedilla",
  0x0137,
  "kcircle",
  0x24da,
  "kcommaaccent",
  0x0137,
  "kdotbelow",
  0x1e33,
  "keharmenian",
  0x0584,
  "kehiragana",
  0x3051,
  "kekatakana",
  0x30b1,
  "kekatakanahalfwidth",
  0xff79,
  "kenarmenian",
  0x056f,
  "kesmallkatakana",
  0x30f6,
  "kgreenlandic",
  0x0138,
  "khabengali",
  0x0996,
  "khacyrillic",
  0x0445,
  "khadeva",
  0x0916,
  "khagujarati",
  0x0a96,
  "khagurmukhi",
  0x0a16,
  "khaharabic",
  0x062e,
  "khahfinalarabic",
  0xfea6,
  "khahinitialarabic",
  0xfea7,
  "khahmedialarabic",
  0xfea8,
  "kheicoptic",
  0x03e7,
  "khhadeva",
  0x0959,
  "khhagurmukhi",
  0x0a59,
  "khieukhacirclekorean",
  0x3278,
  "khieukhaparenkorean",
  0x3218,
  "khieukhcirclekorean",
  0x326a,
  "khieukhkorean",
  0x314b,
  "khieukhparenkorean",
  0x320a,
  "khokhaithai",
  0x0e02,
  "khokhonthai",
  0x0e05,
  "khokhuatthai",
  0x0e03,
  "khokhwaithai",
  0x0e04,
  "khomutthai",
  0x0e5b,
  "khook",
  0x0199,
  "khorakhangthai",
  0x0e06,
  "khzsquare",
  0x3391,
  "kihiragana",
  0x304d,
  "kikatakana",
  0x30ad,
  "kikatakanahalfwidth",
  0xff77,
  "kiroguramusquare",
  0x3315,
  "kiromeetorusquare",
  0x3316,
  "kirosquare",
  0x3314,
  "kiyeokacirclekorean",
  0x326e,
  "kiyeokaparenkorean",
  0x320e,
  "kiyeokcirclekorean",
  0x3260,
  "kiyeokkorean",
  0x3131,
  "kiyeokparenkorean",
  0x3200,
  "kiyeoksioskorean",
  0x3133,
  "kjecyrillic",
  0x045c,
  "klinebelow",
  0x1e35,
  "klsquare",
  0x3398,
  "kmcubedsquare",
  0x33a6,
  "kmonospace",
  0xff4b,
  "kmsquaredsquare",
  0x33a2,
  "kohiragana",
  0x3053,
  "kohmsquare",
  0x33c0,
  "kokaithai",
  0x0e01,
  "kokatakana",
  0x30b3,
  "kokatakanahalfwidth",
  0xff7a,
  "kooposquare",
  0x331e,
  "koppacyrillic",
  0x0481,
  "koreanstandardsymbol",
  0x327f,
  "koroniscmb",
  0x0343,
  "kparen",
  0x24a6,
  "kpasquare",
  0x33aa,
  "ksicyrillic",
  0x046f,
  "ktsquare",
  0x33cf,
  "kturned",
  0x029e,
  "kuhiragana",
  0x304f,
  "kukatakana",
  0x30af,
  "kukatakanahalfwidth",
  0xff78,
  "kvsquare",
  0x33b8,
  "kwsquare",
  0x33be,
  "l",
  0x006c,
  "labengali",
  0x09b2,
  "lacute",
  0x013a,
  "ladeva",
  0x0932,
  "lagujarati",
  0x0ab2,
  "lagurmukhi",
  0x0a32,
  "lakkhangyaothai",
  0x0e45,
  "lamaleffinalarabic",
  0xfefc,
  "lamalefhamzaabovefinalarabic",
  0xfef8,
  "lamalefhamzaaboveisolatedarabic",
  0xfef7,
  "lamalefhamzabelowfinalarabic",
  0xfefa,
  "lamalefhamzabelowisolatedarabic",
  0xfef9,
  "lamalefisolatedarabic",
  0xfefb,
  "lamalefmaddaabovefinalarabic",
  0xfef6,
  "lamalefmaddaaboveisolatedarabic",
  0xfef5,
  "lamarabic",
  0x0644,
  "lambda",
  0x03bb,
  "lambdastroke",
  0x019b,
  "lamed",
  0x05dc,
  "lameddagesh",
  0xfb3c,
  "lameddageshhebrew",
  0xfb3c,
  "lamedhebrew",
  0x05dc,
  "lamfinalarabic",
  0xfede,
  "lamhahinitialarabic",
  0xfcca,
  "laminitialarabic",
  0xfedf,
  "lamjeeminitialarabic",
  0xfcc9,
  "lamkhahinitialarabic",
  0xfccb,
  "lamlamhehisolatedarabic",
  0xfdf2,
  "lammedialarabic",
  0xfee0,
  "lammeemhahinitialarabic",
  0xfd88,
  "lammeeminitialarabic",
  0xfccc,
  "largecircle",
  0x25ef,
  "lbar",
  0x019a,
  "lbelt",
  0x026c,
  "lbopomofo",
  0x310c,
  "lcaron",
  0x013e,
  "lcedilla",
  0x013c,
  "lcircle",
  0x24db,
  "lcircumflexbelow",
  0x1e3d,
  "lcommaaccent",
  0x013c,
  "ldot",
  0x0140,
  "ldotaccent",
  0x0140,
  "ldotbelow",
  0x1e37,
  "ldotbelowmacron",
  0x1e39,
  "leftangleabovecmb",
  0x031a,
  "lefttackbelowcmb",
  0x0318,
  "less",
  0x003c,
  "lessequal",
  0x2264,
  "lessequalorgreater",
  0x22da,
  "lessmonospace",
  0xff1c,
  "lessorequivalent",
  0x2272,
  "lessorgreater",
  0x2276,
  "lessoverequal",
  0x2266,
  "lesssmall",
  0xfe64,
  "lezh",
  0x026e,
  "lfblock",
  0x258c,
  "lhookretroflex",
  0x026d,
  "lira",
  0x20a4,
  "liwnarmenian",
  0x056c,
  "lj",
  0x01c9,
  "ljecyrillic",
  0x0459,
  "ll",
  0xf6c0,
  "lladeva",
  0x0933,
  "llagujarati",
  0x0ab3,
  "llinebelow",
  0x1e3b,
  "llladeva",
  0x0934,
  "llvocalicbengali",
  0x09e1,
  "llvocalicdeva",
  0x0961,
  "llvocalicvowelsignbengali",
  0x09e3,
  "llvocalicvowelsigndeva",
  0x0963,
  "lmiddletilde",
  0x026b,
  "lmonospace",
  0xff4c,
  "lmsquare",
  0x33d0,
  "lochulathai",
  0x0e2c,
  "logicaland",
  0x2227,
  "logicalnot",
  0x00ac,
  "logicalnotreversed",
  0x2310,
  "logicalor",
  0x2228,
  "lolingthai",
  0x0e25,
  "longs",
  0x017f,
  "lowlinecenterline",
  0xfe4e,
  "lowlinecmb",
  0x0332,
  "lowlinedashed",
  0xfe4d,
  "lozenge",
  0x25ca,
  "lparen",
  0x24a7,
  "lslash",
  0x0142,
  "lsquare",
  0x2113,
  "lsuperior",
  0xf6ee,
  "ltshade",
  0x2591,
  "luthai",
  0x0e26,
  "lvocalicbengali",
  0x098c,
  "lvocalicdeva",
  0x090c,
  "lvocalicvowelsignbengali",
  0x09e2,
  "lvocalicvowelsigndeva",
  0x0962,
  "lxsquare",
  0x33d3,
  "m",
  0x006d,
  "mabengali",
  0x09ae,
  "macron",
  0x00af,
  "macronbelowcmb",
  0x0331,
  "macroncmb",
  0x0304,
  "macronlowmod",
  0x02cd,
  "macronmonospace",
  0xffe3,
  "macute",
  0x1e3f,
  "madeva",
  0x092e,
  "magujarati",
  0x0aae,
  "magurmukhi",
  0x0a2e,
  "mahapakhhebrew",
  0x05a4,
  "mahapakhlefthebrew",
  0x05a4,
  "mahiragana",
  0x307e,
  "maichattawalowleftthai",
  0xf895,
  "maichattawalowrightthai",
  0xf894,
  "maichattawathai",
  0x0e4b,
  "maichattawaupperleftthai",
  0xf893,
  "maieklowleftthai",
  0xf88c,
  "maieklowrightthai",
  0xf88b,
  "maiekthai",
  0x0e48,
  "maiekupperleftthai",
  0xf88a,
  "maihanakatleftthai",
  0xf884,
  "maihanakatthai",
  0x0e31,
  "maitaikhuleftthai",
  0xf889,
  "maitaikhuthai",
  0x0e47,
  "maitholowleftthai",
  0xf88f,
  "maitholowrightthai",
  0xf88e,
  "maithothai",
  0x0e49,
  "maithoupperleftthai",
  0xf88d,
  "maitrilowleftthai",
  0xf892,
  "maitrilowrightthai",
  0xf891,
  "maitrithai",
  0x0e4a,
  "maitriupperleftthai",
  0xf890,
  "maiyamokthai",
  0x0e46,
  "makatakana",
  0x30de,
  "makatakanahalfwidth",
  0xff8f,
  "male",
  0x2642,
  "mansyonsquare",
  0x3347,
  "maqafhebrew",
  0x05be,
  "mars",
  0x2642,
  "masoracirclehebrew",
  0x05af,
  "masquare",
  0x3383,
  "mbopomofo",
  0x3107,
  "mbsquare",
  0x33d4,
  "mcircle",
  0x24dc,
  "mcubedsquare",
  0x33a5,
  "mdotaccent",
  0x1e41,
  "mdotbelow",
  0x1e43,
  "meemarabic",
  0x0645,
  "meemfinalarabic",
  0xfee2,
  "meeminitialarabic",
  0xfee3,
  "meemmedialarabic",
  0xfee4,
  "meemmeeminitialarabic",
  0xfcd1,
  "meemmeemisolatedarabic",
  0xfc48,
  "meetorusquare",
  0x334d,
  "mehiragana",
  0x3081,
  "meizierasquare",
  0x337e,
  "mekatakana",
  0x30e1,
  "mekatakanahalfwidth",
  0xff92,
  "mem",
  0x05de,
  "memdagesh",
  0xfb3e,
  "memdageshhebrew",
  0xfb3e,
  "memhebrew",
  0x05de,
  "menarmenian",
  0x0574,
  "merkhahebrew",
  0x05a5,
  "merkhakefulahebrew",
  0x05a6,
  "merkhakefulalefthebrew",
  0x05a6,
  "merkhalefthebrew",
  0x05a5,
  "mhook",
  0x0271,
  "mhzsquare",
  0x3392,
  "middledotkatakanahalfwidth",
  0xff65,
  "middot",
  0x00b7,
  "mieumacirclekorean",
  0x3272,
  "mieumaparenkorean",
  0x3212,
  "mieumcirclekorean",
  0x3264,
  "mieumkorean",
  0x3141,
  "mieumpansioskorean",
  0x3170,
  "mieumparenkorean",
  0x3204,
  "mieumpieupkorean",
  0x316e,
  "mieumsioskorean",
  0x316f,
  "mihiragana",
  0x307f,
  "mikatakana",
  0x30df,
  "mikatakanahalfwidth",
  0xff90,
  "minus",
  0x2212,
  "minusbelowcmb",
  0x0320,
  "minuscircle",
  0x2296,
  "minusmod",
  0x02d7,
  "minusplus",
  0x2213,
  "minute",
  0x2032,
  "miribaarusquare",
  0x334a,
  "mirisquare",
  0x3349,
  "mlonglegturned",
  0x0270,
  "mlsquare",
  0x3396,
  "mmcubedsquare",
  0x33a3,
  "mmonospace",
  0xff4d,
  "mmsquaredsquare",
  0x339f,
  "mohiragana",
  0x3082,
  "mohmsquare",
  0x33c1,
  "mokatakana",
  0x30e2,
  "mokatakanahalfwidth",
  0xff93,
  "molsquare",
  0x33d6,
  "momathai",
  0x0e21,
  "moverssquare",
  0x33a7,
  "moverssquaredsquare",
  0x33a8,
  "mparen",
  0x24a8,
  "mpasquare",
  0x33ab,
  "mssquare",
  0x33b3,
  "msuperior",
  0xf6ef,
  "mturned",
  0x026f,
  "mu",
  0x00b5,
  "mu1",
  0x00b5,
  "muasquare",
  0x3382,
  "muchgreater",
  0x226b,
  "muchless",
  0x226a,
  "mufsquare",
  0x338c,
  "mugreek",
  0x03bc,
  "mugsquare",
  0x338d,
  "muhiragana",
  0x3080,
  "mukatakana",
  0x30e0,
  "mukatakanahalfwidth",
  0xff91,
  "mulsquare",
  0x3395,
  "multiply",
  0x00d7,
  "mumsquare",
  0x339b,
  "munahhebrew",
  0x05a3,
  "munahlefthebrew",
  0x05a3,
  "musicalnote",
  0x266a,
  "musicalnotedbl",
  0x266b,
  "musicflatsign",
  0x266d,
  "musicsharpsign",
  0x266f,
  "mussquare",
  0x33b2,
  "muvsquare",
  0x33b6,
  "muwsquare",
  0x33bc,
  "mvmegasquare",
  0x33b9,
  "mvsquare",
  0x33b7,
  "mwmegasquare",
  0x33bf,
  "mwsquare",
  0x33bd,
  "n",
  0x006e,
  "nabengali",
  0x09a8,
  "nabla",
  0x2207,
  "nacute",
  0x0144,
  "nadeva",
  0x0928,
  "nagujarati",
  0x0aa8,
  "nagurmukhi",
  0x0a28,
  "nahiragana",
  0x306a,
  "nakatakana",
  0x30ca,
  "nakatakanahalfwidth",
  0xff85,
  "napostrophe",
  0x0149,
  "nasquare",
  0x3381,
  "nbopomofo",
  0x310b,
  "nbspace",
  0x00a0,
  "ncaron",
  0x0148,
  "ncedilla",
  0x0146,
  "ncircle",
  0x24dd,
  "ncircumflexbelow",
  0x1e4b,
  "ncommaaccent",
  0x0146,
  "ndotaccent",
  0x1e45,
  "ndotbelow",
  0x1e47,
  "nehiragana",
  0x306d,
  "nekatakana",
  0x30cd,
  "nekatakanahalfwidth",
  0xff88,
  "newsheqelsign",
  0x20aa,
  "nfsquare",
  0x338b,
  "ngabengali",
  0x0999,
  "ngadeva",
  0x0919,
  "ngagujarati",
  0x0a99,
  "ngagurmukhi",
  0x0a19,
  "ngonguthai",
  0x0e07,
  "nhiragana",
  0x3093,
  "nhookleft",
  0x0272,
  "nhookretroflex",
  0x0273,
  "nieunacirclekorean",
  0x326f,
  "nieunaparenkorean",
  0x320f,
  "nieuncieuckorean",
  0x3135,
  "nieuncirclekorean",
  0x3261,
  "nieunhieuhkorean",
  0x3136,
  "nieunkorean",
  0x3134,
  "nieunpansioskorean",
  0x3168,
  "nieunparenkorean",
  0x3201,
  "nieunsioskorean",
  0x3167,
  "nieuntikeutkorean",
  0x3166,
  "nihiragana",
  0x306b,
  "nikatakana",
  0x30cb,
  "nikatakanahalfwidth",
  0xff86,
  "nikhahitleftthai",
  0xf899,
  "nikhahitthai",
  0x0e4d,
  "nine",
  0x0039,
  "ninearabic",
  0x0669,
  "ninebengali",
  0x09ef,
  "ninecircle",
  0x2468,
  "ninecircleinversesansserif",
  0x2792,
  "ninedeva",
  0x096f,
  "ninegujarati",
  0x0aef,
  "ninegurmukhi",
  0x0a6f,
  "ninehackarabic",
  0x0669,
  "ninehangzhou",
  0x3029,
  "nineideographicparen",
  0x3228,
  "nineinferior",
  0x2089,
  "ninemonospace",
  0xff19,
  "nineoldstyle",
  0xf739,
  "nineparen",
  0x247c,
  "nineperiod",
  0x2490,
  "ninepersian",
  0x06f9,
  "nineroman",
  0x2178,
  "ninesuperior",
  0x2079,
  "nineteencircle",
  0x2472,
  "nineteenparen",
  0x2486,
  "nineteenperiod",
  0x249a,
  "ninethai",
  0x0e59,
  "nj",
  0x01cc,
  "njecyrillic",
  0x045a,
  "nkatakana",
  0x30f3,
  "nkatakanahalfwidth",
  0xff9d,
  "nlegrightlong",
  0x019e,
  "nlinebelow",
  0x1e49,
  "nmonospace",
  0xff4e,
  "nmsquare",
  0x339a,
  "nnabengali",
  0x09a3,
  "nnadeva",
  0x0923,
  "nnagujarati",
  0x0aa3,
  "nnagurmukhi",
  0x0a23,
  "nnnadeva",
  0x0929,
  "nohiragana",
  0x306e,
  "nokatakana",
  0x30ce,
  "nokatakanahalfwidth",
  0xff89,
  "nonbreakingspace",
  0x00a0,
  "nonenthai",
  0x0e13,
  "nonuthai",
  0x0e19,
  "noonarabic",
  0x0646,
  "noonfinalarabic",
  0xfee6,
  "noonghunnaarabic",
  0x06ba,
  "noonghunnafinalarabic",
  0xfb9f,
  "nooninitialarabic",
  0xfee7,
  "noonjeeminitialarabic",
  0xfcd2,
  "noonjeemisolatedarabic",
  0xfc4b,
  "noonmedialarabic",
  0xfee8,
  "noonmeeminitialarabic",
  0xfcd5,
  "noonmeemisolatedarabic",
  0xfc4e,
  "noonnoonfinalarabic",
  0xfc8d,
  "notcontains",
  0x220c,
  "notelement",
  0x2209,
  "notelementof",
  0x2209,
  "notequal",
  0x2260,
  "notgreater",
  0x226f,
  "notgreaternorequal",
  0x2271,
  "notgreaternorless",
  0x2279,
  "notidentical",
  0x2262,
  "notless",
  0x226e,
  "notlessnorequal",
  0x2270,
  "notparallel",
  0x2226,
  "notprecedes",
  0x2280,
  "notsubset",
  0x2284,
  "notsucceeds",
  0x2281,
  "notsuperset",
  0x2285,
  "nowarmenian",
  0x0576,
  "nparen",
  0x24a9,
  "nssquare",
  0x33b1,
  "nsuperior",
  0x207f,
  "ntilde",
  0x00f1,
  "nu",
  0x03bd,
  "nuhiragana",
  0x306c,
  "nukatakana",
  0x30cc,
  "nukatakanahalfwidth",
  0xff87,
  "nuktabengali",
  0x09bc,
  "nuktadeva",
  0x093c,
  "nuktagujarati",
  0x0abc,
  "nuktagurmukhi",
  0x0a3c,
  "numbersign",
  0x0023,
  "numbersignmonospace",
  0xff03,
  "numbersignsmall",
  0xfe5f,
  "numeralsigngreek",
  0x0374,
  "numeralsignlowergreek",
  0x0375,
  "numero",
  0x2116,
  "nun",
  0x05e0,
  "nundagesh",
  0xfb40,
  "nundageshhebrew",
  0xfb40,
  "nunhebrew",
  0x05e0,
  "nvsquare",
  0x33b5,
  "nwsquare",
  0x33bb,
  "nyabengali",
  0x099e,
  "nyadeva",
  0x091e,
  "nyagujarati",
  0x0a9e,
  "nyagurmukhi",
  0x0a1e,
  "o",
  0x006f,
  "oacute",
  0x00f3,
  "oangthai",
  0x0e2d,
  "obarred",
  0x0275,
  "obarredcyrillic",
  0x04e9,
  "obarreddieresiscyrillic",
  0x04eb,
  "obengali",
  0x0993,
  "obopomofo",
  0x311b,
  "obreve",
  0x014f,
  "ocandradeva",
  0x0911,
  "ocandragujarati",
  0x0a91,
  "ocandravowelsigndeva",
  0x0949,
  "ocandravowelsigngujarati",
  0x0ac9,
  "ocaron",
  0x01d2,
  "ocircle",
  0x24de,
  "ocircumflex",
  0x00f4,
  "ocircumflexacute",
  0x1ed1,
  "ocircumflexdotbelow",
  0x1ed9,
  "ocircumflexgrave",
  0x1ed3,
  "ocircumflexhookabove",
  0x1ed5,
  "ocircumflextilde",
  0x1ed7,
  "ocyrillic",
  0x043e,
  "odblacute",
  0x0151,
  "odblgrave",
  0x020d,
  "odeva",
  0x0913,
  "odieresis",
  0x00f6,
  "odieresiscyrillic",
  0x04e7,
  "odotbelow",
  0x1ecd,
  "oe",
  0x0153,
  "oekorean",
  0x315a,
  "ogonek",
  0x02db,
  "ogonekcmb",
  0x0328,
  "ograve",
  0x00f2,
  "ogujarati",
  0x0a93,
  "oharmenian",
  0x0585,
  "ohiragana",
  0x304a,
  "ohookabove",
  0x1ecf,
  "ohorn",
  0x01a1,
  "ohornacute",
  0x1edb,
  "ohorndotbelow",
  0x1ee3,
  "ohorngrave",
  0x1edd,
  "ohornhookabove",
  0x1edf,
  "ohorntilde",
  0x1ee1,
  "ohungarumlaut",
  0x0151,
  "oi",
  0x01a3,
  "oinvertedbreve",
  0x020f,
  "okatakana",
  0x30aa,
  "okatakanahalfwidth",
  0xff75,
  "okorean",
  0x3157,
  "olehebrew",
  0x05ab,
  "omacron",
  0x014d,
  "omacronacute",
  0x1e53,
  "omacrongrave",
  0x1e51,
  "omdeva",
  0x0950,
  "omega",
  0x03c9,
  "omega1",
  0x03d6,
  "omegacyrillic",
  0x0461,
  "omegalatinclosed",
  0x0277,
  "omegaroundcyrillic",
  0x047b,
  "omegatitlocyrillic",
  0x047d,
  "omegatonos",
  0x03ce,
  "omgujarati",
  0x0ad0,
  "omicron",
  0x03bf,
  "omicrontonos",
  0x03cc,
  "omonospace",
  0xff4f,
  "one",
  0x0031,
  "onearabic",
  0x0661,
  "onebengali",
  0x09e7,
  "onecircle",
  0x2460,
  "onecircleinversesansserif",
  0x278a,
  "onedeva",
  0x0967,
  "onedotenleader",
  0x2024,
  "oneeighth",
  0x215b,
  "onefitted",
  0xf6dc,
  "onegujarati",
  0x0ae7,
  "onegurmukhi",
  0x0a67,
  "onehackarabic",
  0x0661,
  "onehalf",
  0x00bd,
  "onehangzhou",
  0x3021,
  "oneideographicparen",
  0x3220,
  "oneinferior",
  0x2081,
  "onemonospace",
  0xff11,
  "onenumeratorbengali",
  0x09f4,
  "oneoldstyle",
  0xf731,
  "oneparen",
  0x2474,
  "oneperiod",
  0x2488,
  "onepersian",
  0x06f1,
  "onequarter",
  0x00bc,
  "oneroman",
  0x2170,
  "onesuperior",
  0x00b9,
  "onethai",
  0x0e51,
  "onethird",
  0x2153,
  "oogonek",
  0x01eb,
  "oogonekmacron",
  0x01ed,
  "oogurmukhi",
  0x0a13,
  "oomatragurmukhi",
  0x0a4b,
  "oopen",
  0x0254,
  "oparen",
  0x24aa,
  "openbullet",
  0x25e6,
  "option",
  0x2325,
  "ordfeminine",
  0x00aa,
  "ordmasculine",
  0x00ba,
  "orthogonal",
  0x221f,
  "oshortdeva",
  0x0912,
  "oshortvowelsigndeva",
  0x094a,
  "oslash",
  0x00f8,
  "oslashacute",
  0x01ff,
  "osmallhiragana",
  0x3049,
  "osmallkatakana",
  0x30a9,
  "osmallkatakanahalfwidth",
  0xff6b,
  "ostrokeacute",
  0x01ff,
  "osuperior",
  0xf6f0,
  "otcyrillic",
  0x047f,
  "otilde",
  0x00f5,
  "otildeacute",
  0x1e4d,
  "otildedieresis",
  0x1e4f,
  "oubopomofo",
  0x3121,
  "overline",
  0x203e,
  "overlinecenterline",
  0xfe4a,
  "overlinecmb",
  0x0305,
  "overlinedashed",
  0xfe49,
  "overlinedblwavy",
  0xfe4c,
  "overlinewavy",
  0xfe4b,
  "overscore",
  0x00af,
  "ovowelsignbengali",
  0x09cb,
  "ovowelsigndeva",
  0x094b,
  "ovowelsigngujarati",
  0x0acb,
  "p",
  0x0070,
  "paampssquare",
  0x3380,
  "paasentosquare",
  0x332b,
  "pabengali",
  0x09aa,
  "pacute",
  0x1e55,
  "padeva",
  0x092a,
  "pagedown",
  0x21df,
  "pageup",
  0x21de,
  "pagujarati",
  0x0aaa,
  "pagurmukhi",
  0x0a2a,
  "pahiragana",
  0x3071,
  "paiyannoithai",
  0x0e2f,
  "pakatakana",
  0x30d1,
  "palatalizationcyrilliccmb",
  0x0484,
  "palochkacyrillic",
  0x04c0,
  "pansioskorean",
  0x317f,
  "paragraph",
  0x00b6,
  "parallel",
  0x2225,
  "parenleft",
  0x0028,
  "parenleftaltonearabic",
  0xfd3e,
  "parenleftbt",
  0xf8ed,
  "parenleftex",
  0xf8ec,
  "parenleftinferior",
  0x208d,
  "parenleftmonospace",
  0xff08,
  "parenleftsmall",
  0xfe59,
  "parenleftsuperior",
  0x207d,
  "parenlefttp",
  0xf8eb,
  "parenleftvertical",
  0xfe35,
  "parenright",
  0x0029,
  "parenrightaltonearabic",
  0xfd3f,
  "parenrightbt",
  0xf8f8,
  "parenrightex",
  0xf8f7,
  "parenrightinferior",
  0x208e,
  "parenrightmonospace",
  0xff09,
  "parenrightsmall",
  0xfe5a,
  "parenrightsuperior",
  0x207e,
  "parenrighttp",
  0xf8f6,
  "parenrightvertical",
  0xfe36,
  "partialdiff",
  0x2202,
  "paseqhebrew",
  0x05c0,
  "pashtahebrew",
  0x0599,
  "pasquare",
  0x33a9,
  "patah",
  0x05b7,
  "patah11",
  0x05b7,
  "patah1d",
  0x05b7,
  "patah2a",
  0x05b7,
  "patahhebrew",
  0x05b7,
  "patahnarrowhebrew",
  0x05b7,
  "patahquarterhebrew",
  0x05b7,
  "patahwidehebrew",
  0x05b7,
  "pazerhebrew",
  0x05a1,
  "pbopomofo",
  0x3106,
  "pcircle",
  0x24df,
  "pdotaccent",
  0x1e57,
  "pe",
  0x05e4,
  "pecyrillic",
  0x043f,
  "pedagesh",
  0xfb44,
  "pedageshhebrew",
  0xfb44,
  "peezisquare",
  0x333b,
  "pefinaldageshhebrew",
  0xfb43,
  "peharabic",
  0x067e,
  "peharmenian",
  0x057a,
  "pehebrew",
  0x05e4,
  "pehfinalarabic",
  0xfb57,
  "pehinitialarabic",
  0xfb58,
  "pehiragana",
  0x307a,
  "pehmedialarabic",
  0xfb59,
  "pekatakana",
  0x30da,
  "pemiddlehookcyrillic",
  0x04a7,
  "perafehebrew",
  0xfb4e,
  "percent",
  0x0025,
  "percentarabic",
  0x066a,
  "percentmonospace",
  0xff05,
  "percentsmall",
  0xfe6a,
  "period",
  0x002e,
  "periodarmenian",
  0x0589,
  "periodcentered",
  0x00b7,
  "periodhalfwidth",
  0xff61,
  "periodinferior",
  0xf6e7,
  "periodmonospace",
  0xff0e,
  "periodsmall",
  0xfe52,
  "periodsuperior",
  0xf6e8,
  "perispomenigreekcmb",
  0x0342,
  "perpendicular",
  0x22a5,
  "perthousand",
  0x2030,
  "peseta",
  0x20a7,
  "pfsquare",
  0x338a,
  "phabengali",
  0x09ab,
  "phadeva",
  0x092b,
  "phagujarati",
  0x0aab,
  "phagurmukhi",
  0x0a2b,
  "phi",
  0x03c6,
  "phi1",
  0x03d5,
  "phieuphacirclekorean",
  0x327a,
  "phieuphaparenkorean",
  0x321a,
  "phieuphcirclekorean",
  0x326c,
  "phieuphkorean",
  0x314d,
  "phieuphparenkorean",
  0x320c,
  "philatin",
  0x0278,
  "phinthuthai",
  0x0e3a,
  "phisymbolgreek",
  0x03d5,
  "phook",
  0x01a5,
  "phophanthai",
  0x0e1e,
  "phophungthai",
  0x0e1c,
  "phosamphaothai",
  0x0e20,
  "pi",
  0x03c0,
  "pieupacirclekorean",
  0x3273,
  "pieupaparenkorean",
  0x3213,
  "pieupcieuckorean",
  0x3176,
  "pieupcirclekorean",
  0x3265,
  "pieupkiyeokkorean",
  0x3172,
  "pieupkorean",
  0x3142,
  "pieupparenkorean",
  0x3205,
  "pieupsioskiyeokkorean",
  0x3174,
  "pieupsioskorean",
  0x3144,
  "pieupsiostikeutkorean",
  0x3175,
  "pieupthieuthkorean",
  0x3177,
  "pieuptikeutkorean",
  0x3173,
  "pihiragana",
  0x3074,
  "pikatakana",
  0x30d4,
  "pisymbolgreek",
  0x03d6,
  "piwrarmenian",
  0x0583,
  "plus",
  0x002b,
  "plusbelowcmb",
  0x031f,
  "pluscircle",
  0x2295,
  "plusminus",
  0x00b1,
  "plusmod",
  0x02d6,
  "plusmonospace",
  0xff0b,
  "plussmall",
  0xfe62,
  "plussuperior",
  0x207a,
  "pmonospace",
  0xff50,
  "pmsquare",
  0x33d8,
  "pohiragana",
  0x307d,
  "pointingindexdownwhite",
  0x261f,
  "pointingindexleftwhite",
  0x261c,
  "pointingindexrightwhite",
  0x261e,
  "pointingindexupwhite",
  0x261d,
  "pokatakana",
  0x30dd,
  "poplathai",
  0x0e1b,
  "postalmark",
  0x3012,
  "postalmarkface",
  0x3020,
  "pparen",
  0x24ab,
  "precedes",
  0x227a,
  "prescription",
  0x211e,
  "primemod",
  0x02b9,
  "primereversed",
  0x2035,
  "product",
  0x220f,
  "projective",
  0x2305,
  "prolongedkana",
  0x30fc,
  "propellor",
  0x2318,
  "propersubset",
  0x2282,
  "propersuperset",
  0x2283,
  "proportion",
  0x2237,
  "proportional",
  0x221d,
  "psi",
  0x03c8,
  "psicyrillic",
  0x0471,
  "psilipneumatacyrilliccmb",
  0x0486,
  "pssquare",
  0x33b0,
  "puhiragana",
  0x3077,
  "pukatakana",
  0x30d7,
  "pvsquare",
  0x33b4,
  "pwsquare",
  0x33ba,
  "q",
  0x0071,
  "qadeva",
  0x0958,
  "qadmahebrew",
  0x05a8,
  "qafarabic",
  0x0642,
  "qaffinalarabic",
  0xfed6,
  "qafinitialarabic",
  0xfed7,
  "qafmedialarabic",
  0xfed8,
  "qamats",
  0x05b8,
  "qamats10",
  0x05b8,
  "qamats1a",
  0x05b8,
  "qamats1c",
  0x05b8,
  "qamats27",
  0x05b8,
  "qamats29",
  0x05b8,
  "qamats33",
  0x05b8,
  "qamatsde",
  0x05b8,
  "qamatshebrew",
  0x05b8,
  "qamatsnarrowhebrew",
  0x05b8,
  "qamatsqatanhebrew",
  0x05b8,
  "qamatsqatannarrowhebrew",
  0x05b8,
  "qamatsqatanquarterhebrew",
  0x05b8,
  "qamatsqatanwidehebrew",
  0x05b8,
  "qamatsquarterhebrew",
  0x05b8,
  "qamatswidehebrew",
  0x05b8,
  "qarneyparahebrew",
  0x059f,
  "qbopomofo",
  0x3111,
  "qcircle",
  0x24e0,
  "qhook",
  0x02a0,
  "qmonospace",
  0xff51,
  "qof",
  0x05e7,
  "qofdagesh",
  0xfb47,
  "qofdageshhebrew",
  0xfb47,
  "qofhebrew",
  0x05e7,
  "qparen",
  0x24ac,
  "quarternote",
  0x2669,
  "qubuts",
  0x05bb,
  "qubuts18",
  0x05bb,
  "qubuts25",
  0x05bb,
  "qubuts31",
  0x05bb,
  "qubutshebrew",
  0x05bb,
  "qubutsnarrowhebrew",
  0x05bb,
  "qubutsquarterhebrew",
  0x05bb,
  "qubutswidehebrew",
  0x05bb,
  "question",
  0x003f,
  "questionarabic",
  0x061f,
  "questionarmenian",
  0x055e,
  "questiondown",
  0x00bf,
  "questiondownsmall",
  0xf7bf,
  "questiongreek",
  0x037e,
  "questionmonospace",
  0xff1f,
  "questionsmall",
  0xf73f,
  "quotedbl",
  0x0022,
  "quotedblbase",
  0x201e,
  "quotedblleft",
  0x201c,
  "quotedblmonospace",
  0xff02,
  "quotedblprime",
  0x301e,
  "quotedblprimereversed",
  0x301d,
  "quotedblright",
  0x201d,
  "quoteleft",
  0x2018,
  "quoteleftreversed",
  0x201b,
  "quotereversed",
  0x201b,
  "quoteright",
  0x2019,
  "quoterightn",
  0x0149,
  "quotesinglbase",
  0x201a,
  "quotesingle",
  0x0027,
  "quotesinglemonospace",
  0xff07,
  "r",
  0x0072,
  "raarmenian",
  0x057c,
  "rabengali",
  0x09b0,
  "racute",
  0x0155,
  "radeva",
  0x0930,
  "radical",
  0x221a,
  "radicalex",
  0xf8e5,
  "radoverssquare",
  0x33ae,
  "radoverssquaredsquare",
  0x33af,
  "radsquare",
  0x33ad,
  "rafe",
  0x05bf,
  "rafehebrew",
  0x05bf,
  "ragujarati",
  0x0ab0,
  "ragurmukhi",
  0x0a30,
  "rahiragana",
  0x3089,
  "rakatakana",
  0x30e9,
  "rakatakanahalfwidth",
  0xff97,
  "ralowerdiagonalbengali",
  0x09f1,
  "ramiddlediagonalbengali",
  0x09f0,
  "ramshorn",
  0x0264,
  "ratio",
  0x2236,
  "rbopomofo",
  0x3116,
  "rcaron",
  0x0159,
  "rcedilla",
  0x0157,
  "rcircle",
  0x24e1,
  "rcommaaccent",
  0x0157,
  "rdblgrave",
  0x0211,
  "rdotaccent",
  0x1e59,
  "rdotbelow",
  0x1e5b,
  "rdotbelowmacron",
  0x1e5d,
  "referencemark",
  0x203b,
  "reflexsubset",
  0x2286,
  "reflexsuperset",
  0x2287,
  "registered",
  0x00ae,
  "registersans",
  0xf8e8,
  "registerserif",
  0xf6da,
  "reharabic",
  0x0631,
  "reharmenian",
  0x0580,
  "rehfinalarabic",
  0xfeae,
  "rehiragana",
  0x308c,
  "rekatakana",
  0x30ec,
  "rekatakanahalfwidth",
  0xff9a,
  "resh",
  0x05e8,
  "reshdageshhebrew",
  0xfb48,
  "reshhebrew",
  0x05e8,
  "reversedtilde",
  0x223d,
  "reviahebrew",
  0x0597,
  "reviamugrashhebrew",
  0x0597,
  "revlogicalnot",
  0x2310,
  "rfishhook",
  0x027e,
  "rfishhookreversed",
  0x027f,
  "rhabengali",
  0x09dd,
  "rhadeva",
  0x095d,
  "rho",
  0x03c1,
  "rhook",
  0x027d,
  "rhookturned",
  0x027b,
  "rhookturnedsuperior",
  0x02b5,
  "rhosymbolgreek",
  0x03f1,
  "rhotichookmod",
  0x02de,
  "rieulacirclekorean",
  0x3271,
  "rieulaparenkorean",
  0x3211,
  "rieulcirclekorean",
  0x3263,
  "rieulhieuhkorean",
  0x3140,
  "rieulkiyeokkorean",
  0x313a,
  "rieulkiyeoksioskorean",
  0x3169,
  "rieulkorean",
  0x3139,
  "rieulmieumkorean",
  0x313b,
  "rieulpansioskorean",
  0x316c,
  "rieulparenkorean",
  0x3203,
  "rieulphieuphkorean",
  0x313f,
  "rieulpieupkorean",
  0x313c,
  "rieulpieupsioskorean",
  0x316b,
  "rieulsioskorean",
  0x313d,
  "rieulthieuthkorean",
  0x313e,
  "rieultikeutkorean",
  0x316a,
  "rieulyeorinhieuhkorean",
  0x316d,
  "rightangle",
  0x221f,
  "righttackbelowcmb",
  0x0319,
  "righttriangle",
  0x22bf,
  "rihiragana",
  0x308a,
  "rikatakana",
  0x30ea,
  "rikatakanahalfwidth",
  0xff98,
  "ring",
  0x02da,
  "ringbelowcmb",
  0x0325,
  "ringcmb",
  0x030a,
  "ringhalfleft",
  0x02bf,
  "ringhalfleftarmenian",
  0x0559,
  "ringhalfleftbelowcmb",
  0x031c,
  "ringhalfleftcentered",
  0x02d3,
  "ringhalfright",
  0x02be,
  "ringhalfrightbelowcmb",
  0x0339,
  "ringhalfrightcentered",
  0x02d2,
  "rinvertedbreve",
  0x0213,
  "rittorusquare",
  0x3351,
  "rlinebelow",
  0x1e5f,
  "rlongleg",
  0x027c,
  "rlonglegturned",
  0x027a,
  "rmonospace",
  0xff52,
  "rohiragana",
  0x308d,
  "rokatakana",
  0x30ed,
  "rokatakanahalfwidth",
  0xff9b,
  "roruathai",
  0x0e23,
  "rparen",
  0x24ad,
  "rrabengali",
  0x09dc,
  "rradeva",
  0x0931,
  "rragurmukhi",
  0x0a5c,
  "rreharabic",
  0x0691,
  "rrehfinalarabic",
  0xfb8d,
  "rrvocalicbengali",
  0x09e0,
  "rrvocalicdeva",
  0x0960,
  "rrvocalicgujarati",
  0x0ae0,
  "rrvocalicvowelsignbengali",
  0x09c4,
  "rrvocalicvowelsigndeva",
  0x0944,
  "rrvocalicvowelsigngujarati",
  0x0ac4,
  "rsuperior",
  0xf6f1,
  "rtblock",
  0x2590,
  "rturned",
  0x0279,
  "rturnedsuperior",
  0x02b4,
  "ruhiragana",
  0x308b,
  "rukatakana",
  0x30eb,
  "rukatakanahalfwidth",
  0xff99,
  "rupeemarkbengali",
  0x09f2,
  "rupeesignbengali",
  0x09f3,
  "rupiah",
  0xf6dd,
  "ruthai",
  0x0e24,
  "rvocalicbengali",
  0x098b,
  "rvocalicdeva",
  0x090b,
  "rvocalicgujarati",
  0x0a8b,
  "rvocalicvowelsignbengali",
  0x09c3,
  "rvocalicvowelsigndeva",
  0x0943,
  "rvocalicvowelsigngujarati",
  0x0ac3,
  "s",
  0x0073,
  "sabengali",
  0x09b8,
  "sacute",
  0x015b,
  "sacutedotaccent",
  0x1e65,
  "sadarabic",
  0x0635,
  "sadeva",
  0x0938,
  "sadfinalarabic",
  0xfeba,
  "sadinitialarabic",
  0xfebb,
  "sadmedialarabic",
  0xfebc,
  "sagujarati",
  0x0ab8,
  "sagurmukhi",
  0x0a38,
  "sahiragana",
  0x3055,
  "sakatakana",
  0x30b5,
  "sakatakanahalfwidth",
  0xff7b,
  "sallallahoualayhewasallamarabic",
  0xfdfa,
  "samekh",
  0x05e1,
  "samekhdagesh",
  0xfb41,
  "samekhdageshhebrew",
  0xfb41,
  "samekhhebrew",
  0x05e1,
  "saraaathai",
  0x0e32,
  "saraaethai",
  0x0e41,
  "saraaimaimalaithai",
  0x0e44,
  "saraaimaimuanthai",
  0x0e43,
  "saraamthai",
  0x0e33,
  "saraathai",
  0x0e30,
  "saraethai",
  0x0e40,
  "saraiileftthai",
  0xf886,
  "saraiithai",
  0x0e35,
  "saraileftthai",
  0xf885,
  "saraithai",
  0x0e34,
  "saraothai",
  0x0e42,
  "saraueeleftthai",
  0xf888,
  "saraueethai",
  0x0e37,
  "saraueleftthai",
  0xf887,
  "sarauethai",
  0x0e36,
  "sarauthai",
  0x0e38,
  "sarauuthai",
  0x0e39,
  "sbopomofo",
  0x3119,
  "scaron",
  0x0161,
  "scarondotaccent",
  0x1e67,
  "scedilla",
  0x015f,
  "schwa",
  0x0259,
  "schwacyrillic",
  0x04d9,
  "schwadieresiscyrillic",
  0x04db,
  "schwahook",
  0x025a,
  "scircle",
  0x24e2,
  "scircumflex",
  0x015d,
  "scommaaccent",
  0x0219,
  "sdotaccent",
  0x1e61,
  "sdotbelow",
  0x1e63,
  "sdotbelowdotaccent",
  0x1e69,
  "seagullbelowcmb",
  0x033c,
  "second",
  0x2033,
  "secondtonechinese",
  0x02ca,
  "section",
  0x00a7,
  "seenarabic",
  0x0633,
  "seenfinalarabic",
  0xfeb2,
  "seeninitialarabic",
  0xfeb3,
  "seenmedialarabic",
  0xfeb4,
  "segol",
  0x05b6,
  "segol13",
  0x05b6,
  "segol1f",
  0x05b6,
  "segol2c",
  0x05b6,
  "segolhebrew",
  0x05b6,
  "segolnarrowhebrew",
  0x05b6,
  "segolquarterhebrew",
  0x05b6,
  "segoltahebrew",
  0x0592,
  "segolwidehebrew",
  0x05b6,
  "seharmenian",
  0x057d,
  "sehiragana",
  0x305b,
  "sekatakana",
  0x30bb,
  "sekatakanahalfwidth",
  0xff7e,
  "semicolon",
  0x003b,
  "semicolonarabic",
  0x061b,
  "semicolonmonospace",
  0xff1b,
  "semicolonsmall",
  0xfe54,
  "semivoicedmarkkana",
  0x309c,
  "semivoicedmarkkanahalfwidth",
  0xff9f,
  "sentisquare",
  0x3322,
  "sentosquare",
  0x3323,
  "seven",
  0x0037,
  "sevenarabic",
  0x0667,
  "sevenbengali",
  0x09ed,
  "sevencircle",
  0x2466,
  "sevencircleinversesansserif",
  0x2790,
  "sevendeva",
  0x096d,
  "seveneighths",
  0x215e,
  "sevengujarati",
  0x0aed,
  "sevengurmukhi",
  0x0a6d,
  "sevenhackarabic",
  0x0667,
  "sevenhangzhou",
  0x3027,
  "sevenideographicparen",
  0x3226,
  "seveninferior",
  0x2087,
  "sevenmonospace",
  0xff17,
  "sevenoldstyle",
  0xf737,
  "sevenparen",
  0x247a,
  "sevenperiod",
  0x248e,
  "sevenpersian",
  0x06f7,
  "sevenroman",
  0x2176,
  "sevensuperior",
  0x2077,
  "seventeencircle",
  0x2470,
  "seventeenparen",
  0x2484,
  "seventeenperiod",
  0x2498,
  "seventhai",
  0x0e57,
  "sfthyphen",
  0x00ad,
  "shaarmenian",
  0x0577,
  "shabengali",
  0x09b6,
  "shacyrillic",
  0x0448,
  "shaddaarabic",
  0x0651,
  "shaddadammaarabic",
  0xfc61,
  "shaddadammatanarabic",
  0xfc5e,
  "shaddafathaarabic",
  0xfc60,
  "shaddakasraarabic",
  0xfc62,
  "shaddakasratanarabic",
  0xfc5f,
  "shade",
  0x2592,
  "shadedark",
  0x2593,
  "shadelight",
  0x2591,
  "shademedium",
  0x2592,
  "shadeva",
  0x0936,
  "shagujarati",
  0x0ab6,
  "shagurmukhi",
  0x0a36,
  "shalshelethebrew",
  0x0593,
  "shbopomofo",
  0x3115,
  "shchacyrillic",
  0x0449,
  "sheenarabic",
  0x0634,
  "sheenfinalarabic",
  0xfeb6,
  "sheeninitialarabic",
  0xfeb7,
  "sheenmedialarabic",
  0xfeb8,
  "sheicoptic",
  0x03e3,
  "sheqel",
  0x20aa,
  "sheqelhebrew",
  0x20aa,
  "sheva",
  0x05b0,
  "sheva115",
  0x05b0,
  "sheva15",
  0x05b0,
  "sheva22",
  0x05b0,
  "sheva2e",
  0x05b0,
  "shevahebrew",
  0x05b0,
  "shevanarrowhebrew",
  0x05b0,
  "shevaquarterhebrew",
  0x05b0,
  "shevawidehebrew",
  0x05b0,
  "shhacyrillic",
  0x04bb,
  "shimacoptic",
  0x03ed,
  "shin",
  0x05e9,
  "shindagesh",
  0xfb49,
  "shindageshhebrew",
  0xfb49,
  "shindageshshindot",
  0xfb2c,
  "shindageshshindothebrew",
  0xfb2c,
  "shindageshsindot",
  0xfb2d,
  "shindageshsindothebrew",
  0xfb2d,
  "shindothebrew",
  0x05c1,
  "shinhebrew",
  0x05e9,
  "shinshindot",
  0xfb2a,
  "shinshindothebrew",
  0xfb2a,
  "shinsindot",
  0xfb2b,
  "shinsindothebrew",
  0xfb2b,
  "shook",
  0x0282,
  "sigma",
  0x03c3,
  "sigma1",
  0x03c2,
  "sigmafinal",
  0x03c2,
  "sigmalunatesymbolgreek",
  0x03f2,
  "sihiragana",
  0x3057,
  "sikatakana",
  0x30b7,
  "sikatakanahalfwidth",
  0xff7c,
  "siluqhebrew",
  0x05bd,
  "siluqlefthebrew",
  0x05bd,
  "similar",
  0x223c,
  "sindothebrew",
  0x05c2,
  "siosacirclekorean",
  0x3274,
  "siosaparenkorean",
  0x3214,
  "sioscieuckorean",
  0x317e,
  "sioscirclekorean",
  0x3266,
  "sioskiyeokkorean",
  0x317a,
  "sioskorean",
  0x3145,
  "siosnieunkorean",
  0x317b,
  "siosparenkorean",
  0x3206,
  "siospieupkorean",
  0x317d,
  "siostikeutkorean",
  0x317c,
  "six",
  0x0036,
  "sixarabic",
  0x0666,
  "sixbengali",
  0x09ec,
  "sixcircle",
  0x2465,
  "sixcircleinversesansserif",
  0x278f,
  "sixdeva",
  0x096c,
  "sixgujarati",
  0x0aec,
  "sixgurmukhi",
  0x0a6c,
  "sixhackarabic",
  0x0666,
  "sixhangzhou",
  0x3026,
  "sixideographicparen",
  0x3225,
  "sixinferior",
  0x2086,
  "sixmonospace",
  0xff16,
  "sixoldstyle",
  0xf736,
  "sixparen",
  0x2479,
  "sixperiod",
  0x248d,
  "sixpersian",
  0x06f6,
  "sixroman",
  0x2175,
  "sixsuperior",
  0x2076,
  "sixteencircle",
  0x246f,
  "sixteencurrencydenominatorbengali",
  0x09f9,
  "sixteenparen",
  0x2483,
  "sixteenperiod",
  0x2497,
  "sixthai",
  0x0e56,
  "slash",
  0x002f,
  "slashmonospace",
  0xff0f,
  "slong",
  0x017f,
  "slongdotaccent",
  0x1e9b,
  "smileface",
  0x263a,
  "smonospace",
  0xff53,
  "sofpasuqhebrew",
  0x05c3,
  "softhyphen",
  0x00ad,
  "softsigncyrillic",
  0x044c,
  "sohiragana",
  0x305d,
  "sokatakana",
  0x30bd,
  "sokatakanahalfwidth",
  0xff7f,
  "soliduslongoverlaycmb",
  0x0338,
  "solidusshortoverlaycmb",
  0x0337,
  "sorusithai",
  0x0e29,
  "sosalathai",
  0x0e28,
  "sosothai",
  0x0e0b,
  "sosuathai",
  0x0e2a,
  "space",
  0x0020,
  "spacehackarabic",
  0x0020,
  "spade",
  0x2660,
  "spadesuitblack",
  0x2660,
  "spadesuitwhite",
  0x2664,
  "sparen",
  0x24ae,
  "squarebelowcmb",
  0x033b,
  "squarecc",
  0x33c4,
  "squarecm",
  0x339d,
  "squarediagonalcrosshatchfill",
  0x25a9,
  "squarehorizontalfill",
  0x25a4,
  "squarekg",
  0x338f,
  "squarekm",
  0x339e,
  "squarekmcapital",
  0x33ce,
  "squareln",
  0x33d1,
  "squarelog",
  0x33d2,
  "squaremg",
  0x338e,
  "squaremil",
  0x33d5,
  "squaremm",
  0x339c,
  "squaremsquared",
  0x33a1,
  "squareorthogonalcrosshatchfill",
  0x25a6,
  "squareupperlefttolowerrightfill",
  0x25a7,
  "squareupperrighttolowerleftfill",
  0x25a8,
  "squareverticalfill",
  0x25a5,
  "squarewhitewithsmallblack",
  0x25a3,
  "srsquare",
  0x33db,
  "ssabengali",
  0x09b7,
  "ssadeva",
  0x0937,
  "ssagujarati",
  0x0ab7,
  "ssangcieuckorean",
  0x3149,
  "ssanghieuhkorean",
  0x3185,
  "ssangieungkorean",
  0x3180,
  "ssangkiyeokkorean",
  0x3132,
  "ssangnieunkorean",
  0x3165,
  "ssangpieupkorean",
  0x3143,
  "ssangsioskorean",
  0x3146,
  "ssangtikeutkorean",
  0x3138,
  "ssuperior",
  0xf6f2,
  "sterling",
  0x00a3,
  "sterlingmonospace",
  0xffe1,
  "strokelongoverlaycmb",
  0x0336,
  "strokeshortoverlaycmb",
  0x0335,
  "subset",
  0x2282,
  "subsetnotequal",
  0x228a,
  "subsetorequal",
  0x2286,
  "succeeds",
  0x227b,
  "suchthat",
  0x220b,
  "suhiragana",
  0x3059,
  "sukatakana",
  0x30b9,
  "sukatakanahalfwidth",
  0xff7d,
  "sukunarabic",
  0x0652,
  "summation",
  0x2211,
  "sun",
  0x263c,
  "superset",
  0x2283,
  "supersetnotequal",
  0x228b,
  "supersetorequal",
  0x2287,
  "svsquare",
  0x33dc,
  "syouwaerasquare",
  0x337c,
  "t",
  0x0074,
  "tabengali",
  0x09a4,
  "tackdown",
  0x22a4,
  "tackleft",
  0x22a3,
  "tadeva",
  0x0924,
  "tagujarati",
  0x0aa4,
  "tagurmukhi",
  0x0a24,
  "taharabic",
  0x0637,
  "tahfinalarabic",
  0xfec2,
  "tahinitialarabic",
  0xfec3,
  "tahiragana",
  0x305f,
  "tahmedialarabic",
  0xfec4,
  "taisyouerasquare",
  0x337d,
  "takatakana",
  0x30bf,
  "takatakanahalfwidth",
  0xff80,
  "tatweelarabic",
  0x0640,
  "tau",
  0x03c4,
  "tav",
  0x05ea,
  "tavdages",
  0xfb4a,
  "tavdagesh",
  0xfb4a,
  "tavdageshhebrew",
  0xfb4a,
  "tavhebrew",
  0x05ea,
  "tbar",
  0x0167,
  "tbopomofo",
  0x310a,
  "tcaron",
  0x0165,
  "tccurl",
  0x02a8,
  "tcedilla",
  0x0163,
  "tcheharabic",
  0x0686,
  "tchehfinalarabic",
  0xfb7b,
  "tchehinitialarabic",
  0xfb7c,
  "tchehmedialarabic",
  0xfb7d,
  "tcircle",
  0x24e3,
  "tcircumflexbelow",
  0x1e71,
  "tcommaaccent",
  0x0163,
  "tdieresis",
  0x1e97,
  "tdotaccent",
  0x1e6b,
  "tdotbelow",
  0x1e6d,
  "tecyrillic",
  0x0442,
  "tedescendercyrillic",
  0x04ad,
  "teharabic",
  0x062a,
  "tehfinalarabic",
  0xfe96,
  "tehhahinitialarabic",
  0xfca2,
  "tehhahisolatedarabic",
  0xfc0c,
  "tehinitialarabic",
  0xfe97,
  "tehiragana",
  0x3066,
  "tehjeeminitialarabic",
  0xfca1,
  "tehjeemisolatedarabic",
  0xfc0b,
  "tehmarbutaarabic",
  0x0629,
  "tehmarbutafinalarabic",
  0xfe94,
  "tehmedialarabic",
  0xfe98,
  "tehmeeminitialarabic",
  0xfca4,
  "tehmeemisolatedarabic",
  0xfc0e,
  "tehnoonfinalarabic",
  0xfc73,
  "tekatakana",
  0x30c6,
  "tekatakanahalfwidth",
  0xff83,
  "telephone",
  0x2121,
  "telephoneblack",
  0x260e,
  "telishagedolahebrew",
  0x05a0,
  "telishaqetanahebrew",
  0x05a9,
  "tencircle",
  0x2469,
  "tenideographicparen",
  0x3229,
  "tenparen",
  0x247d,
  "tenperiod",
  0x2491,
  "tenroman",
  0x2179,
  "tesh",
  0x02a7,
  "tet",
  0x05d8,
  "tetdagesh",
  0xfb38,
  "tetdageshhebrew",
  0xfb38,
  "tethebrew",
  0x05d8,
  "tetsecyrillic",
  0x04b5,
  "tevirhebrew",
  0x059b,
  "tevirlefthebrew",
  0x059b,
  "thabengali",
  0x09a5,
  "thadeva",
  0x0925,
  "thagujarati",
  0x0aa5,
  "thagurmukhi",
  0x0a25,
  "thalarabic",
  0x0630,
  "thalfinalarabic",
  0xfeac,
  "thanthakhatlowleftthai",
  0xf898,
  "thanthakhatlowrightthai",
  0xf897,
  "thanthakhatthai",
  0x0e4c,
  "thanthakhatupperleftthai",
  0xf896,
  "theharabic",
  0x062b,
  "thehfinalarabic",
  0xfe9a,
  "thehinitialarabic",
  0xfe9b,
  "thehmedialarabic",
  0xfe9c,
  "thereexists",
  0x2203,
  "therefore",
  0x2234,
  "theta",
  0x03b8,
  "theta1",
  0x03d1,
  "thetasymbolgreek",
  0x03d1,
  "thieuthacirclekorean",
  0x3279,
  "thieuthaparenkorean",
  0x3219,
  "thieuthcirclekorean",
  0x326b,
  "thieuthkorean",
  0x314c,
  "thieuthparenkorean",
  0x320b,
  "thirteencircle",
  0x246c,
  "thirteenparen",
  0x2480,
  "thirteenperiod",
  0x2494,
  "thonangmonthothai",
  0x0e11,
  "thook",
  0x01ad,
  "thophuthaothai",
  0x0e12,
  "thorn",
  0x00fe,
  "thothahanthai",
  0x0e17,
  "thothanthai",
  0x0e10,
  "thothongthai",
  0x0e18,
  "thothungthai",
  0x0e16,
  "thousandcyrillic",
  0x0482,
  "thousandsseparatorarabic",
  0x066c,
  "thousandsseparatorpersian",
  0x066c,
  "three",
  0x0033,
  "threearabic",
  0x0663,
  "threebengali",
  0x09e9,
  "threecircle",
  0x2462,
  "threecircleinversesansserif",
  0x278c,
  "threedeva",
  0x0969,
  "threeeighths",
  0x215c,
  "threegujarati",
  0x0ae9,
  "threegurmukhi",
  0x0a69,
  "threehackarabic",
  0x0663,
  "threehangzhou",
  0x3023,
  "threeideographicparen",
  0x3222,
  "threeinferior",
  0x2083,
  "threemonospace",
  0xff13,
  "threenumeratorbengali",
  0x09f6,
  "threeoldstyle",
  0xf733,
  "threeparen",
  0x2476,
  "threeperiod",
  0x248a,
  "threepersian",
  0x06f3,
  "threequarters",
  0x00be,
  "threequartersemdash",
  0xf6de,
  "threeroman",
  0x2172,
  "threesuperior",
  0x00b3,
  "threethai",
  0x0e53,
  "thzsquare",
  0x3394,
  "tihiragana",
  0x3061,
  "tikatakana",
  0x30c1,
  "tikatakanahalfwidth",
  0xff81,
  "tikeutacirclekorean",
  0x3270,
  "tikeutaparenkorean",
  0x3210,
  "tikeutcirclekorean",
  0x3262,
  "tikeutkorean",
  0x3137,
  "tikeutparenkorean",
  0x3202,
  "tilde",
  0x02dc,
  "tildebelowcmb",
  0x0330,
  "tildecmb",
  0x0303,
  "tildecomb",
  0x0303,
  "tildedoublecmb",
  0x0360,
  "tildeoperator",
  0x223c,
  "tildeoverlaycmb",
  0x0334,
  "tildeverticalcmb",
  0x033e,
  "timescircle",
  0x2297,
  "tipehahebrew",
  0x0596,
  "tipehalefthebrew",
  0x0596,
  "tippigurmukhi",
  0x0a70,
  "titlocyrilliccmb",
  0x0483,
  "tiwnarmenian",
  0x057f,
  "tlinebelow",
  0x1e6f,
  "tmonospace",
  0xff54,
  "toarmenian",
  0x0569,
  "tohiragana",
  0x3068,
  "tokatakana",
  0x30c8,
  "tokatakanahalfwidth",
  0xff84,
  "tonebarextrahighmod",
  0x02e5,
  "tonebarextralowmod",
  0x02e9,
  "tonebarhighmod",
  0x02e6,
  "tonebarlowmod",
  0x02e8,
  "tonebarmidmod",
  0x02e7,
  "tonefive",
  0x01bd,
  "tonesix",
  0x0185,
  "tonetwo",
  0x01a8,
  "tonos",
  0x0384,
  "tonsquare",
  0x3327,
  "topatakthai",
  0x0e0f,
  "tortoiseshellbracketleft",
  0x3014,
  "tortoiseshellbracketleftsmall",
  0xfe5d,
  "tortoiseshellbracketleftvertical",
  0xfe39,
  "tortoiseshellbracketright",
  0x3015,
  "tortoiseshellbracketrightsmall",
  0xfe5e,
  "tortoiseshellbracketrightvertical",
  0xfe3a,
  "totaothai",
  0x0e15,
  "tpalatalhook",
  0x01ab,
  "tparen",
  0x24af,
  "trademark",
  0x2122,
  "trademarksans",
  0xf8ea,
  "trademarkserif",
  0xf6db,
  "tretroflexhook",
  0x0288,
  "triagdn",
  0x25bc,
  "triaglf",
  0x25c4,
  "triagrt",
  0x25ba,
  "triagup",
  0x25b2,
  "ts",
  0x02a6,
  "tsadi",
  0x05e6,
  "tsadidagesh",
  0xfb46,
  "tsadidageshhebrew",
  0xfb46,
  "tsadihebrew",
  0x05e6,
  "tsecyrillic",
  0x0446,
  "tsere",
  0x05b5,
  "tsere12",
  0x05b5,
  "tsere1e",
  0x05b5,
  "tsere2b",
  0x05b5,
  "tserehebrew",
  0x05b5,
  "tserenarrowhebrew",
  0x05b5,
  "tserequarterhebrew",
  0x05b5,
  "tserewidehebrew",
  0x05b5,
  "tshecyrillic",
  0x045b,
  "tsuperior",
  0xf6f3,
  "ttabengali",
  0x099f,
  "ttadeva",
  0x091f,
  "ttagujarati",
  0x0a9f,
  "ttagurmukhi",
  0x0a1f,
  "tteharabic",
  0x0679,
  "ttehfinalarabic",
  0xfb67,
  "ttehinitialarabic",
  0xfb68,
  "ttehmedialarabic",
  0xfb69,
  "tthabengali",
  0x09a0,
  "tthadeva",
  0x0920,
  "tthagujarati",
  0x0aa0,
  "tthagurmukhi",
  0x0a20,
  "tturned",
  0x0287,
  "tuhiragana",
  0x3064,
  "tukatakana",
  0x30c4,
  "tukatakanahalfwidth",
  0xff82,
  "tusmallhiragana",
  0x3063,
  "tusmallkatakana",
  0x30c3,
  "tusmallkatakanahalfwidth",
  0xff6f,
  "twelvecircle",
  0x246b,
  "twelveparen",
  0x247f,
  "twelveperiod",
  0x2493,
  "twelveroman",
  0x217b,
  "twentycircle",
  0x2473,
  "twentyhangzhou",
  0x5344,
  "twentyparen",
  0x2487,
  "twentyperiod",
  0x249b,
  "two",
  0x0032,
  "twoarabic",
  0x0662,
  "twobengali",
  0x09e8,
  "twocircle",
  0x2461,
  "twocircleinversesansserif",
  0x278b,
  "twodeva",
  0x0968,
  "twodotenleader",
  0x2025,
  "twodotleader",
  0x2025,
  "twodotleadervertical",
  0xfe30,
  "twogujarati",
  0x0ae8,
  "twogurmukhi",
  0x0a68,
  "twohackarabic",
  0x0662,
  "twohangzhou",
  0x3022,
  "twoideographicparen",
  0x3221,
  "twoinferior",
  0x2082,
  "twomonospace",
  0xff12,
  "twonumeratorbengali",
  0x09f5,
  "twooldstyle",
  0xf732,
  "twoparen",
  0x2475,
  "twoperiod",
  0x2489,
  "twopersian",
  0x06f2,
  "tworoman",
  0x2171,
  "twostroke",
  0x01bb,
  "twosuperior",
  0x00b2,
  "twothai",
  0x0e52,
  "twothirds",
  0x2154,
  "u",
  0x0075,
  "uacute",
  0x00fa,
  "ubar",
  0x0289,
  "ubengali",
  0x0989,
  "ubopomofo",
  0x3128,
  "ubreve",
  0x016d,
  "ucaron",
  0x01d4,
  "ucircle",
  0x24e4,
  "ucircumflex",
  0x00fb,
  "ucircumflexbelow",
  0x1e77,
  "ucyrillic",
  0x0443,
  "udattadeva",
  0x0951,
  "udblacute",
  0x0171,
  "udblgrave",
  0x0215,
  "udeva",
  0x0909,
  "udieresis",
  0x00fc,
  "udieresisacute",
  0x01d8,
  "udieresisbelow",
  0x1e73,
  "udieresiscaron",
  0x01da,
  "udieresiscyrillic",
  0x04f1,
  "udieresisgrave",
  0x01dc,
  "udieresismacron",
  0x01d6,
  "udotbelow",
  0x1ee5,
  "ugrave",
  0x00f9,
  "ugujarati",
  0x0a89,
  "ugurmukhi",
  0x0a09,
  "uhiragana",
  0x3046,
  "uhookabove",
  0x1ee7,
  "uhorn",
  0x01b0,
  "uhornacute",
  0x1ee9,
  "uhorndotbelow",
  0x1ef1,
  "uhorngrave",
  0x1eeb,
  "uhornhookabove",
  0x1eed,
  "uhorntilde",
  0x1eef,
  "uhungarumlaut",
  0x0171,
  "uhungarumlautcyrillic",
  0x04f3,
  "uinvertedbreve",
  0x0217,
  "ukatakana",
  0x30a6,
  "ukatakanahalfwidth",
  0xff73,
  "ukcyrillic",
  0x0479,
  "ukorean",
  0x315c,
  "umacron",
  0x016b,
  "umacroncyrillic",
  0x04ef,
  "umacrondieresis",
  0x1e7b,
  "umatragurmukhi",
  0x0a41,
  "umonospace",
  0xff55,
  "underscore",
  0x005f,
  "underscoredbl",
  0x2017,
  "underscoremonospace",
  0xff3f,
  "underscorevertical",
  0xfe33,
  "underscorewavy",
  0xfe4f,
  "union",
  0x222a,
  "universal",
  0x2200,
  "uogonek",
  0x0173,
  "uparen",
  0x24b0,
  "upblock",
  0x2580,
  "upperdothebrew",
  0x05c4,
  "upsilon",
  0x03c5,
  "upsilondieresis",
  0x03cb,
  "upsilondieresistonos",
  0x03b0,
  "upsilonlatin",
  0x028a,
  "upsilontonos",
  0x03cd,
  "uptackbelowcmb",
  0x031d,
  "uptackmod",
  0x02d4,
  "uragurmukhi",
  0x0a73,
  "uring",
  0x016f,
  "ushortcyrillic",
  0x045e,
  "usmallhiragana",
  0x3045,
  "usmallkatakana",
  0x30a5,
  "usmallkatakanahalfwidth",
  0xff69,
  "ustraightcyrillic",
  0x04af,
  "ustraightstrokecyrillic",
  0x04b1,
  "utilde",
  0x0169,
  "utildeacute",
  0x1e79,
  "utildebelow",
  0x1e75,
  "uubengali",
  0x098a,
  "uudeva",
  0x090a,
  "uugujarati",
  0x0a8a,
  "uugurmukhi",
  0x0a0a,
  "uumatragurmukhi",
  0x0a42,
  "uuvowelsignbengali",
  0x09c2,
  "uuvowelsigndeva",
  0x0942,
  "uuvowelsigngujarati",
  0x0ac2,
  "uvowelsignbengali",
  0x09c1,
  "uvowelsigndeva",
  0x0941,
  "uvowelsigngujarati",
  0x0ac1,
  "v",
  0x0076,
  "vadeva",
  0x0935,
  "vagujarati",
  0x0ab5,
  "vagurmukhi",
  0x0a35,
  "vakatakana",
  0x30f7,
  "vav",
  0x05d5,
  "vavdagesh",
  0xfb35,
  "vavdagesh65",
  0xfb35,
  "vavdageshhebrew",
  0xfb35,
  "vavhebrew",
  0x05d5,
  "vavholam",
  0xfb4b,
  "vavholamhebrew",
  0xfb4b,
  "vavvavhebrew",
  0x05f0,
  "vavyodhebrew",
  0x05f1,
  "vcircle",
  0x24e5,
  "vdotbelow",
  0x1e7f,
  "vecyrillic",
  0x0432,
  "veharabic",
  0x06a4,
  "vehfinalarabic",
  0xfb6b,
  "vehinitialarabic",
  0xfb6c,
  "vehmedialarabic",
  0xfb6d,
  "vekatakana",
  0x30f9,
  "venus",
  0x2640,
  "verticalbar",
  0x007c,
  "verticallineabovecmb",
  0x030d,
  "verticallinebelowcmb",
  0x0329,
  "verticallinelowmod",
  0x02cc,
  "verticallinemod",
  0x02c8,
  "vewarmenian",
  0x057e,
  "vhook",
  0x028b,
  "vikatakana",
  0x30f8,
  "viramabengali",
  0x09cd,
  "viramadeva",
  0x094d,
  "viramagujarati",
  0x0acd,
  "visargabengali",
  0x0983,
  "visargadeva",
  0x0903,
  "visargagujarati",
  0x0a83,
  "vmonospace",
  0xff56,
  "voarmenian",
  0x0578,
  "voicediterationhiragana",
  0x309e,
  "voicediterationkatakana",
  0x30fe,
  "voicedmarkkana",
  0x309b,
  "voicedmarkkanahalfwidth",
  0xff9e,
  "vokatakana",
  0x30fa,
  "vparen",
  0x24b1,
  "vtilde",
  0x1e7d,
  "vturned",
  0x028c,
  "vuhiragana",
  0x3094,
  "vukatakana",
  0x30f4,
  "w",
  0x0077,
  "wacute",
  0x1e83,
  "waekorean",
  0x3159,
  "wahiragana",
  0x308f,
  "wakatakana",
  0x30ef,
  "wakatakanahalfwidth",
  0xff9c,
  "wakorean",
  0x3158,
  "wasmallhiragana",
  0x308e,
  "wasmallkatakana",
  0x30ee,
  "wattosquare",
  0x3357,
  "wavedash",
  0x301c,
  "wavyunderscorevertical",
  0xfe34,
  "wawarabic",
  0x0648,
  "wawfinalarabic",
  0xfeee,
  "wawhamzaabovearabic",
  0x0624,
  "wawhamzaabovefinalarabic",
  0xfe86,
  "wbsquare",
  0x33dd,
  "wcircle",
  0x24e6,
  "wcircumflex",
  0x0175,
  "wdieresis",
  0x1e85,
  "wdotaccent",
  0x1e87,
  "wdotbelow",
  0x1e89,
  "wehiragana",
  0x3091,
  "weierstrass",
  0x2118,
  "wekatakana",
  0x30f1,
  "wekorean",
  0x315e,
  "weokorean",
  0x315d,
  "wgrave",
  0x1e81,
  "whitebullet",
  0x25e6,
  "whitecircle",
  0x25cb,
  "whitecircleinverse",
  0x25d9,
  "whitecornerbracketleft",
  0x300e,
  "whitecornerbracketleftvertical",
  0xfe43,
  "whitecornerbracketright",
  0x300f,
  "whitecornerbracketrightvertical",
  0xfe44,
  "whitediamond",
  0x25c7,
  "whitediamondcontainingblacksmalldiamond",
  0x25c8,
  "whitedownpointingsmalltriangle",
  0x25bf,
  "whitedownpointingtriangle",
  0x25bd,
  "whiteleftpointingsmalltriangle",
  0x25c3,
  "whiteleftpointingtriangle",
  0x25c1,
  "whitelenticularbracketleft",
  0x3016,
  "whitelenticularbracketright",
  0x3017,
  "whiterightpointingsmalltriangle",
  0x25b9,
  "whiterightpointingtriangle",
  0x25b7,
  "whitesmallsquare",
  0x25ab,
  "whitesmilingface",
  0x263a,
  "whitesquare",
  0x25a1,
  "whitestar",
  0x2606,
  "whitetelephone",
  0x260f,
  "whitetortoiseshellbracketleft",
  0x3018,
  "whitetortoiseshellbracketright",
  0x3019,
  "whiteuppointingsmalltriangle",
  0x25b5,
  "whiteuppointingtriangle",
  0x25b3,
  "wihiragana",
  0x3090,
  "wikatakana",
  0x30f0,
  "wikorean",
  0x315f,
  "wmonospace",
  0xff57,
  "wohiragana",
  0x3092,
  "wokatakana",
  0x30f2,
  "wokatakanahalfwidth",
  0xff66,
  "won",
  0x20a9,
  "wonmonospace",
  0xffe6,
  "wowaenthai",
  0x0e27,
  "wparen",
  0x24b2,
  "wring",
  0x1e98,
  "wsuperior",
  0x02b7,
  "wturned",
  0x028d,
  "wynn",
  0x01bf,
  "x",
  0x0078,
  "xabovecmb",
  0x033d,
  "xbopomofo",
  0x3112,
  "xcircle",
  0x24e7,
  "xdieresis",
  0x1e8d,
  "xdotaccent",
  0x1e8b,
  "xeharmenian",
  0x056d,
  "xi",
  0x03be,
  "xmonospace",
  0xff58,
  "xparen",
  0x24b3,
  "xsuperior",
  0x02e3,
  "y",
  0x0079,
  "yaadosquare",
  0x334e,
  "yabengali",
  0x09af,
  "yacute",
  0x00fd,
  "yadeva",
  0x092f,
  "yaekorean",
  0x3152,
  "yagujarati",
  0x0aaf,
  "yagurmukhi",
  0x0a2f,
  "yahiragana",
  0x3084,
  "yakatakana",
  0x30e4,
  "yakatakanahalfwidth",
  0xff94,
  "yakorean",
  0x3151,
  "yamakkanthai",
  0x0e4e,
  "yasmallhiragana",
  0x3083,
  "yasmallkatakana",
  0x30e3,
  "yasmallkatakanahalfwidth",
  0xff6c,
  "yatcyrillic",
  0x0463,
  "ycircle",
  0x24e8,
  "ycircumflex",
  0x0177,
  "ydieresis",
  0x00ff,
  "ydotaccent",
  0x1e8f,
  "ydotbelow",
  0x1ef5,
  "yeharabic",
  0x064a,
  "yehbarreearabic",
  0x06d2,
  "yehbarreefinalarabic",
  0xfbaf,
  "yehfinalarabic",
  0xfef2,
  "yehhamzaabovearabic",
  0x0626,
  "yehhamzaabovefinalarabic",
  0xfe8a,
  "yehhamzaaboveinitialarabic",
  0xfe8b,
  "yehhamzaabovemedialarabic",
  0xfe8c,
  "yehinitialarabic",
  0xfef3,
  "yehmedialarabic",
  0xfef4,
  "yehmeeminitialarabic",
  0xfcdd,
  "yehmeemisolatedarabic",
  0xfc58,
  "yehnoonfinalarabic",
  0xfc94,
  "yehthreedotsbelowarabic",
  0x06d1,
  "yekorean",
  0x3156,
  "yen",
  0x00a5,
  "yenmonospace",
  0xffe5,
  "yeokorean",
  0x3155,
  "yeorinhieuhkorean",
  0x3186,
  "yerahbenyomohebrew",
  0x05aa,
  "yerahbenyomolefthebrew",
  0x05aa,
  "yericyrillic",
  0x044b,
  "yerudieresiscyrillic",
  0x04f9,
  "yesieungkorean",
  0x3181,
  "yesieungpansioskorean",
  0x3183,
  "yesieungsioskorean",
  0x3182,
  "yetivhebrew",
  0x059a,
  "ygrave",
  0x1ef3,
  "yhook",
  0x01b4,
  "yhookabove",
  0x1ef7,
  "yiarmenian",
  0x0575,
  "yicyrillic",
  0x0457,
  "yikorean",
  0x3162,
  "yinyang",
  0x262f,
  "yiwnarmenian",
  0x0582,
  "ymonospace",
  0xff59,
  "yod",
  0x05d9,
  "yoddagesh",
  0xfb39,
  "yoddageshhebrew",
  0xfb39,
  "yodhebrew",
  0x05d9,
  "yodyodhebrew",
  0x05f2,
  "yodyodpatahhebrew",
  0xfb1f,
  "yohiragana",
  0x3088,
  "yoikorean",
  0x3189,
  "yokatakana",
  0x30e8,
  "yokatakanahalfwidth",
  0xff96,
  "yokorean",
  0x315b,
  "yosmallhiragana",
  0x3087,
  "yosmallkatakana",
  0x30e7,
  "yosmallkatakanahalfwidth",
  0xff6e,
  "yotgreek",
  0x03f3,
  "yoyaekorean",
  0x3188,
  "yoyakorean",
  0x3187,
  "yoyakthai",
  0x0e22,
  "yoyingthai",
  0x0e0d,
  "yparen",
  0x24b4,
  "ypogegrammeni",
  0x037a,
  "ypogegrammenigreekcmb",
  0x0345,
  "yr",
  0x01a6,
  "yring",
  0x1e99,
  "ysuperior",
  0x02b8,
  "ytilde",
  0x1ef9,
  "yturned",
  0x028e,
  "yuhiragana",
  0x3086,
  "yuikorean",
  0x318c,
  "yukatakana",
  0x30e6,
  "yukatakanahalfwidth",
  0xff95,
  "yukorean",
  0x3160,
  "yusbigcyrillic",
  0x046b,
  "yusbigiotifiedcyrillic",
  0x046d,
  "yuslittlecyrillic",
  0x0467,
  "yuslittleiotifiedcyrillic",
  0x0469,
  "yusmallhiragana",
  0x3085,
  "yusmallkatakana",
  0x30e5,
  "yusmallkatakanahalfwidth",
  0xff6d,
  "yuyekorean",
  0x318b,
  "yuyeokorean",
  0x318a,
  "yyabengali",
  0x09df,
  "yyadeva",
  0x095f,
  "z",
  0x007a,
  "zaarmenian",
  0x0566,
  "zacute",
  0x017a,
  "zadeva",
  0x095b,
  "zagurmukhi",
  0x0a5b,
  "zaharabic",
  0x0638,
  "zahfinalarabic",
  0xfec6,
  "zahinitialarabic",
  0xfec7,
  "zahiragana",
  0x3056,
  "zahmedialarabic",
  0xfec8,
  "zainarabic",
  0x0632,
  "zainfinalarabic",
  0xfeb0,
  "zakatakana",
  0x30b6,
  "zaqefgadolhebrew",
  0x0595,
  "zaqefqatanhebrew",
  0x0594,
  "zarqahebrew",
  0x0598,
  "zayin",
  0x05d6,
  "zayindagesh",
  0xfb36,
  "zayindageshhebrew",
  0xfb36,
  "zayinhebrew",
  0x05d6,
  "zbopomofo",
  0x3117,
  "zcaron",
  0x017e,
  "zcircle",
  0x24e9,
  "zcircumflex",
  0x1e91,
  "zcurl",
  0x0291,
  "zdot",
  0x017c,
  "zdotaccent",
  0x017c,
  "zdotbelow",
  0x1e93,
  "zecyrillic",
  0x0437,
  "zedescendercyrillic",
  0x0499,
  "zedieresiscyrillic",
  0x04df,
  "zehiragana",
  0x305c,
  "zekatakana",
  0x30bc,
  "zero",
  0x0030,
  "zeroarabic",
  0x0660,
  "zerobengali",
  0x09e6,
  "zerodeva",
  0x0966,
  "zerogujarati",
  0x0ae6,
  "zerogurmukhi",
  0x0a66,
  "zerohackarabic",
  0x0660,
  "zeroinferior",
  0x2080,
  "zeromonospace",
  0xff10,
  "zerooldstyle",
  0xf730,
  "zeropersian",
  0x06f0,
  "zerosuperior",
  0x2070,
  "zerothai",
  0x0e50,
  "zerowidthjoiner",
  0xfeff,
  "zerowidthnonjoiner",
  0x200c,
  "zerowidthspace",
  0x200b,
  "zeta",
  0x03b6,
  "zhbopomofo",
  0x3113,
  "zhearmenian",
  0x056a,
  "zhebrevecyrillic",
  0x04c2,
  "zhecyrillic",
  0x0436,
  "zhedescendercyrillic",
  0x0497,
  "zhedieresiscyrillic",
  0x04dd,
  "zihiragana",
  0x3058,
  "zikatakana",
  0x30b8,
  "zinorhebrew",
  0x05ae,
  "zlinebelow",
  0x1e95,
  "zmonospace",
  0xff5a,
  "zohiragana",
  0x305e,
  "zokatakana",
  0x30be,
  "zparen",
  0x24b5,
  "zretroflexhook",
  0x0290,
  "zstroke",
  0x01b6,
  "zuhiragana",
  0x305a,
  "zukatakana",
  0x30ba,
  ".notdef",
  0x0000,
  "angbracketleftbig",
  0x2329,
  "angbracketleftBig",
  0x2329,
  "angbracketleftbigg",
  0x2329,
  "angbracketleftBigg",
  0x2329,
  "angbracketrightBig",
  0x232a,
  "angbracketrightbig",
  0x232a,
  "angbracketrightBigg",
  0x232a,
  "angbracketrightbigg",
  0x232a,
  "arrowhookleft",
  0x21aa,
  "arrowhookright",
  0x21a9,
  "arrowlefttophalf",
  0x21bc,
  "arrowleftbothalf",
  0x21bd,
  "arrownortheast",
  0x2197,
  "arrownorthwest",
  0x2196,
  "arrowrighttophalf",
  0x21c0,
  "arrowrightbothalf",
  0x21c1,
  "arrowsoutheast",
  0x2198,
  "arrowsouthwest",
  0x2199,
  "backslashbig",
  0x2216,
  "backslashBig",
  0x2216,
  "backslashBigg",
  0x2216,
  "backslashbigg",
  0x2216,
  "bardbl",
  0x2016,
  "bracehtipdownleft",
  0xfe37,
  "bracehtipdownright",
  0xfe37,
  "bracehtipupleft",
  0xfe38,
  "bracehtipupright",
  0xfe38,
  "braceleftBig",
  0x007b,
  "braceleftbig",
  0x007b,
  "braceleftbigg",
  0x007b,
  "braceleftBigg",
  0x007b,
  "bracerightBig",
  0x007d,
  "bracerightbig",
  0x007d,
  "bracerightbigg",
  0x007d,
  "bracerightBigg",
  0x007d,
  "bracketleftbig",
  0x005b,
  "bracketleftBig",
  0x005b,
  "bracketleftbigg",
  0x005b,
  "bracketleftBigg",
  0x005b,
  "bracketrightBig",
  0x005d,
  "bracketrightbig",
  0x005d,
  "bracketrightbigg",
  0x005d,
  "bracketrightBigg",
  0x005d,
  "ceilingleftbig",
  0x2308,
  "ceilingleftBig",
  0x2308,
  "ceilingleftBigg",
  0x2308,
  "ceilingleftbigg",
  0x2308,
  "ceilingrightbig",
  0x2309,
  "ceilingrightBig",
  0x2309,
  "ceilingrightbigg",
  0x2309,
  "ceilingrightBigg",
  0x2309,
  "circledotdisplay",
  0x2299,
  "circledottext",
  0x2299,
  "circlemultiplydisplay",
  0x2297,
  "circlemultiplytext",
  0x2297,
  "circleplusdisplay",
  0x2295,
  "circleplustext",
  0x2295,
  "contintegraldisplay",
  0x222e,
  "contintegraltext",
  0x222e,
  "coproductdisplay",
  0x2210,
  "coproducttext",
  0x2210,
  "floorleftBig",
  0x230a,
  "floorleftbig",
  0x230a,
  "floorleftbigg",
  0x230a,
  "floorleftBigg",
  0x230a,
  "floorrightbig",
  0x230b,
  "floorrightBig",
  0x230b,
  "floorrightBigg",
  0x230b,
  "floorrightbigg",
  0x230b,
  "hatwide",
  0x0302,
  "hatwider",
  0x0302,
  "hatwidest",
  0x0302,
  "intercal",
  0x1d40,
  "integraldisplay",
  0x222b,
  "integraltext",
  0x222b,
  "intersectiondisplay",
  0x22c2,
  "intersectiontext",
  0x22c2,
  "logicalanddisplay",
  0x2227,
  "logicalandtext",
  0x2227,
  "logicalordisplay",
  0x2228,
  "logicalortext",
  0x2228,
  "parenleftBig",
  0x0028,
  "parenleftbig",
  0x0028,
  "parenleftBigg",
  0x0028,
  "parenleftbigg",
  0x0028,
  "parenrightBig",
  0x0029,
  "parenrightbig",
  0x0029,
  "parenrightBigg",
  0x0029,
  "parenrightbigg",
  0x0029,
  "prime",
  0x2032,
  "productdisplay",
  0x220f,
  "producttext",
  0x220f,
  "radicalbig",
  0x221a,
  "radicalBig",
  0x221a,
  "radicalBigg",
  0x221a,
  "radicalbigg",
  0x221a,
  "radicalbt",
  0x221a,
  "radicaltp",
  0x221a,
  "radicalvertex",
  0x221a,
  "slashbig",
  0x002f,
  "slashBig",
  0x002f,
  "slashBigg",
  0x002f,
  "slashbigg",
  0x002f,
  "summationdisplay",
  0x2211,
  "summationtext",
  0x2211,
  "tildewide",
  0x02dc,
  "tildewider",
  0x02dc,
  "tildewidest",
  0x02dc,
  "uniondisplay",
  0x22c3,
  "unionmultidisplay",
  0x228e,
  "unionmultitext",
  0x228e,
  "unionsqdisplay",
  0x2294,
  "unionsqtext",
  0x2294,
  "uniontext",
  0x22c3,
  "vextenddouble",
  0x2225,
  "vextendsingle",
  0x2223
 ];
});
const getDingbatsGlyphsUnicode = (0,_core_utils_js__WEBPACK_IMPORTED_MODULE_0__.getArrayLookupTableFactory)(function () {
 return [
  "space",
  0x0020,
  "a1",
  0x2701,
  "a2",
  0x2702,
  "a202",
  0x2703,
  "a3",
  0x2704,
  "a4",
  0x260e,
  "a5",
  0x2706,
  "a119",
  0x2707,
  "a118",
  0x2708,
  "a117",
  0x2709,
  "a11",
  0x261b,
  "a12",
  0x261e,
  "a13",
  0x270c,
  "a14",
  0x270d,
  "a15",
  0x270e,
  "a16",
  0x270f,
  "a105",
  0x2710,
  "a17",
  0x2711,
  "a18",
  0x2712,
  "a19",
  0x2713,
  "a20",
  0x2714,
  "a21",
  0x2715,
  "a22",
  0x2716,
  "a23",
  0x2717,
  "a24",
  0x2718,
  "a25",
  0x2719,
  "a26",
  0x271a,
  "a27",
  0x271b,
  "a28",
  0x271c,
  "a6",
  0x271d,
  "a7",
  0x271e,
  "a8",
  0x271f,
  "a9",
  0x2720,
  "a10",
  0x2721,
  "a29",
  0x2722,
  "a30",
  0x2723,
  "a31",
  0x2724,
  "a32",
  0x2725,
  "a33",
  0x2726,
  "a34",
  0x2727,
  "a35",
  0x2605,
  "a36",
  0x2729,
  "a37",
  0x272a,
  "a38",
  0x272b,
  "a39",
  0x272c,
  "a40",
  0x272d,
  "a41",
  0x272e,
  "a42",
  0x272f,
  "a43",
  0x2730,
  "a44",
  0x2731,
  "a45",
  0x2732,
  "a46",
  0x2733,
  "a47",
  0x2734,
  "a48",
  0x2735,
  "a49",
  0x2736,
  "a50",
  0x2737,
  "a51",
  0x2738,
  "a52",
  0x2739,
  "a53",
  0x273a,
  "a54",
  0x273b,
  "a55",
  0x273c,
  "a56",
  0x273d,
  "a57",
  0x273e,
  "a58",
  0x273f,
  "a59",
  0x2740,
  "a60",
  0x2741,
  "a61",
  0x2742,
  "a62",
  0x2743,
  "a63",
  0x2744,
  "a64",
  0x2745,
  "a65",
  0x2746,
  "a66",
  0x2747,
  "a67",
  0x2748,
  "a68",
  0x2749,
  "a69",
  0x274a,
  "a70",
  0x274b,
  "a71",
  0x25cf,
  "a72",
  0x274d,
  "a73",
  0x25a0,
  "a74",
  0x274f,
  "a203",
  0x2750,
  "a75",
  0x2751,
  "a204",
  0x2752,
  "a76",
  0x25b2,
  "a77",
  0x25bc,
  "a78",
  0x25c6,
  "a79",
  0x2756,
  "a81",
  0x25d7,
  "a82",
  0x2758,
  "a83",
  0x2759,
  "a84",
  0x275a,
  "a97",
  0x275b,
  "a98",
  0x275c,
  "a99",
  0x275d,
  "a100",
  0x275e,
  "a101",
  0x2761,
  "a102",
  0x2762,
  "a103",
  0x2763,
  "a104",
  0x2764,
  "a106",
  0x2765,
  "a107",
  0x2766,
  "a108",
  0x2767,
  "a112",
  0x2663,
  "a111",
  0x2666,
  "a110",
  0x2665,
  "a109",
  0x2660,
  "a120",
  0x2460,
  "a121",
  0x2461,
  "a122",
  0x2462,
  "a123",
  0x2463,
  "a124",
  0x2464,
  "a125",
  0x2465,
  "a126",
  0x2466,
  "a127",
  0x2467,
  "a128",
  0x2468,
  "a129",
  0x2469,
  "a130",
  0x2776,
  "a131",
  0x2777,
  "a132",
  0x2778,
  "a133",
  0x2779,
  "a134",
  0x277a,
  "a135",
  0x277b,
  "a136",
  0x277c,
  "a137",
  0x277d,
  "a138",
  0x277e,
  "a139",
  0x277f,
  "a140",
  0x2780,
  "a141",
  0x2781,
  "a142",
  0x2782,
  "a143",
  0x2783,
  "a144",
  0x2784,
  "a145",
  0x2785,
  "a146",
  0x2786,
  "a147",
  0x2787,
  "a148",
  0x2788,
  "a149",
  0x2789,
  "a150",
  0x278a,
  "a151",
  0x278b,
  "a152",
  0x278c,
  "a153",
  0x278d,
  "a154",
  0x278e,
  "a155",
  0x278f,
  "a156",
  0x2790,
  "a157",
  0x2791,
  "a158",
  0x2792,
  "a159",
  0x2793,
  "a160",
  0x2794,
  "a161",
  0x2192,
  "a163",
  0x2194,
  "a164",
  0x2195,
  "a196",
  0x2798,
  "a165",
  0x2799,
  "a192",
  0x279a,
  "a166",
  0x279b,
  "a167",
  0x279c,
  "a168",
  0x279d,
  "a169",
  0x279e,
  "a170",
  0x279f,
  "a171",
  0x27a0,
  "a172",
  0x27a1,
  "a173",
  0x27a2,
  "a162",
  0x27a3,
  "a174",
  0x27a4,
  "a175",
  0x27a5,
  "a176",
  0x27a6,
  "a177",
  0x27a7,
  "a178",
  0x27a8,
  "a179",
  0x27a9,
  "a193",
  0x27aa,
  "a180",
  0x27ab,
  "a199",
  0x27ac,
  "a181",
  0x27ad,
  "a200",
  0x27ae,
  "a182",
  0x27af,
  "a201",
  0x27b1,
  "a183",
  0x27b2,
  "a184",
  0x27b3,
  "a197",
  0x27b4,
  "a185",
  0x27b5,
  "a194",
  0x27b6,
  "a198",
  0x27b7,
  "a186",
  0x27b8,
  "a195",
  0x27b9,
  "a187",
  0x27ba,
  "a188",
  0x27bb,
  "a189",
  0x27bc,
  "a190",
  0x27bd,
  "a191",
  0x27be,
  "a89",
  0x2768,
  "a90",
  0x2769,
  "a93",
  0x276a,
  "a94",
  0x276b,
  "a91",
  0x276c,
  "a92",
  0x276d,
  "a205",
  0x276e,
  "a85",
  0x276f,
  "a206",
  0x2770,
  "a86",
  0x2771,
  "a87",
  0x2772,
  "a88",
  0x2773,
  "a95",
  0x2774,
  "a96",
  0x2775,
  ".notdef",
  0x0000
 ];
});


/***/ }),
/* 38 */
/***/ ((__unused_webpack_module, __webpack_exports__, __w_pdfjs_require__) => {

__w_pdfjs_require__.r(__webpack_exports__);
/* harmony export */ __w_pdfjs_require__.d(__webpack_exports__, {
/* harmony export */   "clearUnicodeCaches": () => (/* binding */ clearUnicodeCaches),
/* harmony export */   "getCharUnicodeCategory": () => (/* binding */ getCharUnicodeCategory),
/* harmony export */   "getNormalizedUnicodes": () => (/* binding */ getNormalizedUnicodes),
/* harmony export */   "getUnicodeForGlyph": () => (/* binding */ getUnicodeForGlyph),
/* harmony export */   "getUnicodeRangeFor": () => (/* binding */ getUnicodeRangeFor),
/* harmony export */   "mapSpecialUnicodeValues": () => (/* binding */ mapSpecialUnicodeValues),
/* harmony export */   "reverseIfRtl": () => (/* binding */ reverseIfRtl)
/* harmony export */ });
/* harmony import */ var _core_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __w_pdfjs_require__(4);

const getSpecialPUASymbols = (0,_core_utils_js__WEBPACK_IMPORTED_MODULE_0__.getLookupTableFactory)(function (t) {
 t[63721] = 0x00a9;
 t[63193] = 0x00a9;
 t[63720] = 0x00ae;
 t[63194] = 0x00ae;
 t[63722] = 0x2122;
 t[63195] = 0x2122;
 t[63729] = 0x23a7;
 t[63730] = 0x23a8;
 t[63731] = 0x23a9;
 t[63740] = 0x23ab;
 t[63741] = 0x23ac;
 t[63742] = 0x23ad;
 t[63726] = 0x23a1;
 t[63727] = 0x23a2;
 t[63728] = 0x23a3;
 t[63737] = 0x23a4;
 t[63738] = 0x23a5;
 t[63739] = 0x23a6;
 t[63723] = 0x239b;
 t[63724] = 0x239c;
 t[63725] = 0x239d;
 t[63734] = 0x239e;
 t[63735] = 0x239f;
 t[63736] = 0x23a0;
});
function mapSpecialUnicodeValues(code) {
 if (code >= 0xfff0 && code <= 0xffff) {
  return 0;
 } else if (code >= 0xf600 && code <= 0xf8ff) {
  return getSpecialPUASymbols()[code] || code;
 } else if (code === 0x00ad) {
  return 0x002d;
 }
 return code;
}
function getUnicodeForGlyph(name, glyphsUnicodeMap) {
 let unicode = glyphsUnicodeMap[name];
 if (unicode !== undefined) {
  return unicode;
 }
 if (!name) {
  return -1;
 }
 if (name[0] === "u") {
  const nameLen = name.length;
  let hexStr;
  if (nameLen === 7 && name[1] === "n" && name[2] === "i") {
   hexStr = name.substring(3);
  } else if (nameLen >= 5 && nameLen <= 7) {
   hexStr = name.substring(1);
  } else {
   return -1;
  }
  if (hexStr === hexStr.toUpperCase()) {
   unicode = parseInt(hexStr, 16);
   if (unicode >= 0) {
    return unicode;
   }
  }
 }
 return -1;
}
const UnicodeRanges = [
 {
  begin: 0x0000,
  end: 0x007f
 },
 {
  begin: 0x0080,
  end: 0x00ff
 },
 {
  begin: 0x0100,
  end: 0x017f
 },
 {
  begin: 0x0180,
  end: 0x024f
 },
 {
  begin: 0x0250,
  end: 0x02af
 },
 {
  begin: 0x02b0,
  end: 0x02ff
 },
 {
  begin: 0x0300,
  end: 0x036f
 },
 {
  begin: 0x0370,
  end: 0x03ff
 },
 {
  begin: 0x2c80,
  end: 0x2cff
 },
 {
  begin: 0x0400,
  end: 0x04ff
 },
 {
  begin: 0x0530,
  end: 0x058f
 },
 {
  begin: 0x0590,
  end: 0x05ff
 },
 {
  begin: 0xa500,
  end: 0xa63f
 },
 {
  begin: 0x0600,
  end: 0x06ff
 },
 {
  begin: 0x07c0,
  end: 0x07ff
 },
 {
  begin: 0x0900,
  end: 0x097f
 },
 {
  begin: 0x0980,
  end: 0x09ff
 },
 {
  begin: 0x0a00,
  end: 0x0a7f
 },
 {
  begin: 0x0a80,
  end: 0x0aff
 },
 {
  begin: 0x0b00,
  end: 0x0b7f
 },
 {
  begin: 0x0b80,
  end: 0x0bff
 },
 {
  begin: 0x0c00,
  end: 0x0c7f
 },
 {
  begin: 0x0c80,
  end: 0x0cff
 },
 {
  begin: 0x0d00,
  end: 0x0d7f
 },
 {
  begin: 0x0e00,
  end: 0x0e7f
 },
 {
  begin: 0x0e80,
  end: 0x0eff
 },
 {
  begin: 0x10a0,
  end: 0x10ff
 },
 {
  begin: 0x1b00,
  end: 0x1b7f
 },
 {
  begin: 0x1100,
  end: 0x11ff
 },
 {
  begin: 0x1e00,
  end: 0x1eff
 },
 {
  begin: 0x1f00,
  end: 0x1fff
 },
 {
  begin: 0x2000,
  end: 0x206f
 },
 {
  begin: 0x2070,
  end: 0x209f
 },
 {
  begin: 0x20a0,
  end: 0x20cf
 },
 {
  begin: 0x20d0,
  end: 0x20ff
 },
 {
  begin: 0x2100,
  end: 0x214f
 },
 {
  begin: 0x2150,
  end: 0x218f
 },
 {
  begin: 0x2190,
  end: 0x21ff
 },
 {
  begin: 0x2200,
  end: 0x22ff
 },
 {
  begin: 0x2300,
  end: 0x23ff
 },
 {
  begin: 0x2400,
  end: 0x243f
 },
 {
  begin: 0x2440,
  end: 0x245f
 },
 {
  begin: 0x2460,
  end: 0x24ff
 },
 {
  begin: 0x2500,
  end: 0x257f
 },
 {
  begin: 0x2580,
  end: 0x259f
 },
 {
  begin: 0x25a0,
  end: 0x25ff
 },
 {
  begin: 0x2600,
  end: 0x26ff
 },
 {
  begin: 0x2700,
  end: 0x27bf
 },
 {
  begin: 0x3000,
  end: 0x303f
 },
 {
  begin: 0x3040,
  end: 0x309f
 },
 {
  begin: 0x30a0,
  end: 0x30ff
 },
 {
  begin: 0x3100,
  end: 0x312f
 },
 {
  begin: 0x3130,
  end: 0x318f
 },
 {
  begin: 0xa840,
  end: 0xa87f
 },
 {
  begin: 0x3200,
  end: 0x32ff
 },
 {
  begin: 0x3300,
  end: 0x33ff
 },
 {
  begin: 0xac00,
  end: 0xd7af
 },
 {
  begin: 0xd800,
  end: 0xdfff
 },
 {
  begin: 0x10900,
  end: 0x1091f
 },
 {
  begin: 0x4e00,
  end: 0x9fff
 },
 {
  begin: 0xe000,
  end: 0xf8ff
 },
 {
  begin: 0x31c0,
  end: 0x31ef
 },
 {
  begin: 0xfb00,
  end: 0xfb4f
 },
 {
  begin: 0xfb50,
  end: 0xfdff
 },
 {
  begin: 0xfe20,
  end: 0xfe2f
 },
 {
  begin: 0xfe10,
  end: 0xfe1f
 },
 {
  begin: 0xfe50,
  end: 0xfe6f
 },
 {
  begin: 0xfe70,
  end: 0xfeff
 },
 {
  begin: 0xff00,
  end: 0xffef
 },
 {
  begin: 0xfff0,
  end: 0xffff
 },
 {
  begin: 0x0f00,
  end: 0x0fff
 },
 {
  begin: 0x0700,
  end: 0x074f
 },
 {
  begin: 0x0780,
  end: 0x07bf
 },
 {
  begin: 0x0d80,
  end: 0x0dff
 },
 {
  begin: 0x1000,
  end: 0x109f
 },
 {
  begin: 0x1200,
  end: 0x137f
 },
 {
  begin: 0x13a0,
  end: 0x13ff
 },
 {
  begin: 0x1400,
  end: 0x167f
 },
 {
  begin: 0x1680,
  end: 0x169f
 },
 {
  begin: 0x16a0,
  end: 0x16ff
 },
 {
  begin: 0x1780,
  end: 0x17ff
 },
 {
  begin: 0x1800,
  end: 0x18af
 },
 {
  begin: 0x2800,
  end: 0x28ff
 },
 {
  begin: 0xa000,
  end: 0xa48f
 },
 {
  begin: 0x1700,
  end: 0x171f
 },
 {
  begin: 0x10300,
  end: 0x1032f
 },
 {
  begin: 0x10330,
  end: 0x1034f
 },
 {
  begin: 0x10400,
  end: 0x1044f
 },
 {
  begin: 0x1d000,
  end: 0x1d0ff
 },
 {
  begin: 0x1d400,
  end: 0x1d7ff
 },
 {
  begin: 0xff000,
  end: 0xffffd
 },
 {
  begin: 0xfe00,
  end: 0xfe0f
 },
 {
  begin: 0xe0000,
  end: 0xe007f
 },
 {
  begin: 0x1900,
  end: 0x194f
 },
 {
  begin: 0x1950,
  end: 0x197f
 },
 {
  begin: 0x1980,
  end: 0x19df
 },
 {
  begin: 0x1a00,
  end: 0x1a1f
 },
 {
  begin: 0x2c00,
  end: 0x2c5f
 },
 {
  begin: 0x2d30,
  end: 0x2d7f
 },
 {
  begin: 0x4dc0,
  end: 0x4dff
 },
 {
  begin: 0xa800,
  end: 0xa82f
 },
 {
  begin: 0x10000,
  end: 0x1007f
 },
 {
  begin: 0x10140,
  end: 0x1018f
 },
 {
  begin: 0x10380,
  end: 0x1039f
 },
 {
  begin: 0x103a0,
  end: 0x103df
 },
 {
  begin: 0x10450,
  end: 0x1047f
 },
 {
  begin: 0x10480,
  end: 0x104af
 },
 {
  begin: 0x10800,
  end: 0x1083f
 },
 {
  begin: 0x10a00,
  end: 0x10a5f
 },
 {
  begin: 0x1d300,
  end: 0x1d35f
 },
 {
  begin: 0x12000,
  end: 0x123ff
 },
 {
  begin: 0x1d360,
  end: 0x1d37f
 },
 {
  begin: 0x1b80,
  end: 0x1bbf
 },
 {
  begin: 0x1c00,
  end: 0x1c4f
 },
 {
  begin: 0x1c50,
  end: 0x1c7f
 },
 {
  begin: 0xa880,
  end: 0xa8df
 },
 {
  begin: 0xa900,
  end: 0xa92f
 },
 {
  begin: 0xa930,
  end: 0xa95f
 },
 {
  begin: 0xaa00,
  end: 0xaa5f
 },
 {
  begin: 0x10190,
  end: 0x101cf
 },
 {
  begin: 0x101d0,
  end: 0x101ff
 },
 {
  begin: 0x102a0,
  end: 0x102df
 },
 {
  begin: 0x1f030,
  end: 0x1f09f
 }
];
function getUnicodeRangeFor(value) {
 for (let i = 0, ii = UnicodeRanges.length; i < ii; i++) {
  const range = UnicodeRanges[i];
  if (value >= range.begin && value < range.end) {
   return i;
  }
 }
 return -1;
}
function isRTLRangeFor(value) {
 let range = UnicodeRanges[13];
 if (value >= range.begin && value < range.end) {
  return true;
 }
 range = UnicodeRanges[11];
 if (value >= range.begin && value < range.end) {
  return true;
 }
 return false;
}
const getNormalizedUnicodes = (0,_core_utils_js__WEBPACK_IMPORTED_MODULE_0__.getArrayLookupTableFactory)(function () {
 return [
  "\u00A8",
  "\u0020\u0308",
  "\u00AF",
  "\u0020\u0304",
  "\u00B4",
  "\u0020\u0301",
  "\u00B5",
  "\u03BC",
  "\u00B8",
  "\u0020\u0327",
  "\u0132",
  "\u0049\u004A",
  "\u0133",
  "\u0069\u006A",
  "\u013F",
  "\u004C\u00B7",
  "\u0140",
  "\u006C\u00B7",
  "\u0149",
  "\u02BC\u006E",
  "\u017F",
  "\u0073",
  "\u01C4",
  "\u0044\u017D",
  "\u01C5",
  "\u0044\u017E",
  "\u01C6",
  "\u0064\u017E",
  "\u01C7",
  "\u004C\u004A",
  "\u01C8",
  "\u004C\u006A",
  "\u01C9",
  "\u006C\u006A",
  "\u01CA",
  "\u004E\u004A",
  "\u01CB",
  "\u004E\u006A",
  "\u01CC",
  "\u006E\u006A",
  "\u01F1",
  "\u0044\u005A",
  "\u01F2",
  "\u0044\u007A",
  "\u01F3",
  "\u0064\u007A",
  "\u02D8",
  "\u0020\u0306",
  "\u02D9",
  "\u0020\u0307",
  "\u02DA",
  "\u0020\u030A",
  "\u02DB",
  "\u0020\u0328",
  "\u02DC",
  "\u0020\u0303",
  "\u02DD",
  "\u0020\u030B",
  "\u037A",
  "\u0020\u0345",
  "\u0384",
  "\u0020\u0301",
  "\u03D0",
  "\u03B2",
  "\u03D1",
  "\u03B8",
  "\u03D2",
  "\u03A5",
  "\u03D5",
  "\u03C6",
  "\u03D6",
  "\u03C0",
  "\u03F0",
  "\u03BA",
  "\u03F1",
  "\u03C1",
  "\u03F2",
  "\u03C2",
  "\u03F4",
  "\u0398",
  "\u03F5",
  "\u03B5",
  "\u03F9",
  "\u03A3",
  "\u0587",
  "\u0565\u0582",
  "\u0675",
  "\u0627\u0674",
  "\u0676",
  "\u0648\u0674",
  "\u0677",
  "\u06C7\u0674",
  "\u0678",
  "\u064A\u0674",
  "\u0E33",
  "\u0E4D\u0E32",
  "\u0EB3",
  "\u0ECD\u0EB2",
  "\u0EDC",
  "\u0EAB\u0E99",
  "\u0EDD",
  "\u0EAB\u0EA1",
  "\u0F77",
  "\u0FB2\u0F81",
  "\u0F79",
  "\u0FB3\u0F81",
  "\u1E9A",
  "\u0061\u02BE",
  "\u1FBD",
  "\u0020\u0313",
  "\u1FBF",
  "\u0020\u0313",
  "\u1FC0",
  "\u0020\u0342",
  "\u1FFE",
  "\u0020\u0314",
  "\u2002",
  "\u0020",
  "\u2003",
  "\u0020",
  "\u2004",
  "\u0020",
  "\u2005",
  "\u0020",
  "\u2006",
  "\u0020",
  "\u2008",
  "\u0020",
  "\u2009",
  "\u0020",
  "\u200A",
  "\u0020",
  "\u2017",
  "\u0020\u0333",
  "\u2024",
  "\u002E",
  "\u2025",
  "\u002E\u002E",
  "\u2026",
  "\u002E\u002E\u002E",
  "\u2033",
  "\u2032\u2032",
  "\u2034",
  "\u2032\u2032\u2032",
  "\u2036",
  "\u2035\u2035",
  "\u2037",
  "\u2035\u2035\u2035",
  "\u203C",
  "\u0021\u0021",
  "\u203E",
  "\u0020\u0305",
  "\u2047",
  "\u003F\u003F",
  "\u2048",
  "\u003F\u0021",
  "\u2049",
  "\u0021\u003F",
  "\u2057",
  "\u2032\u2032\u2032\u2032",
  "\u205F",
  "\u0020",
  "\u20A8",
  "\u0052\u0073",
  "\u2100",
  "\u0061\u002F\u0063",
  "\u2101",
  "\u0061\u002F\u0073",
  "\u2103",
  "\u00B0\u0043",
  "\u2105",
  "\u0063\u002F\u006F",
  "\u2106",
  "\u0063\u002F\u0075",
  "\u2107",
  "\u0190",
  "\u2109",
  "\u00B0\u0046",
  "\u2116",
  "\u004E\u006F",
  "\u2121",
  "\u0054\u0045\u004C",
  "\u2135",
  "\u05D0",
  "\u2136",
  "\u05D1",
  "\u2137",
  "\u05D2",
  "\u2138",
  "\u05D3",
  "\u213B",
  "\u0046\u0041\u0058",
  "\u2160",
  "\u0049",
  "\u2161",
  "\u0049\u0049",
  "\u2162",
  "\u0049\u0049\u0049",
  "\u2163",
  "\u0049\u0056",
  "\u2164",
  "\u0056",
  "\u2165",
  "\u0056\u0049",
  "\u2166",
  "\u0056\u0049\u0049",
  "\u2167",
  "\u0056\u0049\u0049\u0049",
  "\u2168",
  "\u0049\u0058",
  "\u2169",
  "\u0058",
  "\u216A",
  "\u0058\u0049",
  "\u216B",
  "\u0058\u0049\u0049",
  "\u216C",
  "\u004C",
  "\u216D",
  "\u0043",
  "\u216E",
  "\u0044",
  "\u216F",
  "\u004D",
  "\u2170",
  "\u0069",
  "\u2171",
  "\u0069\u0069",
  "\u2172",
  "\u0069\u0069\u0069",
  "\u2173",
  "\u0069\u0076",
  "\u2174",
  "\u0076",
  "\u2175",
  "\u0076\u0069",
  "\u2176",
  "\u0076\u0069\u0069",
  "\u2177",
  "\u0076\u0069\u0069\u0069",
  "\u2178",
  "\u0069\u0078",
  "\u2179",
  "\u0078",
  "\u217A",
  "\u0078\u0069",
  "\u217B",
  "\u0078\u0069\u0069",
  "\u217C",
  "\u006C",
  "\u217D",
  "\u0063",
  "\u217E",
  "\u0064",
  "\u217F",
  "\u006D",
  "\u222C",
  "\u222B\u222B",
  "\u222D",
  "\u222B\u222B\u222B",
  "\u222F",
  "\u222E\u222E",
  "\u2230",
  "\u222E\u222E\u222E",
  "\u2474",
  "\u0028\u0031\u0029",
  "\u2475",
  "\u0028\u0032\u0029",
  "\u2476",
  "\u0028\u0033\u0029",
  "\u2477",
  "\u0028\u0034\u0029",
  "\u2478",
  "\u0028\u0035\u0029",
  "\u2479",
  "\u0028\u0036\u0029",
  "\u247A",
  "\u0028\u0037\u0029",
  "\u247B",
  "\u0028\u0038\u0029",
  "\u247C",
  "\u0028\u0039\u0029",
  "\u247D",
  "\u0028\u0031\u0030\u0029",
  "\u247E",
  "\u0028\u0031\u0031\u0029",
  "\u247F",
  "\u0028\u0031\u0032\u0029",
  "\u2480",
  "\u0028\u0031\u0033\u0029",
  "\u2481",
  "\u0028\u0031\u0034\u0029",
  "\u2482",
  "\u0028\u0031\u0035\u0029",
  "\u2483",
  "\u0028\u0031\u0036\u0029",
  "\u2484",
  "\u0028\u0031\u0037\u0029",
  "\u2485",
  "\u0028\u0031\u0038\u0029",
  "\u2486",
  "\u0028\u0031\u0039\u0029",
  "\u2487",
  "\u0028\u0032\u0030\u0029",
  "\u2488",
  "\u0031\u002E",
  "\u2489",
  "\u0032\u002E",
  "\u248A",
  "\u0033\u002E",
  "\u248B",
  "\u0034\u002E",
  "\u248C",
  "\u0035\u002E",
  "\u248D",
  "\u0036\u002E",
  "\u248E",
  "\u0037\u002E",
  "\u248F",
  "\u0038\u002E",
  "\u2490",
  "\u0039\u002E",
  "\u2491",
  "\u0031\u0030\u002E",
  "\u2492",
  "\u0031\u0031\u002E",
  "\u2493",
  "\u0031\u0032\u002E",
  "\u2494",
  "\u0031\u0033\u002E",
  "\u2495",
  "\u0031\u0034\u002E",
  "\u2496",
  "\u0031\u0035\u002E",
  "\u2497",
  "\u0031\u0036\u002E",
  "\u2498",
  "\u0031\u0037\u002E",
  "\u2499",
  "\u0031\u0038\u002E",
  "\u249A",
  "\u0031\u0039\u002E",
  "\u249B",
  "\u0032\u0030\u002E",
  "\u249C",
  "\u0028\u0061\u0029",
  "\u249D",
  "\u0028\u0062\u0029",
  "\u249E",
  "\u0028\u0063\u0029",
  "\u249F",
  "\u0028\u0064\u0029",
  "\u24A0",
  "\u0028\u0065\u0029",
  "\u24A1",
  "\u0028\u0066\u0029",
  "\u24A2",
  "\u0028\u0067\u0029",
  "\u24A3",
  "\u0028\u0068\u0029",
  "\u24A4",
  "\u0028\u0069\u0029",
  "\u24A5",
  "\u0028\u006A\u0029",
  "\u24A6",
  "\u0028\u006B\u0029",
  "\u24A7",
  "\u0028\u006C\u0029",
  "\u24A8",
  "\u0028\u006D\u0029",
  "\u24A9",
  "\u0028\u006E\u0029",
  "\u24AA",
  "\u0028\u006F\u0029",
  "\u24AB",
  "\u0028\u0070\u0029",
  "\u24AC",
  "\u0028\u0071\u0029",
  "\u24AD",
  "\u0028\u0072\u0029",
  "\u24AE",
  "\u0028\u0073\u0029",
  "\u24AF",
  "\u0028\u0074\u0029",
  "\u24B0",
  "\u0028\u0075\u0029",
  "\u24B1",
  "\u0028\u0076\u0029",
  "\u24B2",
  "\u0028\u0077\u0029",
  "\u24B3",
  "\u0028\u0078\u0029",
  "\u24B4",
  "\u0028\u0079\u0029",
  "\u24B5",
  "\u0028\u007A\u0029",
  "\u2A0C",
  "\u222B\u222B\u222B\u222B",
  "\u2A74",
  "\u003A\u003A\u003D",
  "\u2A75",
  "\u003D\u003D",
  "\u2A76",
  "\u003D\u003D\u003D",
  "\u2E9F",
  "\u6BCD",
  "\u2EF3",
  "\u9F9F",
  "\u2F00",
  "\u4E00",
  "\u2F01",
  "\u4E28",
  "\u2F02",
  "\u4E36",
  "\u2F03",
  "\u4E3F",
  "\u2F04",
  "\u4E59",
  "\u2F05",
  "\u4E85",
  "\u2F06",
  "\u4E8C",
  "\u2F07",
  "\u4EA0",
  "\u2F08",
  "\u4EBA",
  "\u2F09",
  "\u513F",
  "\u2F0A",
  "\u5165",
  "\u2F0B",
  "\u516B",
  "\u2F0C",
  "\u5182",
  "\u2F0D",
  "\u5196",
  "\u2F0E",
  "\u51AB",
  "\u2F0F",
  "\u51E0",
  "\u2F10",
  "\u51F5",
  "\u2F11",
  "\u5200",
  "\u2F12",
  "\u529B",
  "\u2F13",
  "\u52F9",
  "\u2F14",
  "\u5315",
  "\u2F15",
  "\u531A",
  "\u2F16",
  "\u5338",
  "\u2F17",
  "\u5341",
  "\u2F18",
  "\u535C",
  "\u2F19",
  "\u5369",
  "\u2F1A",
  "\u5382",
  "\u2F1B",
  "\u53B6",
  "\u2F1C",
  "\u53C8",
  "\u2F1D",
  "\u53E3",
  "\u2F1E",
  "\u56D7",
  "\u2F1F",
  "\u571F",
  "\u2F20",
  "\u58EB",
  "\u2F21",
  "\u5902",
  "\u2F22",
  "\u590A",
  "\u2F23",
  "\u5915",
  "\u2F24",
  "\u5927",
  "\u2F25",
  "\u5973",
  "\u2F26",
  "\u5B50",
  "\u2F27",
  "\u5B80",
  "\u2F28",
  "\u5BF8",
  "\u2F29",
  "\u5C0F",
  "\u2F2A",
  "\u5C22",
  "\u2F2B",
  "\u5C38",
  "\u2F2C",
  "\u5C6E",
  "\u2F2D",
  "\u5C71",
  "\u2F2E",
  "\u5DDB",
  "\u2F2F",
  "\u5DE5",
  "\u2F30",
  "\u5DF1",
  "\u2F31",
  "\u5DFE",
  "\u2F32",
  "\u5E72",
  "\u2F33",
  "\u5E7A",
  "\u2F34",
  "\u5E7F",
  "\u2F35",
  "\u5EF4",
  "\u2F36",
  "\u5EFE",
  "\u2F37",
  "\u5F0B",
  "\u2F38",
  "\u5F13",
  "\u2F39",
  "\u5F50",
  "\u2F3A",
  "\u5F61",
  "\u2F3B",
  "\u5F73",
  "\u2F3C",
  "\u5FC3",
  "\u2F3D",
  "\u6208",
  "\u2F3E",
  "\u6236",
  "\u2F3F",
  "\u624B",
  "\u2F40",
  "\u652F",
  "\u2F41",
  "\u6534",
  "\u2F42",
  "\u6587",
  "\u2F43",
  "\u6597",
  "\u2F44",
  "\u65A4",
  "\u2F45",
  "\u65B9",
  "\u2F46",
  "\u65E0",
  "\u2F47",
  "\u65E5",
  "\u2F48",
  "\u66F0",
  "\u2F49",
  "\u6708",
  "\u2F4A",
  "\u6728",
  "\u2F4B",
  "\u6B20",
  "\u2F4C",
  "\u6B62",
  "\u2F4D",
  "\u6B79",
  "\u2F4E",
  "\u6BB3",
  "\u2F4F",
  "\u6BCB",
  "\u2F50",
  "\u6BD4",
  "\u2F51",
  "\u6BDB",
  "\u2F52",
  "\u6C0F",
  "\u2F53",
  "\u6C14",
  "\u2F54",
  "\u6C34",
  "\u2F55",
  "\u706B",
  "\u2F56",
  "\u722A",
  "\u2F57",
  "\u7236",
  "\u2F58",
  "\u723B",
  "\u2F59",
  "\u723F",
  "\u2F5A",
  "\u7247",
  "\u2F5B",
  "\u7259",
  "\u2F5C",
  "\u725B",
  "\u2F5D",
  "\u72AC",
  "\u2F5E",
  "\u7384",
  "\u2F5F",
  "\u7389",
  "\u2F60",
  "\u74DC",
  "\u2F61",
  "\u74E6",
  "\u2F62",
  "\u7518",
  "\u2F63",
  "\u751F",
  "\u2F64",
  "\u7528",
  "\u2F65",
  "\u7530",
  "\u2F66",
  "\u758B",
  "\u2F67",
  "\u7592",
  "\u2F68",
  "\u7676",
  "\u2F69",
  "\u767D",
  "\u2F6A",
  "\u76AE",
  "\u2F6B",
  "\u76BF",
  "\u2F6C",
  "\u76EE",
  "\u2F6D",
  "\u77DB",
  "\u2F6E",
  "\u77E2",
  "\u2F6F",
  "\u77F3",
  "\u2F70",
  "\u793A",
  "\u2F71",
  "\u79B8",
  "\u2F72",
  "\u79BE",
  "\u2F73",
  "\u7A74",
  "\u2F74",
  "\u7ACB",
  "\u2F75",
  "\u7AF9",
  "\u2F76",
  "\u7C73",
  "\u2F77",
  "\u7CF8",
  "\u2F78",
  "\u7F36",
  "\u2F79",
  "\u7F51",
  "\u2F7A",
  "\u7F8A",
  "\u2F7B",
  "\u7FBD",
  "\u2F7C",
  "\u8001",
  "\u2F7D",
  "\u800C",
  "\u2F7E",
  "\u8012",
  "\u2F7F",
  "\u8033",
  "\u2F80",
  "\u807F",
  "\u2F81",
  "\u8089",
  "\u2F82",
  "\u81E3",
  "\u2F83",
  "\u81EA",
  "\u2F84",
  "\u81F3",
  "\u2F85",
  "\u81FC",
  "\u2F86",
  "\u820C",
  "\u2F87",
  "\u821B",
  "\u2F88",
  "\u821F",
  "\u2F89",
  "\u826E",
  "\u2F8A",
  "\u8272",
  "\u2F8B",
  "\u8278",
  "\u2F8C",
  "\u864D",
  "\u2F8D",
  "\u866B",
  "\u2F8E",
  "\u8840",
  "\u2F8F",
  "\u884C",
  "\u2F90",
  "\u8863",
  "\u2F91",
  "\u897E",
  "\u2F92",
  "\u898B",
  "\u2F93",
  "\u89D2",
  "\u2F94",
  "\u8A00",
  "\u2F95",
  "\u8C37",
  "\u2F96",
  "\u8C46",
  "\u2F97",
  "\u8C55",
  "\u2F98",
  "\u8C78",
  "\u2F99",
  "\u8C9D",
  "\u2F9A",
  "\u8D64",
  "\u2F9B",
  "\u8D70",
  "\u2F9C",
  "\u8DB3",
  "\u2F9D",
  "\u8EAB",
  "\u2F9E",
  "\u8ECA",
  "\u2F9F",
  "\u8F9B",
  "\u2FA0",
  "\u8FB0",
  "\u2FA1",
  "\u8FB5",
  "\u2FA2",
  "\u9091",
  "\u2FA3",
  "\u9149",
  "\u2FA4",
  "\u91C6",
  "\u2FA5",
  "\u91CC",
  "\u2FA6",
  "\u91D1",
  "\u2FA7",
  "\u9577",
  "\u2FA8",
  "\u9580",
  "\u2FA9",
  "\u961C",
  "\u2FAA",
  "\u96B6",
  "\u2FAB",
  "\u96B9",
  "\u2FAC",
  "\u96E8",
  "\u2FAD",
  "\u9751",
  "\u2FAE",
  "\u975E",
  "\u2FAF",
  "\u9762",
  "\u2FB0",
  "\u9769",
  "\u2FB1",
  "\u97CB",
  "\u2FB2",
  "\u97ED",
  "\u2FB3",
  "\u97F3",
  "\u2FB4",
  "\u9801",
  "\u2FB5",
  "\u98A8",
  "\u2FB6",
  "\u98DB",
  "\u2FB7",
  "\u98DF",
  "\u2FB8",
  "\u9996",
  "\u2FB9",
  "\u9999",
  "\u2FBA",
  "\u99AC",
  "\u2FBB",
  "\u9AA8",
  "\u2FBC",
  "\u9AD8",
  "\u2FBD",
  "\u9ADF",
  "\u2FBE",
  "\u9B25",
  "\u2FBF",
  "\u9B2F",
  "\u2FC0",
  "\u9B32",
  "\u2FC1",
  "\u9B3C",
  "\u2FC2",
  "\u9B5A",
  "\u2FC3",
  "\u9CE5",
  "\u2FC4",
  "\u9E75",
  "\u2FC5",
  "\u9E7F",
  "\u2FC6",
  "\u9EA5",
  "\u2FC7",
  "\u9EBB",
  "\u2FC8",
  "\u9EC3",
  "\u2FC9",
  "\u9ECD",
  "\u2FCA",
  "\u9ED1",
  "\u2FCB",
  "\u9EF9",
  "\u2FCC",
  "\u9EFD",
  "\u2FCD",
  "\u9F0E",
  "\u2FCE",
  "\u9F13",
  "\u2FCF",
  "\u9F20",
  "\u2FD0",
  "\u9F3B",
  "\u2FD1",
  "\u9F4A",
  "\u2FD2",
  "\u9F52",
  "\u2FD3",
  "\u9F8D",
  "\u2FD4",
  "\u9F9C",
  "\u2FD5",
  "\u9FA0",
  "\u3036",
  "\u3012",
  "\u3038",
  "\u5341",
  "\u3039",
  "\u5344",
  "\u303A",
  "\u5345",
  "\u309B",
  "\u0020\u3099",
  "\u309C",
  "\u0020\u309A",
  "\u3131",
  "\u1100",
  "\u3132",
  "\u1101",
  "\u3133",
  "\u11AA",
  "\u3134",
  "\u1102",
  "\u3135",
  "\u11AC",
  "\u3136",
  "\u11AD",
  "\u3137",
  "\u1103",
  "\u3138",
  "\u1104",
  "\u3139",
  "\u1105",
  "\u313A",
  "\u11B0",
  "\u313B",
  "\u11B1",
  "\u313C",
  "\u11B2",
  "\u313D",
  "\u11B3",
  "\u313E",
  "\u11B4",
  "\u313F",
  "\u11B5",
  "\u3140",
  "\u111A",
  "\u3141",
  "\u1106",
  "\u3142",
  "\u1107",
  "\u3143",
  "\u1108",
  "\u3144",
  "\u1121",
  "\u3145",
  "\u1109",
  "\u3146",
  "\u110A",
  "\u3147",
  "\u110B",
  "\u3148",
  "\u110C",
  "\u3149",
  "\u110D",
  "\u314A",
  "\u110E",
  "\u314B",
  "\u110F",
  "\u314C",
  "\u1110",
  "\u314D",
  "\u1111",
  "\u314E",
  "\u1112",
  "\u314F",
  "\u1161",
  "\u3150",
  "\u1162",
  "\u3151",
  "\u1163",
  "\u3152",
  "\u1164",
  "\u3153",
  "\u1165",
  "\u3154",
  "\u1166",
  "\u3155",
  "\u1167",
  "\u3156",
  "\u1168",
  "\u3157",
  "\u1169",
  "\u3158",
  "\u116A",
  "\u3159",
  "\u116B",
  "\u315A",
  "\u116C",
  "\u315B",
  "\u116D",
  "\u315C",
  "\u116E",
  "\u315D",
  "\u116F",
  "\u315E",
  "\u1170",
  "\u315F",
  "\u1171",
  "\u3160",
  "\u1172",
  "\u3161",
  "\u1173",
  "\u3162",
  "\u1174",
  "\u3163",
  "\u1175",
  "\u3164",
  "\u1160",
  "\u3165",
  "\u1114",
  "\u3166",
  "\u1115",
  "\u3167",
  "\u11C7",
  "\u3168",
  "\u11C8",
  "\u3169",
  "\u11CC",
  "\u316A",
  "\u11CE",
  "\u316B",
  "\u11D3",
  "\u316C",
  "\u11D7",
  "\u316D",
  "\u11D9",
  "\u316E",
  "\u111C",
  "\u316F",
  "\u11DD",
  "\u3170",
  "\u11DF",
  "\u3171",
  "\u111D",
  "\u3172",
  "\u111E",
  "\u3173",
  "\u1120",
  "\u3174",
  "\u1122",
  "\u3175",
  "\u1123",
  "\u3176",
  "\u1127",
  "\u3177",
  "\u1129",
  "\u3178",
  "\u112B",
  "\u3179",
  "\u112C",
  "\u317A",
  "\u112D",
  "\u317B",
  "\u112E",
  "\u317C",
  "\u112F",
  "\u317D",
  "\u1132",
  "\u317E",
  "\u1136",
  "\u317F",
  "\u1140",
  "\u3180",
  "\u1147",
  "\u3181",
  "\u114C",
  "\u3182",
  "\u11F1",
  "\u3183",
  "\u11F2",
  "\u3184",
  "\u1157",
  "\u3185",
  "\u1158",
  "\u3186",
  "\u1159",
  "\u3187",
  "\u1184",
  "\u3188",
  "\u1185",
  "\u3189",
  "\u1188",
  "\u318A",
  "\u1191",
  "\u318B",
  "\u1192",
  "\u318C",
  "\u1194",
  "\u318D",
  "\u119E",
  "\u318E",
  "\u11A1",
  "\u3200",
  "\u0028\u1100\u0029",
  "\u3201",
  "\u0028\u1102\u0029",
  "\u3202",
  "\u0028\u1103\u0029",
  "\u3203",
  "\u0028\u1105\u0029",
  "\u3204",
  "\u0028\u1106\u0029",
  "\u3205",
  "\u0028\u1107\u0029",
  "\u3206",
  "\u0028\u1109\u0029",
  "\u3207",
  "\u0028\u110B\u0029",
  "\u3208",
  "\u0028\u110C\u0029",
  "\u3209",
  "\u0028\u110E\u0029",
  "\u320A",
  "\u0028\u110F\u0029",
  "\u320B",
  "\u0028\u1110\u0029",
  "\u320C",
  "\u0028\u1111\u0029",
  "\u320D",
  "\u0028\u1112\u0029",
  "\u320E",
  "\u0028\u1100\u1161\u0029",
  "\u320F",
  "\u0028\u1102\u1161\u0029",
  "\u3210",
  "\u0028\u1103\u1161\u0029",
  "\u3211",
  "\u0028\u1105\u1161\u0029",
  "\u3212",
  "\u0028\u1106\u1161\u0029",
  "\u3213",
  "\u0028\u1107\u1161\u0029",
  "\u3214",
  "\u0028\u1109\u1161\u0029",
  "\u3215",
  "\u0028\u110B\u1161\u0029",
  "\u3216",
  "\u0028\u110C\u1161\u0029",
  "\u3217",
  "\u0028\u110E\u1161\u0029",
  "\u3218",
  "\u0028\u110F\u1161\u0029",
  "\u3219",
  "\u0028\u1110\u1161\u0029",
  "\u321A",
  "\u0028\u1111\u1161\u0029",
  "\u321B",
  "\u0028\u1112\u1161\u0029",
  "\u321C",
  "\u0028\u110C\u116E\u0029",
  "\u321D",
  "\u0028\u110B\u1169\u110C\u1165\u11AB\u0029",
  "\u321E",
  "\u0028\u110B\u1169\u1112\u116E\u0029",
  "\u3220",
  "\u0028\u4E00\u0029",
  "\u3221",
  "\u0028\u4E8C\u0029",
  "\u3222",
  "\u0028\u4E09\u0029",
  "\u3223",
  "\u0028\u56DB\u0029",
  "\u3224",
  "\u0028\u4E94\u0029",
  "\u3225",
  "\u0028\u516D\u0029",
  "\u3226",
  "\u0028\u4E03\u0029",
  "\u3227",
  "\u0028\u516B\u0029",
  "\u3228",
  "\u0028\u4E5D\u0029",
  "\u3229",
  "\u0028\u5341\u0029",
  "\u322A",
  "\u0028\u6708\u0029",
  "\u322B",
  "\u0028\u706B\u0029",
  "\u322C",
  "\u0028\u6C34\u0029",
  "\u322D",
  "\u0028\u6728\u0029",
  "\u322E",
  "\u0028\u91D1\u0029",
  "\u322F",
  "\u0028\u571F\u0029",
  "\u3230",
  "\u0028\u65E5\u0029",
  "\u3231",
  "\u0028\u682A\u0029",
  "\u3232",
  "\u0028\u6709\u0029",
  "\u3233",
  "\u0028\u793E\u0029",
  "\u3234",
  "\u0028\u540D\u0029",
  "\u3235",
  "\u0028\u7279\u0029",
  "\u3236",
  "\u0028\u8CA1\u0029",
  "\u3237",
  "\u0028\u795D\u0029",
  "\u3238",
  "\u0028\u52B4\u0029",
  "\u3239",
  "\u0028\u4EE3\u0029",
  "\u323A",
  "\u0028\u547C\u0029",
  "\u323B",
  "\u0028\u5B66\u0029",
  "\u323C",
  "\u0028\u76E3\u0029",
  "\u323D",
  "\u0028\u4F01\u0029",
  "\u323E",
  "\u0028\u8CC7\u0029",
  "\u323F",
  "\u0028\u5354\u0029",
  "\u3240",
  "\u0028\u796D\u0029",
  "\u3241",
  "\u0028\u4F11\u0029",
  "\u3242",
  "\u0028\u81EA\u0029",
  "\u3243",
  "\u0028\u81F3\u0029",
  "\u32C0",
  "\u0031\u6708",
  "\u32C1",
  "\u0032\u6708",
  "\u32C2",
  "\u0033\u6708",
  "\u32C3",
  "\u0034\u6708",
  "\u32C4",
  "\u0035\u6708",
  "\u32C5",
  "\u0036\u6708",
  "\u32C6",
  "\u0037\u6708",
  "\u32C7",
  "\u0038\u6708",
  "\u32C8",
  "\u0039\u6708",
  "\u32C9",
  "\u0031\u0030\u6708",
  "\u32CA",
  "\u0031\u0031\u6708",
  "\u32CB",
  "\u0031\u0032\u6708",
  "\u3358",
  "\u0030\u70B9",
  "\u3359",
  "\u0031\u70B9",
  "\u335A",
  "\u0032\u70B9",
  "\u335B",
  "\u0033\u70B9",
  "\u335C",
  "\u0034\u70B9",
  "\u335D",
  "\u0035\u70B9",
  "\u335E",
  "\u0036\u70B9",
  "\u335F",
  "\u0037\u70B9",
  "\u3360",
  "\u0038\u70B9",
  "\u3361",
  "\u0039\u70B9",
  "\u3362",
  "\u0031\u0030\u70B9",
  "\u3363",
  "\u0031\u0031\u70B9",
  "\u3364",
  "\u0031\u0032\u70B9",
  "\u3365",
  "\u0031\u0033\u70B9",
  "\u3366",
  "\u0031\u0034\u70B9",
  "\u3367",
  "\u0031\u0035\u70B9",
  "\u3368",
  "\u0031\u0036\u70B9",
  "\u3369",
  "\u0031\u0037\u70B9",
  "\u336A",
  "\u0031\u0038\u70B9",
  "\u336B",
  "\u0031\u0039\u70B9",
  "\u336C",
  "\u0032\u0030\u70B9",
  "\u336D",
  "\u0032\u0031\u70B9",
  "\u336E",
  "\u0032\u0032\u70B9",
  "\u336F",
  "\u0032\u0033\u70B9",
  "\u3370",
  "\u0032\u0034\u70B9",
  "\u33E0",
  "\u0031\u65E5",
  "\u33E1",
  "\u0032\u65E5",
  "\u33E2",
  "\u0033\u65E5",
  "\u33E3",
  "\u0034\u65E5",
  "\u33E4",
  "\u0035\u65E5",
  "\u33E5",
  "\u0036\u65E5",
  "\u33E6",
  "\u0037\u65E5",
  "\u33E7",
  "\u0038\u65E5",
  "\u33E8",
  "\u0039\u65E5",
  "\u33E9",
  "\u0031\u0030\u65E5",
  "\u33EA",
  "\u0031\u0031\u65E5",
  "\u33EB",
  "\u0031\u0032\u65E5",
  "\u33EC",
  "\u0031\u0033\u65E5",
  "\u33ED",
  "\u0031\u0034\u65E5",
  "\u33EE",
  "\u0031\u0035\u65E5",
  "\u33EF",
  "\u0031\u0036\u65E5",
  "\u33F0",
  "\u0031\u0037\u65E5",
  "\u33F1",
  "\u0031\u0038\u65E5",
  "\u33F2",
  "\u0031\u0039\u65E5",
  "\u33F3",
  "\u0032\u0030\u65E5",
  "\u33F4",
  "\u0032\u0031\u65E5",
  "\u33F5",
  "\u0032\u0032\u65E5",
  "\u33F6",
  "\u0032\u0033\u65E5",
  "\u33F7",
  "\u0032\u0034\u65E5",
  "\u33F8",
  "\u0032\u0035\u65E5",
  "\u33F9",
  "\u0032\u0036\u65E5",
  "\u33FA",
  "\u0032\u0037\u65E5",
  "\u33FB",
  "\u0032\u0038\u65E5",
  "\u33FC",
  "\u0032\u0039\u65E5",
  "\u33FD",
  "\u0033\u0030\u65E5",
  "\u33FE",
  "\u0033\u0031\u65E5",
  "\uFB00",
  "\u0066\u0066",
  "\uFB01",
  "\u0066\u0069",
  "\uFB02",
  "\u0066\u006C",
  "\uFB03",
  "\u0066\u0066\u0069",
  "\uFB04",
  "\u0066\u0066\u006C",
  "\uFB05",
  "\u017F\u0074",
  "\uFB06",
  "\u0073\u0074",
  "\uFB13",
  "\u0574\u0576",
  "\uFB14",
  "\u0574\u0565",
  "\uFB15",
  "\u0574\u056B",
  "\uFB16",
  "\u057E\u0576",
  "\uFB17",
  "\u0574\u056D",
  "\uFB4F",
  "\u05D0\u05DC",
  "\uFB50",
  "\u0671",
  "\uFB51",
  "\u0671",
  "\uFB52",
  "\u067B",
  "\uFB53",
  "\u067B",
  "\uFB54",
  "\u067B",
  "\uFB55",
  "\u067B",
  "\uFB56",
  "\u067E",
  "\uFB57",
  "\u067E",
  "\uFB58",
  "\u067E",
  "\uFB59",
  "\u067E",
  "\uFB5A",
  "\u0680",
  "\uFB5B",
  "\u0680",
  "\uFB5C",
  "\u0680",
  "\uFB5D",
  "\u0680",
  "\uFB5E",
  "\u067A",
  "\uFB5F",
  "\u067A",
  "\uFB60",
  "\u067A",
  "\uFB61",
  "\u067A",
  "\uFB62",
  "\u067F",
  "\uFB63",
  "\u067F",
  "\uFB64",
  "\u067F",
  "\uFB65",
  "\u067F",
  "\uFB66",
  "\u0679",
  "\uFB67",
  "\u0679",
  "\uFB68",
  "\u0679",
  "\uFB69",
  "\u0679",
  "\uFB6A",
  "\u06A4",
  "\uFB6B",
  "\u06A4",
  "\uFB6C",
  "\u06A4",
  "\uFB6D",
  "\u06A4",
  "\uFB6E",
  "\u06A6",
  "\uFB6F",
  "\u06A6",
  "\uFB70",
  "\u06A6",
  "\uFB71",
  "\u06A6",
  "\uFB72",
  "\u0684",
  "\uFB73",
  "\u0684",
  "\uFB74",
  "\u0684",
  "\uFB75",
  "\u0684",
  "\uFB76",
  "\u0683",
  "\uFB77",
  "\u0683",
  "\uFB78",
  "\u0683",
  "\uFB79",
  "\u0683",
  "\uFB7A",
  "\u0686",
  "\uFB7B",
  "\u0686",
  "\uFB7C",
  "\u0686",
  "\uFB7D",
  "\u0686",
  "\uFB7E",
  "\u0687",
  "\uFB7F",
  "\u0687",
  "\uFB80",
  "\u0687",
  "\uFB81",
  "\u0687",
  "\uFB82",
  "\u068D",
  "\uFB83",
  "\u068D",
  "\uFB84",
  "\u068C",
  "\uFB85",
  "\u068C",
  "\uFB86",
  "\u068E",
  "\uFB87",
  "\u068E",
  "\uFB88",
  "\u0688",
  "\uFB89",
  "\u0688",
  "\uFB8A",
  "\u0698",
  "\uFB8B",
  "\u0698",
  "\uFB8C",
  "\u0691",
  "\uFB8D",
  "\u0691",
  "\uFB8E",
  "\u06A9",
  "\uFB8F",
  "\u06A9",
  "\uFB90",
  "\u06A9",
  "\uFB91",
  "\u06A9",
  "\uFB92",
  "\u06AF",
  "\uFB93",
  "\u06AF",
  "\uFB94",
  "\u06AF",
  "\uFB95",
  "\u06AF",
  "\uFB96",
  "\u06B3",
  "\uFB97",
  "\u06B3",
  "\uFB98",
  "\u06B3",
  "\uFB99",
  "\u06B3",
  "\uFB9A",
  "\u06B1",
  "\uFB9B",
  "\u06B1",
  "\uFB9C",
  "\u06B1",
  "\uFB9D",
  "\u06B1",
  "\uFB9E",
  "\u06BA",
  "\uFB9F",
  "\u06BA",
  "\uFBA0",
  "\u06BB",
  "\uFBA1",
  "\u06BB",
  "\uFBA2",
  "\u06BB",
  "\uFBA3",
  "\u06BB",
  "\uFBA4",
  "\u06C0",
  "\uFBA5",
  "\u06C0",
  "\uFBA6",
  "\u06C1",
  "\uFBA7",
  "\u06C1",
  "\uFBA8",
  "\u06C1",
  "\uFBA9",
  "\u06C1",
  "\uFBAA",
  "\u06BE",
  "\uFBAB",
  "\u06BE",
  "\uFBAC",
  "\u06BE",
  "\uFBAD",
  "\u06BE",
  "\uFBAE",
  "\u06D2",
  "\uFBAF",
  "\u06D2",
  "\uFBB0",
  "\u06D3",
  "\uFBB1",
  "\u06D3",
  "\uFBD3",
  "\u06AD",
  "\uFBD4",
  "\u06AD",
  "\uFBD5",
  "\u06AD",
  "\uFBD6",
  "\u06AD",
  "\uFBD7",
  "\u06C7",
  "\uFBD8",
  "\u06C7",
  "\uFBD9",
  "\u06C6",
  "\uFBDA",
  "\u06C6",
  "\uFBDB",
  "\u06C8",
  "\uFBDC",
  "\u06C8",
  "\uFBDD",
  "\u0677",
  "\uFBDE",
  "\u06CB",
  "\uFBDF",
  "\u06CB",
  "\uFBE0",
  "\u06C5",
  "\uFBE1",
  "\u06C5",
  "\uFBE2",
  "\u06C9",
  "\uFBE3",
  "\u06C9",
  "\uFBE4",
  "\u06D0",
  "\uFBE5",
  "\u06D0",
  "\uFBE6",
  "\u06D0",
  "\uFBE7",
  "\u06D0",
  "\uFBE8",
  "\u0649",
  "\uFBE9",
  "\u0649",
  "\uFBEA",
  "\u0626\u0627",
  "\uFBEB",
  "\u0626\u0627",
  "\uFBEC",
  "\u0626\u06D5",
  "\uFBED",
  "\u0626\u06D5",
  "\uFBEE",
  "\u0626\u0648",
  "\uFBEF",
  "\u0626\u0648",
  "\uFBF0",
  "\u0626\u06C7",
  "\uFBF1",
  "\u0626\u06C7",
  "\uFBF2",
  "\u0626\u06C6",
  "\uFBF3",
  "\u0626\u06C6",
  "\uFBF4",
  "\u0626\u06C8",
  "\uFBF5",
  "\u0626\u06C8",
  "\uFBF6",
  "\u0626\u06D0",
  "\uFBF7",
  "\u0626\u06D0",
  "\uFBF8",
  "\u0626\u06D0",
  "\uFBF9",
  "\u0626\u0649",
  "\uFBFA",
  "\u0626\u0649",
  "\uFBFB",
  "\u0626\u0649",
  "\uFBFC",
  "\u06CC",
  "\uFBFD",
  "\u06CC",
  "\uFBFE",
  "\u06CC",
  "\uFBFF",
  "\u06CC",
  "\uFC00",
  "\u0626\u062C",
  "\uFC01",
  "\u0626\u062D",
  "\uFC02",
  "\u0626\u0645",
  "\uFC03",
  "\u0626\u0649",
  "\uFC04",
  "\u0626\u064A",
  "\uFC05",
  "\u0628\u062C",
  "\uFC06",
  "\u0628\u062D",
  "\uFC07",
  "\u0628\u062E",
  "\uFC08",
  "\u0628\u0645",
  "\uFC09",
  "\u0628\u0649",
  "\uFC0A",
  "\u0628\u064A",
  "\uFC0B",
  "\u062A\u062C",
  "\uFC0C",
  "\u062A\u062D",
  "\uFC0D",
  "\u062A\u062E",
  "\uFC0E",
  "\u062A\u0645",
  "\uFC0F",
  "\u062A\u0649",
  "\uFC10",
  "\u062A\u064A",
  "\uFC11",
  "\u062B\u062C",
  "\uFC12",
  "\u062B\u0645",
  "\uFC13",
  "\u062B\u0649",
  "\uFC14",
  "\u062B\u064A",
  "\uFC15",
  "\u062C\u062D",
  "\uFC16",
  "\u062C\u0645",
  "\uFC17",
  "\u062D\u062C",
  "\uFC18",
  "\u062D\u0645",
  "\uFC19",
  "\u062E\u062C",
  "\uFC1A",
  "\u062E\u062D",
  "\uFC1B",
  "\u062E\u0645",
  "\uFC1C",
  "\u0633\u062C",
  "\uFC1D",
  "\u0633\u062D",
  "\uFC1E",
  "\u0633\u062E",
  "\uFC1F",
  "\u0633\u0645",
  "\uFC20",
  "\u0635\u062D",
  "\uFC21",
  "\u0635\u0645",
  "\uFC22",
  "\u0636\u062C",
  "\uFC23",
  "\u0636\u062D",
  "\uFC24",
  "\u0636\u062E",
  "\uFC25",
  "\u0636\u0645",
  "\uFC26",
  "\u0637\u062D",
  "\uFC27",
  "\u0637\u0645",
  "\uFC28",
  "\u0638\u0645",
  "\uFC29",
  "\u0639\u062C",
  "\uFC2A",
  "\u0639\u0645",
  "\uFC2B",
  "\u063A\u062C",
  "\uFC2C",
  "\u063A\u0645",
  "\uFC2D",
  "\u0641\u062C",
  "\uFC2E",
  "\u0641\u062D",
  "\uFC2F",
  "\u0641\u062E",
  "\uFC30",
  "\u0641\u0645",
  "\uFC31",
  "\u0641\u0649",
  "\uFC32",
  "\u0641\u064A",
  "\uFC33",
  "\u0642\u062D",
  "\uFC34",
  "\u0642\u0645",
  "\uFC35",
  "\u0642\u0649",
  "\uFC36",
  "\u0642\u064A",
  "\uFC37",
  "\u0643\u0627",
  "\uFC38",
  "\u0643\u062C",
  "\uFC39",
  "\u0643\u062D",
  "\uFC3A",
  "\u0643\u062E",
  "\uFC3B",
  "\u0643\u0644",
  "\uFC3C",
  "\u0643\u0645",
  "\uFC3D",
  "\u0643\u0649",
  "\uFC3E",
  "\u0643\u064A",
  "\uFC3F",
  "\u0644\u062C",
  "\uFC40",
  "\u0644\u062D",
  "\uFC41",
  "\u0644\u062E",
  "\uFC42",
  "\u0644\u0645",
  "\uFC43",
  "\u0644\u0649",
  "\uFC44",
  "\u0644\u064A",
  "\uFC45",
  "\u0645\u062C",
  "\uFC46",
  "\u0645\u062D",
  "\uFC47",
  "\u0645\u062E",
  "\uFC48",
  "\u0645\u0645",
  "\uFC49",
  "\u0645\u0649",
  "\uFC4A",
  "\u0645\u064A",
  "\uFC4B",
  "\u0646\u062C",
  "\uFC4C",
  "\u0646\u062D",
  "\uFC4D",
  "\u0646\u062E",
  "\uFC4E",
  "\u0646\u0645",
  "\uFC4F",
  "\u0646\u0649",
  "\uFC50",
  "\u0646\u064A",
  "\uFC51",
  "\u0647\u062C",
  "\uFC52",
  "\u0647\u0645",
  "\uFC53",
  "\u0647\u0649",
  "\uFC54",
  "\u0647\u064A",
  "\uFC55",
  "\u064A\u062C",
  "\uFC56",
  "\u064A\u062D",
  "\uFC57",
  "\u064A\u062E",
  "\uFC58",
  "\u064A\u0645",
  "\uFC59",
  "\u064A\u0649",
  "\uFC5A",
  "\u064A\u064A",
  "\uFC5B",
  "\u0630\u0670",
  "\uFC5C",
  "\u0631\u0670",
  "\uFC5D",
  "\u0649\u0670",
  "\uFC5E",
  "\u0020\u064C\u0651",
  "\uFC5F",
  "\u0020\u064D\u0651",
  "\uFC60",
  "\u0020\u064E\u0651",
  "\uFC61",
  "\u0020\u064F\u0651",
  "\uFC62",
  "\u0020\u0650\u0651",
  "\uFC63",
  "\u0020\u0651\u0670",
  "\uFC64",
  "\u0626\u0631",
  "\uFC65",
  "\u0626\u0632",
  "\uFC66",
  "\u0626\u0645",
  "\uFC67",
  "\u0626\u0646",
  "\uFC68",
  "\u0626\u0649",
  "\uFC69",
  "\u0626\u064A",
  "\uFC6A",
  "\u0628\u0631",
  "\uFC6B",
  "\u0628\u0632",
  "\uFC6C",
  "\u0628\u0645",
  "\uFC6D",
  "\u0628\u0646",
  "\uFC6E",
  "\u0628\u0649",
  "\uFC6F",
  "\u0628\u064A",
  "\uFC70",
  "\u062A\u0631",
  "\uFC71",
  "\u062A\u0632",
  "\uFC72",
  "\u062A\u0645",
  "\uFC73",
  "\u062A\u0646",
  "\uFC74",
  "\u062A\u0649",
  "\uFC75",
  "\u062A\u064A",
  "\uFC76",
  "\u062B\u0631",
  "\uFC77",
  "\u062B\u0632",
  "\uFC78",
  "\u062B\u0645",
  "\uFC79",
  "\u062B\u0646",
  "\uFC7A",
  "\u062B\u0649",
  "\uFC7B",
  "\u062B\u064A",
  "\uFC7C",
  "\u0641\u0649",
  "\uFC7D",
  "\u0641\u064A",
  "\uFC7E",
  "\u0642\u0649",
  "\uFC7F",
  "\u0642\u064A",
  "\uFC80",
  "\u0643\u0627",
  "\uFC81",
  "\u0643\u0644",
  "\uFC82",
  "\u0643\u0645",
  "\uFC83",
  "\u0643\u0649",
  "\uFC84",
  "\u0643\u064A",
  "\uFC85",
  "\u0644\u0645",
  "\uFC86",
  "\u0644\u0649",
  "\uFC87",
  "\u0644\u064A",
  "\uFC88",
  "\u0645\u0627",
  "\uFC89",
  "\u0645\u0645",
  "\uFC8A",
  "\u0646\u0631",
  "\uFC8B",
  "\u0646\u0632",
  "\uFC8C",
  "\u0646\u0645",
  "\uFC8D",
  "\u0646\u0646",
  "\uFC8E",
  "\u0646\u0649",
  "\uFC8F",
  "\u0646\u064A",
  "\uFC90",
  "\u0649\u0670",
  "\uFC91",
  "\u064A\u0631",
  "\uFC92",
  "\u064A\u0632",
  "\uFC93",
  "\u064A\u0645",
  "\uFC94",
  "\u064A\u0646",
  "\uFC95",
  "\u064A\u0649",
  "\uFC96",
  "\u064A\u064A",
  "\uFC97",
  "\u0626\u062C",
  "\uFC98",
  "\u0626\u062D",
  "\uFC99",
  "\u0626\u062E",
  "\uFC9A",
  "\u0626\u0645",
  "\uFC9B",
  "\u0626\u0647",
  "\uFC9C",
  "\u0628\u062C",
  "\uFC9D",
  "\u0628\u062D",
  "\uFC9E",
  "\u0628\u062E",
  "\uFC9F",
  "\u0628\u0645",
  "\uFCA0",
  "\u0628\u0647",
  "\uFCA1",
  "\u062A\u062C",
  "\uFCA2",
  "\u062A\u062D",
  "\uFCA3",
  "\u062A\u062E",
  "\uFCA4",
  "\u062A\u0645",
  "\uFCA5",
  "\u062A\u0647",
  "\uFCA6",
  "\u062B\u0645",
  "\uFCA7",
  "\u062C\u062D",
  "\uFCA8",
  "\u062C\u0645",
  "\uFCA9",
  "\u062D\u062C",
  "\uFCAA",
  "\u062D\u0645",
  "\uFCAB",
  "\u062E\u062C",
  "\uFCAC",
  "\u062E\u0645",
  "\uFCAD",
  "\u0633\u062C",
  "\uFCAE",
  "\u0633\u062D",
  "\uFCAF",
  "\u0633\u062E",
  "\uFCB0",
  "\u0633\u0645",
  "\uFCB1",
  "\u0635\u062D",
  "\uFCB2",
  "\u0635\u062E",
  "\uFCB3",
  "\u0635\u0645",
  "\uFCB4",
  "\u0636\u062C",
  "\uFCB5",
  "\u0636\u062D",
  "\uFCB6",
  "\u0636\u062E",
  "\uFCB7",
  "\u0636\u0645",
  "\uFCB8",
  "\u0637\u062D",
  "\uFCB9",
  "\u0638\u0645",
  "\uFCBA",
  "\u0639\u062C",
  "\uFCBB",
  "\u0639\u0645",
  "\uFCBC",
  "\u063A\u062C",
  "\uFCBD",
  "\u063A\u0645",
  "\uFCBE",
  "\u0641\u062C",
  "\uFCBF",
  "\u0641\u062D",
  "\uFCC0",
  "\u0641\u062E",
  "\uFCC1",
  "\u0641\u0645",
  "\uFCC2",
  "\u0642\u062D",
  "\uFCC3",
  "\u0642\u0645",
  "\uFCC4",
  "\u0643\u062C",
  "\uFCC5",
  "\u0643\u062D",
  "\uFCC6",
  "\u0643\u062E",
  "\uFCC7",
  "\u0643\u0644",
  "\uFCC8",
  "\u0643\u0645",
  "\uFCC9",
  "\u0644\u062C",
  "\uFCCA",
  "\u0644\u062D",
  "\uFCCB",
  "\u0644\u062E",
  "\uFCCC",
  "\u0644\u0645",
  "\uFCCD",
  "\u0644\u0647",
  "\uFCCE",
  "\u0645\u062C",
  "\uFCCF",
  "\u0645\u062D",
  "\uFCD0",
  "\u0645\u062E",
  "\uFCD1",
  "\u0645\u0645",
  "\uFCD2",
  "\u0646\u062C",
  "\uFCD3",
  "\u0646\u062D",
  "\uFCD4",
  "\u0646\u062E",
  "\uFCD5",
  "\u0646\u0645",
  "\uFCD6",
  "\u0646\u0647",
  "\uFCD7",
  "\u0647\u062C",
  "\uFCD8",
  "\u0647\u0645",
  "\uFCD9",
  "\u0647\u0670",
  "\uFCDA",
  "\u064A\u062C",
  "\uFCDB",
  "\u064A\u062D",
  "\uFCDC",
  "\u064A\u062E",
  "\uFCDD",
  "\u064A\u0645",
  "\uFCDE",
  "\u064A\u0647",
  "\uFCDF",
  "\u0626\u0645",
  "\uFCE0",
  "\u0626\u0647",
  "\uFCE1",
  "\u0628\u0645",
  "\uFCE2",
  "\u0628\u0647",
  "\uFCE3",
  "\u062A\u0645",
  "\uFCE4",
  "\u062A\u0647",
  "\uFCE5",
  "\u062B\u0645",
  "\uFCE6",
  "\u062B\u0647",
  "\uFCE7",
  "\u0633\u0645",
  "\uFCE8",
  "\u0633\u0647",
  "\uFCE9",
  "\u0634\u0645",
  "\uFCEA",
  "\u0634\u0647",
  "\uFCEB",
  "\u0643\u0644",
  "\uFCEC",
  "\u0643\u0645",
  "\uFCED",
  "\u0644\u0645",
  "\uFCEE",
  "\u0646\u0645",
  "\uFCEF",
  "\u0646\u0647",
  "\uFCF0",
  "\u064A\u0645",
  "\uFCF1",
  "\u064A\u0647",
  "\uFCF2",
  "\u0640\u064E\u0651",
  "\uFCF3",
  "\u0640\u064F\u0651",
  "\uFCF4",
  "\u0640\u0650\u0651",
  "\uFCF5",
  "\u0637\u0649",
  "\uFCF6",
  "\u0637\u064A",
  "\uFCF7",
  "\u0639\u0649",
  "\uFCF8",
  "\u0639\u064A",
  "\uFCF9",
  "\u063A\u0649",
  "\uFCFA",
  "\u063A\u064A",
  "\uFCFB",
  "\u0633\u0649",
  "\uFCFC",
  "\u0633\u064A",
  "\uFCFD",
  "\u0634\u0649",
  "\uFCFE",
  "\u0634\u064A",
  "\uFCFF",
  "\u062D\u0649",
  "\uFD00",
  "\u062D\u064A",
  "\uFD01",
  "\u062C\u0649",
  "\uFD02",
  "\u062C\u064A",
  "\uFD03",
  "\u062E\u0649",
  "\uFD04",
  "\u062E\u064A",
  "\uFD05",
  "\u0635\u0649",
  "\uFD06",
  "\u0635\u064A",
  "\uFD07",
  "\u0636\u0649",
  "\uFD08",
  "\u0636\u064A",
  "\uFD09",
  "\u0634\u062C",
  "\uFD0A",
  "\u0634\u062D",
  "\uFD0B",
  "\u0634\u062E",
  "\uFD0C",
  "\u0634\u0645",
  "\uFD0D",
  "\u0634\u0631",
  "\uFD0E",
  "\u0633\u0631",
  "\uFD0F",
  "\u0635\u0631",
  "\uFD10",
  "\u0636\u0631",
  "\uFD11",
  "\u0637\u0649",
  "\uFD12",
  "\u0637\u064A",
  "\uFD13",
  "\u0639\u0649",
  "\uFD14",
  "\u0639\u064A",
  "\uFD15",
  "\u063A\u0649",
  "\uFD16",
  "\u063A\u064A",
  "\uFD17",
  "\u0633\u0649",
  "\uFD18",
  "\u0633\u064A",
  "\uFD19",
  "\u0634\u0649",
  "\uFD1A",
  "\u0634\u064A",
  "\uFD1B",
  "\u062D\u0649",
  "\uFD1C",
  "\u062D\u064A",
  "\uFD1D",
  "\u062C\u0649",
  "\uFD1E",
  "\u062C\u064A",
  "\uFD1F",
  "\u062E\u0649",
  "\uFD20",
  "\u062E\u064A",
  "\uFD21",
  "\u0635\u0649",
  "\uFD22",
  "\u0635\u064A",
  "\uFD23",
  "\u0636\u0649",
  "\uFD24",
  "\u0636\u064A",
  "\uFD25",
  "\u0634\u062C",
  "\uFD26",
  "\u0634\u062D",
  "\uFD27",
  "\u0634\u062E",
  "\uFD28",
  "\u0634\u0645",
  "\uFD29",
  "\u0634\u0631",
  "\uFD2A",
  "\u0633\u0631",
  "\uFD2B",
  "\u0635\u0631",
  "\uFD2C",
  "\u0636\u0631",
  "\uFD2D",
  "\u0634\u062C",
  "\uFD2E",
  "\u0634\u062D",
  "\uFD2F",
  "\u0634\u062E",
  "\uFD30",
  "\u0634\u0645",
  "\uFD31",
  "\u0633\u0647",
  "\uFD32",
  "\u0634\u0647",
  "\uFD33",
  "\u0637\u0645",
  "\uFD34",
  "\u0633\u062C",
  "\uFD35",
  "\u0633\u062D",
  "\uFD36",
  "\u0633\u062E",
  "\uFD37",
  "\u0634\u062C",
  "\uFD38",
  "\u0634\u062D",
  "\uFD39",
  "\u0634\u062E",
  "\uFD3A",
  "\u0637\u0645",
  "\uFD3B",
  "\u0638\u0645",
  "\uFD3C",
  "\u0627\u064B",
  "\uFD3D",
  "\u0627\u064B",
  "\uFD50",
  "\u062A\u062C\u0645",
  "\uFD51",
  "\u062A\u062D\u062C",
  "\uFD52",
  "\u062A\u062D\u062C",
  "\uFD53",
  "\u062A\u062D\u0645",
  "\uFD54",
  "\u062A\u062E\u0645",
  "\uFD55",
  "\u062A\u0645\u062C",
  "\uFD56",
  "\u062A\u0645\u062D",
  "\uFD57",
  "\u062A\u0645\u062E",
  "\uFD58",
  "\u062C\u0645\u062D",
  "\uFD59",
  "\u062C\u0645\u062D",
  "\uFD5A",
  "\u062D\u0645\u064A",
  "\uFD5B",
  "\u062D\u0645\u0649",
  "\uFD5C",
  "\u0633\u062D\u062C",
  "\uFD5D",
  "\u0633\u062C\u062D",
  "\uFD5E",
  "\u0633\u062C\u0649",
  "\uFD5F",
  "\u0633\u0645\u062D",
  "\uFD60",
  "\u0633\u0645\u062D",
  "\uFD61",
  "\u0633\u0645\u062C",
  "\uFD62",
  "\u0633\u0645\u0645",
  "\uFD63",
  "\u0633\u0645\u0645",
  "\uFD64",
  "\u0635\u062D\u062D",
  "\uFD65",
  "\u0635\u062D\u062D",
  "\uFD66",
  "\u0635\u0645\u0645",
  "\uFD67",
  "\u0634\u062D\u0645",
  "\uFD68",
  "\u0634\u062D\u0645",
  "\uFD69",
  "\u0634\u062C\u064A",
  "\uFD6A",
  "\u0634\u0645\u062E",
  "\uFD6B",
  "\u0634\u0645\u062E",
  "\uFD6C",
  "\u0634\u0645\u0645",
  "\uFD6D",
  "\u0634\u0645\u0645",
  "\uFD6E",
  "\u0636\u062D\u0649",
  "\uFD6F",
  "\u0636\u062E\u0645",
  "\uFD70",
  "\u0636\u062E\u0645",
  "\uFD71",
  "\u0637\u0645\u062D",
  "\uFD72",
  "\u0637\u0645\u062D",
  "\uFD73",
  "\u0637\u0645\u0645",
  "\uFD74",
  "\u0637\u0645\u064A",
  "\uFD75",
  "\u0639\u062C\u0645",
  "\uFD76",
  "\u0639\u0645\u0645",
  "\uFD77",
  "\u0639\u0645\u0645",
  "\uFD78",
  "\u0639\u0645\u0649",
  "\uFD79",
  "\u063A\u0645\u0645",
  "\uFD7A",
  "\u063A\u0645\u064A",
  "\uFD7B",
  "\u063A\u0645\u0649",
  "\uFD7C",
  "\u0641\u062E\u0645",
  "\uFD7D",
  "\u0641\u062E\u0645",
  "\uFD7E",
  "\u0642\u0645\u062D",
  "\uFD7F",
  "\u0642\u0645\u0645",
  "\uFD80",
  "\u0644\u062D\u0645",
  "\uFD81",
  "\u0644\u062D\u064A",
  "\uFD82",
  "\u0644\u062D\u0649",
  "\uFD83",
  "\u0644\u062C\u062C",
  "\uFD84",
  "\u0644\u062C\u062C",
  "\uFD85",
  "\u0644\u062E\u0645",
  "\uFD86",
  "\u0644\u062E\u0645",
  "\uFD87",
  "\u0644\u0645\u062D",
  "\uFD88",
  "\u0644\u0645\u062D",
  "\uFD89",
  "\u0645\u062D\u062C",
  "\uFD8A",
  "\u0645\u062D\u0645",
  "\uFD8B",
  "\u0645\u062D\u064A",
  "\uFD8C",
  "\u0645\u062C\u062D",
  "\uFD8D",
  "\u0645\u062C\u0645",
  "\uFD8E",
  "\u0645\u062E\u062C",
  "\uFD8F",
  "\u0645\u062E\u0645",
  "\uFD92",
  "\u0645\u062C\u062E",
  "\uFD93",
  "\u0647\u0645\u062C",
  "\uFD94",
  "\u0647\u0645\u0645",
  "\uFD95",
  "\u0646\u062D\u0645",
  "\uFD96",
  "\u0646\u062D\u0649",
  "\uFD97",
  "\u0646\u062C\u0645",
  "\uFD98",
  "\u0646\u062C\u0645",
  "\uFD99",
  "\u0646\u062C\u0649",
  "\uFD9A",
  "\u0646\u0645\u064A",
  "\uFD9B",
  "\u0646\u0645\u0649",
  "\uFD9C",
  "\u064A\u0645\u0645",
  "\uFD9D",
  "\u064A\u0645\u0645",
  "\uFD9E",
  "\u0628\u062E\u064A",
  "\uFD9F",
  "\u062A\u062C\u064A",
  "\uFDA0",
  "\u062A\u062C\u0649",
  "\uFDA1",
  "\u062A\u062E\u064A",
  "\uFDA2",
  "\u062A\u062E\u0649",
  "\uFDA3",
  "\u062A\u0645\u064A",
  "\uFDA4",
  "\u062A\u0645\u0649",
  "\uFDA5",
  "\u062C\u0645\u064A",
  "\uFDA6",
  "\u062C\u062D\u0649",
  "\uFDA7",
  "\u062C\u0645\u0649",
  "\uFDA8",
  "\u0633\u062E\u0649",
  "\uFDA9",
  "\u0635\u062D\u064A",
  "\uFDAA",
  "\u0634\u062D\u064A",
  "\uFDAB",
  "\u0636\u062D\u064A",
  "\uFDAC",
  "\u0644\u062C\u064A",
  "\uFDAD",
  "\u0644\u0645\u064A",
  "\uFDAE",
  "\u064A\u062D\u064A",
  "\uFDAF",
  "\u064A\u062C\u064A",
  "\uFDB0",
  "\u064A\u0645\u064A",
  "\uFDB1",
  "\u0645\u0645\u064A",
  "\uFDB2",
  "\u0642\u0645\u064A",
  "\uFDB3",
  "\u0646\u062D\u064A",
  "\uFDB4",
  "\u0642\u0645\u062D",
  "\uFDB5",
  "\u0644\u062D\u0645",
  "\uFDB6",
  "\u0639\u0645\u064A",
  "\uFDB7",
  "\u0643\u0645\u064A",
  "\uFDB8",
  "\u0646\u062C\u062D",
  "\uFDB9",
  "\u0645\u062E\u064A",
  "\uFDBA",
  "\u0644\u062C\u0645",
  "\uFDBB",
  "\u0643\u0645\u0645",
  "\uFDBC",
  "\u0644\u062C\u0645",
  "\uFDBD",
  "\u0646\u062C\u062D",
  "\uFDBE",
  "\u062C\u062D\u064A",
  "\uFDBF",
  "\u062D\u062C\u064A",
  "\uFDC0",
  "\u0645\u062C\u064A",
  "\uFDC1",
  "\u0641\u0645\u064A",
  "\uFDC2",
  "\u0628\u062D\u064A",
  "\uFDC3",
  "\u0643\u0645\u0645",
  "\uFDC4",
  "\u0639\u062C\u0645",
  "\uFDC5",
  "\u0635\u0645\u0645",
  "\uFDC6",
  "\u0633\u062E\u064A",
  "\uFDC7",
  "\u0646\u062C\u064A",
  "\uFE49",
  "\u203E",
  "\uFE4A",
  "\u203E",
  "\uFE4B",
  "\u203E",
  "\uFE4C",
  "\u203E",
  "\uFE4D",
  "\u005F",
  "\uFE4E",
  "\u005F",
  "\uFE4F",
  "\u005F",
  "\uFE80",
  "\u0621",
  "\uFE81",
  "\u0622",
  "\uFE82",
  "\u0622",
  "\uFE83",
  "\u0623",
  "\uFE84",
  "\u0623",
  "\uFE85",
  "\u0624",
  "\uFE86",
  "\u0624",
  "\uFE87",
  "\u0625",
  "\uFE88",
  "\u0625",
  "\uFE89",
  "\u0626",
  "\uFE8A",
  "\u0626",
  "\uFE8B",
  "\u0626",
  "\uFE8C",
  "\u0626",
  "\uFE8D",
  "\u0627",
  "\uFE8E",
  "\u0627",
  "\uFE8F",
  "\u0628",
  "\uFE90",
  "\u0628",
  "\uFE91",
  "\u0628",
  "\uFE92",
  "\u0628",
  "\uFE93",
  "\u0629",
  "\uFE94",
  "\u0629",
  "\uFE95",
  "\u062A",
  "\uFE96",
  "\u062A",
  "\uFE97",
  "\u062A",
  "\uFE98",
  "\u062A",
  "\uFE99",
  "\u062B",
  "\uFE9A",
  "\u062B",
  "\uFE9B",
  "\u062B",
  "\uFE9C",
  "\u062B",
  "\uFE9D",
  "\u062C",
  "\uFE9E",
  "\u062C",
  "\uFE9F",
  "\u062C",
  "\uFEA0",
  "\u062C",
  "\uFEA1",
  "\u062D",
  "\uFEA2",
  "\u062D",
  "\uFEA3",
  "\u062D",
  "\uFEA4",
  "\u062D",
  "\uFEA5",
  "\u062E",
  "\uFEA6",
  "\u062E",
  "\uFEA7",
  "\u062E",
  "\uFEA8",
  "\u062E",
  "\uFEA9",
  "\u062F",
  "\uFEAA",
  "\u062F",
  "\uFEAB",
  "\u0630",
  "\uFEAC",
  "\u0630",
  "\uFEAD",
  "\u0631",
  "\uFEAE",
  "\u0631",
  "\uFEAF",
  "\u0632",
  "\uFEB0",
  "\u0632",
  "\uFEB1",
  "\u0633",
  "\uFEB2",
  "\u0633",
  "\uFEB3",
  "\u0633",
  "\uFEB4",
  "\u0633",
  "\uFEB5",
  "\u0634",
  "\uFEB6",
  "\u0634",
  "\uFEB7",
  "\u0634",
  "\uFEB8",
  "\u0634",
  "\uFEB9",
  "\u0635",
  "\uFEBA",
  "\u0635",
  "\uFEBB",
  "\u0635",
  "\uFEBC",
  "\u0635",
  "\uFEBD",
  "\u0636",
  "\uFEBE",
  "\u0636",
  "\uFEBF",
  "\u0636",
  "\uFEC0",
  "\u0636",
  "\uFEC1",
  "\u0637",
  "\uFEC2",
  "\u0637",
  "\uFEC3",
  "\u0637",
  "\uFEC4",
  "\u0637",
  "\uFEC5",
  "\u0638",
  "\uFEC6",
  "\u0638",
  "\uFEC7",
  "\u0638",
  "\uFEC8",
  "\u0638",
  "\uFEC9",
  "\u0639",
  "\uFECA",
  "\u0639",
  "\uFECB",
  "\u0639",
  "\uFECC",
  "\u0639",
  "\uFECD",
  "\u063A",
  "\uFECE",
  "\u063A",
  "\uFECF",
  "\u063A",
  "\uFED0",
  "\u063A",
  "\uFED1",
  "\u0641",
  "\uFED2",
  "\u0641",
  "\uFED3",
  "\u0641",
  "\uFED4",
  "\u0641",
  "\uFED5",
  "\u0642",
  "\uFED6",
  "\u0642",
  "\uFED7",
  "\u0642",
  "\uFED8",
  "\u0642",
  "\uFED9",
  "\u0643",
  "\uFEDA",
  "\u0643",
  "\uFEDB",
  "\u0643",
  "\uFEDC",
  "\u0643",
  "\uFEDD",
  "\u0644",
  "\uFEDE",
  "\u0644",
  "\uFEDF",
  "\u0644",
  "\uFEE0",
  "\u0644",
  "\uFEE1",
  "\u0645",
  "\uFEE2",
  "\u0645",
  "\uFEE3",
  "\u0645",
  "\uFEE4",
  "\u0645",
  "\uFEE5",
  "\u0646",
  "\uFEE6",
  "\u0646",
  "\uFEE7",
  "\u0646",
  "\uFEE8",
  "\u0646",
  "\uFEE9",
  "\u0647",
  "\uFEEA",
  "\u0647",
  "\uFEEB",
  "\u0647",
  "\uFEEC",
  "\u0647",
  "\uFEED",
  "\u0648",
  "\uFEEE",
  "\u0648",
  "\uFEEF",
  "\u0649",
  "\uFEF0",
  "\u0649",
  "\uFEF1",
  "\u064A",
  "\uFEF2",
  "\u064A",
  "\uFEF3",
  "\u064A",
  "\uFEF4",
  "\u064A",
  "\uFEF5",
  "\u0644\u0622",
  "\uFEF6",
  "\u0644\u0622",
  "\uFEF7",
  "\u0644\u0623",
  "\uFEF8",
  "\u0644\u0623",
  "\uFEF9",
  "\u0644\u0625",
  "\uFEFA",
  "\u0644\u0625",
  "\uFEFB",
  "\u0644\u0627",
  "\uFEFC",
  "\u0644\u0627"
 ];
});
function reverseIfRtl(chars) {
 const charsLength = chars.length;
 if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {
  return chars;
 }
 const buf = [];
 for (let ii = charsLength - 1; ii >= 0; ii--) {
  buf.push(chars[ii]);
 }
 return buf.join("");
}
const SpecialCharRegExp = new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$", "u");
const CategoryCache = new Map();
function getCharUnicodeCategory(char) {
 const cachedCategory = CategoryCache.get(char);
 if (cachedCategory) {
  return cachedCategory;
 }
 const groups = char.match(SpecialCharRegExp);
 const category = {
  isWhitespace: !!(groups && groups[1]),
  isZeroWidthDiacritic: !!(groups && groups[2]),
  isInvisibleFormatMark: !!(groups && groups[3])
 };
 CategoryCache.set(char, category);
 return category;
}
function clearUnicodeCaches() {
 CategoryCache.clear();
}


/***/ }),
/* 39 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.getSerifFonts = exports.getNonStdFontMap = exports.getGlyphMapForStandardFonts = exports.getFontNameToFileMap = void 0;
exports.getStandardFontName = getStandardFontName;
exports.getSymbolsFonts = exports.getSupplementalGlyphMapForCalibri = exports.getSupplementalGlyphMapForArialBlack = exports.getStdFontMap = void 0;
var _core_utils = __w_pdfjs_require__(4);
var _fonts_utils = __w_pdfjs_require__(36);
const getStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  t["Times-Roman"] = "Times-Roman";
  t.Helvetica = "Helvetica";
  t.Courier = "Courier";
  t.Symbol = "Symbol";
  t["Times-Bold"] = "Times-Bold";
  t["Helvetica-Bold"] = "Helvetica-Bold";
  t["Courier-Bold"] = "Courier-Bold";
  t.ZapfDingbats = "ZapfDingbats";
  t["Times-Italic"] = "Times-Italic";
  t["Helvetica-Oblique"] = "Helvetica-Oblique";
  t["Courier-Oblique"] = "Courier-Oblique";
  t["Times-BoldItalic"] = "Times-BoldItalic";
  t["Helvetica-BoldOblique"] = "Helvetica-BoldOblique";
  t["Courier-BoldOblique"] = "Courier-BoldOblique";
  t.ArialNarrow = "Helvetica";
  t["ArialNarrow-Bold"] = "Helvetica-Bold";
  t["ArialNarrow-BoldItalic"] = "Helvetica-BoldOblique";
  t["ArialNarrow-Italic"] = "Helvetica-Oblique";
  t.ArialBlack = "Helvetica";
  t["ArialBlack-Bold"] = "Helvetica-Bold";
  t["ArialBlack-BoldItalic"] = "Helvetica-BoldOblique";
  t["ArialBlack-Italic"] = "Helvetica-Oblique";
  t["Arial-Black"] = "Helvetica";
  t["Arial-Black-Bold"] = "Helvetica-Bold";
  t["Arial-Black-BoldItalic"] = "Helvetica-BoldOblique";
  t["Arial-Black-Italic"] = "Helvetica-Oblique";
  t.Arial = "Helvetica";
  t["Arial-Bold"] = "Helvetica-Bold";
  t["Arial-BoldItalic"] = "Helvetica-BoldOblique";
  t["Arial-Italic"] = "Helvetica-Oblique";
  t.ArialMT = "Helvetica";
  t["Arial-BoldItalicMT"] = "Helvetica-BoldOblique";
  t["Arial-BoldMT"] = "Helvetica-Bold";
  t["Arial-ItalicMT"] = "Helvetica-Oblique";
  t.ArialUnicodeMS = "Helvetica";
  t["ArialUnicodeMS-Bold"] = "Helvetica-Bold";
  t["ArialUnicodeMS-BoldItalic"] = "Helvetica-BoldOblique";
  t["ArialUnicodeMS-Italic"] = "Helvetica-Oblique";
  t["Courier-BoldItalic"] = "Courier-BoldOblique";
  t["Courier-Italic"] = "Courier-Oblique";
  t.CourierNew = "Courier";
  t["CourierNew-Bold"] = "Courier-Bold";
  t["CourierNew-BoldItalic"] = "Courier-BoldOblique";
  t["CourierNew-Italic"] = "Courier-Oblique";
  t["CourierNewPS-BoldItalicMT"] = "Courier-BoldOblique";
  t["CourierNewPS-BoldMT"] = "Courier-Bold";
  t["CourierNewPS-ItalicMT"] = "Courier-Oblique";
  t.CourierNewPSMT = "Courier";
  t["Helvetica-BoldItalic"] = "Helvetica-BoldOblique";
  t["Helvetica-Italic"] = "Helvetica-Oblique";
  t["Symbol-Bold"] = "Symbol";
  t["Symbol-BoldItalic"] = "Symbol";
  t["Symbol-Italic"] = "Symbol";
  t.TimesNewRoman = "Times-Roman";
  t["TimesNewRoman-Bold"] = "Times-Bold";
  t["TimesNewRoman-BoldItalic"] = "Times-BoldItalic";
  t["TimesNewRoman-Italic"] = "Times-Italic";
  t.TimesNewRomanPS = "Times-Roman";
  t["TimesNewRomanPS-Bold"] = "Times-Bold";
  t["TimesNewRomanPS-BoldItalic"] = "Times-BoldItalic";
  t["TimesNewRomanPS-BoldItalicMT"] = "Times-BoldItalic";
  t["TimesNewRomanPS-BoldMT"] = "Times-Bold";
  t["TimesNewRomanPS-Italic"] = "Times-Italic";
  t["TimesNewRomanPS-ItalicMT"] = "Times-Italic";
  t.TimesNewRomanPSMT = "Times-Roman";
  t["TimesNewRomanPSMT-Bold"] = "Times-Bold";
  t["TimesNewRomanPSMT-BoldItalic"] = "Times-BoldItalic";
  t["TimesNewRomanPSMT-Italic"] = "Times-Italic";
});
exports.getStdFontMap = getStdFontMap;
const getFontNameToFileMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  t.Courier = "FoxitFixed.pfb";
  t["Courier-Bold"] = "FoxitFixedBold.pfb";
  t["Courier-BoldOblique"] = "FoxitFixedBoldItalic.pfb";
  t["Courier-Oblique"] = "FoxitFixedItalic.pfb";
  t.Helvetica = "FoxitSans.pfb";
  t["Helvetica-Bold"] = "FoxitSansBold.pfb";
  t["Helvetica-BoldOblique"] = "FoxitSansBoldItalic.pfb";
  t["Helvetica-Oblique"] = "FoxitSansItalic.pfb";
  t["Times-Roman"] = "FoxitSerif.pfb";
  t["Times-Bold"] = "FoxitSerifBold.pfb";
  t["Times-BoldItalic"] = "FoxitSerifBoldItalic.pfb";
  t["Times-Italic"] = "FoxitSerifItalic.pfb";
  t.Symbol = "FoxitSymbol.pfb";
  t.ZapfDingbats = "FoxitDingbats.pfb";
  t["LiberationSans-Regular"] = "LiberationSans-Regular.ttf";
  t["LiberationSans-Bold"] = "LiberationSans-Bold.ttf";
  t["LiberationSans-Italic"] = "LiberationSans-Italic.ttf";
  t["LiberationSans-BoldItalic"] = "LiberationSans-BoldItalic.ttf";
});
exports.getFontNameToFileMap = getFontNameToFileMap;
const getNonStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  t.Calibri = "Helvetica";
  t["Calibri-Bold"] = "Helvetica-Bold";
  t["Calibri-BoldItalic"] = "Helvetica-BoldOblique";
  t["Calibri-Italic"] = "Helvetica-Oblique";
  t.CenturyGothic = "Helvetica";
  t["CenturyGothic-Bold"] = "Helvetica-Bold";
  t["CenturyGothic-BoldItalic"] = "Helvetica-BoldOblique";
  t["CenturyGothic-Italic"] = "Helvetica-Oblique";
  t.ComicSansMS = "Comic Sans MS";
  t["ComicSansMS-Bold"] = "Comic Sans MS-Bold";
  t["ComicSansMS-BoldItalic"] = "Comic Sans MS-BoldItalic";
  t["ComicSansMS-Italic"] = "Comic Sans MS-Italic";
  t["ItcSymbol-Bold"] = "Helvetica-Bold";
  t["ItcSymbol-BoldItalic"] = "Helvetica-BoldOblique";
  t["ItcSymbol-Book"] = "Helvetica";
  t["ItcSymbol-BookItalic"] = "Helvetica-Oblique";
  t["ItcSymbol-Medium"] = "Helvetica";
  t["ItcSymbol-MediumItalic"] = "Helvetica-Oblique";
  t.LucidaConsole = "Courier";
  t["LucidaConsole-Bold"] = "Courier-Bold";
  t["LucidaConsole-BoldItalic"] = "Courier-BoldOblique";
  t["LucidaConsole-Italic"] = "Courier-Oblique";
  t["LucidaSans-Demi"] = "Helvetica-Bold";
  t["MS-Gothic"] = "MS Gothic";
  t["MS-Gothic-Bold"] = "MS Gothic-Bold";
  t["MS-Gothic-BoldItalic"] = "MS Gothic-BoldItalic";
  t["MS-Gothic-Italic"] = "MS Gothic-Italic";
  t["MS-Mincho"] = "MS Mincho";
  t["MS-Mincho-Bold"] = "MS Mincho-Bold";
  t["MS-Mincho-BoldItalic"] = "MS Mincho-BoldItalic";
  t["MS-Mincho-Italic"] = "MS Mincho-Italic";
  t["MS-PGothic"] = "MS PGothic";
  t["MS-PGothic-Bold"] = "MS PGothic-Bold";
  t["MS-PGothic-BoldItalic"] = "MS PGothic-BoldItalic";
  t["MS-PGothic-Italic"] = "MS PGothic-Italic";
  t["MS-PMincho"] = "MS PMincho";
  t["MS-PMincho-Bold"] = "MS PMincho-Bold";
  t["MS-PMincho-BoldItalic"] = "MS PMincho-BoldItalic";
  t["MS-PMincho-Italic"] = "MS PMincho-Italic";
  t.NuptialScript = "Times-Italic";
  t.SegoeUISymbol = "Helvetica";
  t.Wingdings = "ZapfDingbats";
  t["Wingdings-Regular"] = "ZapfDingbats";
});
exports.getNonStdFontMap = getNonStdFontMap;
const getSerifFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
  t["Adobe Jenson"] = true;
  t["Adobe Text"] = true;
  t.Albertus = true;
  t.Aldus = true;
  t.Alexandria = true;
  t.Algerian = true;
  t["American Typewriter"] = true;
  t.Antiqua = true;
  t.Apex = true;
  t.Arno = true;
  t.Aster = true;
  t.Aurora = true;
  t.Baskerville = true;
  t.Bell = true;
  t.Bembo = true;
  t["Bembo Schoolbook"] = true;
  t.Benguiat = true;
  t["Berkeley Old Style"] = true;
  t["Bernhard Modern"] = true;
  t["Berthold City"] = true;
  t.Bodoni = true;
  t["Bauer Bodoni"] = true;
  t["Book Antiqua"] = true;
  t.Bookman = true;
  t["Bordeaux Roman"] = true;
  t["Californian FB"] = true;
  t.Calisto = true;
  t.Calvert = true;
  t.Capitals = true;
  t.Cambria = true;
  t.Cartier = true;
  t.Caslon = true;
  t.Catull = true;
  t.Centaur = true;
  t["Century Old Style"] = true;
  t["Century Schoolbook"] = true;
  t.Chaparral = true;
  t["Charis SIL"] = true;
  t.Cheltenham = true;
  t["Cholla Slab"] = true;
  t.Clarendon = true;
  t.Clearface = true;
  t.Cochin = true;
  t.Colonna = true;
  t["Computer Modern"] = true;
  t["Concrete Roman"] = true;
  t.Constantia = true;
  t["Cooper Black"] = true;
  t.Corona = true;
  t.Ecotype = true;
  t.Egyptienne = true;
  t.Elephant = true;
  t.Excelsior = true;
  t.Fairfield = true;
  t["FF Scala"] = true;
  t.Folkard = true;
  t.Footlight = true;
  t.FreeSerif = true;
  t["Friz Quadrata"] = true;
  t.Garamond = true;
  t.Gentium = true;
  t.Georgia = true;
  t.Gloucester = true;
  t["Goudy Old Style"] = true;
  t["Goudy Schoolbook"] = true;
  t["Goudy Pro Font"] = true;
  t.Granjon = true;
  t["Guardian Egyptian"] = true;
  t.Heather = true;
  t.Hercules = true;
  t["High Tower Text"] = true;
  t.Hiroshige = true;
  t["Hoefler Text"] = true;
  t["Humana Serif"] = true;
  t.Imprint = true;
  t["Ionic No. 5"] = true;
  t.Janson = true;
  t.Joanna = true;
  t.Korinna = true;
  t.Lexicon = true;
  t.LiberationSerif = true;
  t["Liberation Serif"] = true;
  t["Linux Libertine"] = true;
  t.Literaturnaya = true;
  t.Lucida = true;
  t["Lucida Bright"] = true;
  t.Melior = true;
  t.Memphis = true;
  t.Miller = true;
  t.Minion = true;
  t.Modern = true;
  t["Mona Lisa"] = true;
  t["Mrs Eaves"] = true;
  t["MS Serif"] = true;
  t["Museo Slab"] = true;
  t["New York"] = true;
  t["Nimbus Roman"] = true;
  t["NPS Rawlinson Roadway"] = true;
  t.NuptialScript = true;
  t.Palatino = true;
  t.Perpetua = true;
  t.Plantin = true;
  t["Plantin Schoolbook"] = true;
  t.Playbill = true;
  t["Poor Richard"] = true;
  t["Rawlinson Roadway"] = true;
  t.Renault = true;
  t.Requiem = true;
  t.Rockwell = true;
  t.Roman = true;
  t["Rotis Serif"] = true;
  t.Sabon = true;
  t.Scala = true;
  t.Seagull = true;
  t.Sistina = true;
  t.Souvenir = true;
  t.STIX = true;
  t["Stone Informal"] = true;
  t["Stone Serif"] = true;
  t.Sylfaen = true;
  t.Times = true;
  t.Trajan = true;
  t["Trinité"] = true;
  t["Trump Mediaeval"] = true;
  t.Utopia = true;
  t["Vale Type"] = true;
  t["Bitstream Vera"] = true;
  t["Vera Serif"] = true;
  t.Versailles = true;
  t.Wanted = true;
  t.Weiss = true;
  t["Wide Latin"] = true;
  t.Windsor = true;
  t.XITS = true;
});
exports.getSerifFonts = getSerifFonts;
const getSymbolsFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
  t.Dingbats = true;
  t.Symbol = true;
  t.ZapfDingbats = true;
});
exports.getSymbolsFonts = getSymbolsFonts;
const getGlyphMapForStandardFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
  t[2] = 10;
  t[3] = 32;
  t[4] = 33;
  t[5] = 34;
  t[6] = 35;
  t[7] = 36;
  t[8] = 37;
  t[9] = 38;
  t[10] = 39;
  t[11] = 40;
  t[12] = 41;
  t[13] = 42;
  t[14] = 43;
  t[15] = 44;
  t[16] = 45;
  t[17] = 46;
  t[18] = 47;
  t[19] = 48;
  t[20] = 49;
  t[21] = 50;
  t[22] = 51;
  t[23] = 52;
  t[24] = 53;
  t[25] = 54;
  t[26] = 55;
  t[27] = 56;
  t[28] = 57;
  t[29] = 58;
  t[30] = 894;
  t[31] = 60;
  t[32] = 61;
  t[33] = 62;
  t[34] = 63;
  t[35] = 64;
  t[36] = 65;
  t[37] = 66;
  t[38] = 67;
  t[39] = 68;
  t[40] = 69;
  t[41] = 70;
  t[42] = 71;
  t[43] = 72;
  t[44] = 73;
  t[45] = 74;
  t[46] = 75;
  t[47] = 76;
  t[48] = 77;
  t[49] = 78;
  t[50] = 79;
  t[51] = 80;
  t[52] = 81;
  t[53] = 82;
  t[54] = 83;
  t[55] = 84;
  t[56] = 85;
  t[57] = 86;
  t[58] = 87;
  t[59] = 88;
  t[60] = 89;
  t[61] = 90;
  t[62] = 91;
  t[63] = 92;
  t[64] = 93;
  t[65] = 94;
  t[66] = 95;
  t[67] = 96;
  t[68] = 97;
  t[69] = 98;
  t[70] = 99;
  t[71] = 100;
  t[72] = 101;
  t[73] = 102;
  t[74] = 103;
  t[75] = 104;
  t[76] = 105;
  t[77] = 106;
  t[78] = 107;
  t[79] = 108;
  t[80] = 109;
  t[81] = 110;
  t[82] = 111;
  t[83] = 112;
  t[84] = 113;
  t[85] = 114;
  t[86] = 115;
  t[87] = 116;
  t[88] = 117;
  t[89] = 118;
  t[90] = 119;
  t[91] = 120;
  t[92] = 121;
  t[93] = 122;
  t[94] = 123;
  t[95] = 124;
  t[96] = 125;
  t[97] = 126;
  t[98] = 196;
  t[99] = 197;
  t[100] = 199;
  t[101] = 201;
  t[102] = 209;
  t[103] = 214;
  t[104] = 220;
  t[105] = 225;
  t[106] = 224;
  t[107] = 226;
  t[108] = 228;
  t[109] = 227;
  t[110] = 229;
  t[111] = 231;
  t[112] = 233;
  t[113] = 232;
  t[114] = 234;
  t[115] = 235;
  t[116] = 237;
  t[117] = 236;
  t[118] = 238;
  t[119] = 239;
  t[120] = 241;
  t[121] = 243;
  t[122] = 242;
  t[123] = 244;
  t[124] = 246;
  t[125] = 245;
  t[126] = 250;
  t[127] = 249;
  t[128] = 251;
  t[129] = 252;
  t[130] = 8224;
  t[131] = 176;
  t[132] = 162;
  t[133] = 163;
  t[134] = 167;
  t[135] = 8226;
  t[136] = 182;
  t[137] = 223;
  t[138] = 174;
  t[139] = 169;
  t[140] = 8482;
  t[141] = 180;
  t[142] = 168;
  t[143] = 8800;
  t[144] = 198;
  t[145] = 216;
  t[146] = 8734;
  t[147] = 177;
  t[148] = 8804;
  t[149] = 8805;
  t[150] = 165;
  t[151] = 181;
  t[152] = 8706;
  t[153] = 8721;
  t[154] = 8719;
  t[156] = 8747;
  t[157] = 170;
  t[158] = 186;
  t[159] = 8486;
  t[160] = 230;
  t[161] = 248;
  t[162] = 191;
  t[163] = 161;
  t[164] = 172;
  t[165] = 8730;
  t[166] = 402;
  t[167] = 8776;
  t[168] = 8710;
  t[169] = 171;
  t[170] = 187;
  t[171] = 8230;
  t[179] = 8220;
  t[180] = 8221;
  t[181] = 8216;
  t[182] = 8217;
  t[200] = 193;
  t[203] = 205;
  t[207] = 211;
  t[210] = 218;
  t[223] = 711;
  t[224] = 321;
  t[225] = 322;
  t[226] = 352;
  t[227] = 353;
  t[228] = 381;
  t[229] = 382;
  t[233] = 221;
  t[234] = 253;
  t[252] = 263;
  t[253] = 268;
  t[254] = 269;
  t[258] = 258;
  t[260] = 260;
  t[261] = 261;
  t[265] = 280;
  t[266] = 281;
  t[267] = 282;
  t[268] = 283;
  t[269] = 313;
  t[275] = 323;
  t[276] = 324;
  t[278] = 328;
  t[283] = 344;
  t[284] = 345;
  t[285] = 346;
  t[286] = 347;
  t[292] = 367;
  t[295] = 377;
  t[296] = 378;
  t[298] = 380;
  t[305] = 963;
  t[306] = 964;
  t[307] = 966;
  t[308] = 8215;
  t[309] = 8252;
  t[310] = 8319;
  t[311] = 8359;
  t[312] = 8592;
  t[313] = 8593;
  t[337] = 9552;
  t[493] = 1039;
  t[494] = 1040;
  t[672] = 1488;
  t[673] = 1489;
  t[674] = 1490;
  t[675] = 1491;
  t[676] = 1492;
  t[677] = 1493;
  t[678] = 1494;
  t[679] = 1495;
  t[680] = 1496;
  t[681] = 1497;
  t[682] = 1498;
  t[683] = 1499;
  t[684] = 1500;
  t[685] = 1501;
  t[686] = 1502;
  t[687] = 1503;
  t[688] = 1504;
  t[689] = 1505;
  t[690] = 1506;
  t[691] = 1507;
  t[692] = 1508;
  t[693] = 1509;
  t[694] = 1510;
  t[695] = 1511;
  t[696] = 1512;
  t[697] = 1513;
  t[698] = 1514;
  t[705] = 1524;
  t[706] = 8362;
  t[710] = 64288;
  t[711] = 64298;
  t[759] = 1617;
  t[761] = 1776;
  t[763] = 1778;
  t[775] = 1652;
  t[777] = 1764;
  t[778] = 1780;
  t[779] = 1781;
  t[780] = 1782;
  t[782] = 771;
  t[783] = 64726;
  t[786] = 8363;
  t[788] = 8532;
  t[790] = 768;
  t[791] = 769;
  t[792] = 768;
  t[795] = 803;
  t[797] = 64336;
  t[798] = 64337;
  t[799] = 64342;
  t[800] = 64343;
  t[801] = 64344;
  t[802] = 64345;
  t[803] = 64362;
  t[804] = 64363;
  t[805] = 64364;
  t[2424] = 7821;
  t[2425] = 7822;
  t[2426] = 7823;
  t[2427] = 7824;
  t[2428] = 7825;
  t[2429] = 7826;
  t[2430] = 7827;
  t[2433] = 7682;
  t[2678] = 8045;
  t[2679] = 8046;
  t[2830] = 1552;
  t[2838] = 686;
  t[2840] = 751;
  t[2842] = 753;
  t[2843] = 754;
  t[2844] = 755;
  t[2846] = 757;
  t[2856] = 767;
  t[2857] = 848;
  t[2858] = 849;
  t[2862] = 853;
  t[2863] = 854;
  t[2864] = 855;
  t[2865] = 861;
  t[2866] = 862;
  t[2906] = 7460;
  t[2908] = 7462;
  t[2909] = 7463;
  t[2910] = 7464;
  t[2912] = 7466;
  t[2913] = 7467;
  t[2914] = 7468;
  t[2916] = 7470;
  t[2917] = 7471;
  t[2918] = 7472;
  t[2920] = 7474;
  t[2921] = 7475;
  t[2922] = 7476;
  t[2924] = 7478;
  t[2925] = 7479;
  t[2926] = 7480;
  t[2928] = 7482;
  t[2929] = 7483;
  t[2930] = 7484;
  t[2932] = 7486;
  t[2933] = 7487;
  t[2934] = 7488;
  t[2936] = 7490;
  t[2937] = 7491;
  t[2938] = 7492;
  t[2940] = 7494;
  t[2941] = 7495;
  t[2942] = 7496;
  t[2944] = 7498;
  t[2946] = 7500;
  t[2948] = 7502;
  t[2950] = 7504;
  t[2951] = 7505;
  t[2952] = 7506;
  t[2954] = 7508;
  t[2955] = 7509;
  t[2956] = 7510;
  t[2958] = 7512;
  t[2959] = 7513;
  t[2960] = 7514;
  t[2962] = 7516;
  t[2963] = 7517;
  t[2964] = 7518;
  t[2966] = 7520;
  t[2967] = 7521;
  t[2968] = 7522;
  t[2970] = 7524;
  t[2971] = 7525;
  t[2972] = 7526;
  t[2974] = 7528;
  t[2975] = 7529;
  t[2976] = 7530;
  t[2978] = 1537;
  t[2979] = 1538;
  t[2980] = 1539;
  t[2982] = 1549;
  t[2983] = 1551;
  t[2984] = 1552;
  t[2986] = 1554;
  t[2987] = 1555;
  t[2988] = 1556;
  t[2990] = 1623;
  t[2991] = 1624;
  t[2995] = 1775;
  t[2999] = 1791;
  t[3002] = 64290;
  t[3003] = 64291;
  t[3004] = 64292;
  t[3006] = 64294;
  t[3007] = 64295;
  t[3008] = 64296;
  t[3011] = 1900;
  t[3014] = 8223;
  t[3015] = 8244;
  t[3017] = 7532;
  t[3018] = 7533;
  t[3019] = 7534;
  t[3075] = 7590;
  t[3076] = 7591;
  t[3079] = 7594;
  t[3080] = 7595;
  t[3083] = 7598;
  t[3084] = 7599;
  t[3087] = 7602;
  t[3088] = 7603;
  t[3091] = 7606;
  t[3092] = 7607;
  t[3095] = 7610;
  t[3096] = 7611;
  t[3099] = 7614;
  t[3100] = 7615;
  t[3103] = 7618;
  t[3104] = 7619;
  t[3107] = 8337;
  t[3108] = 8338;
  t[3116] = 1884;
  t[3119] = 1885;
  t[3120] = 1885;
  t[3123] = 1886;
  t[3124] = 1886;
  t[3127] = 1887;
  t[3128] = 1887;
  t[3131] = 1888;
  t[3132] = 1888;
  t[3135] = 1889;
  t[3136] = 1889;
  t[3139] = 1890;
  t[3140] = 1890;
  t[3143] = 1891;
  t[3144] = 1891;
  t[3147] = 1892;
  t[3148] = 1892;
  t[3153] = 580;
  t[3154] = 581;
  t[3157] = 584;
  t[3158] = 585;
  t[3161] = 588;
  t[3162] = 589;
  t[3165] = 891;
  t[3166] = 892;
  t[3169] = 1274;
  t[3170] = 1275;
  t[3173] = 1278;
  t[3174] = 1279;
  t[3181] = 7622;
  t[3182] = 7623;
  t[3282] = 11799;
  t[3316] = 578;
  t[3379] = 42785;
  t[3393] = 1159;
  t[3416] = 8377;
});
exports.getGlyphMapForStandardFonts = getGlyphMapForStandardFonts;
const getSupplementalGlyphMapForArialBlack = (0, _core_utils.getLookupTableFactory)(function (t) {
  t[227] = 322;
  t[264] = 261;
  t[291] = 346;
});
exports.getSupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBlack;
const getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)(function (t) {
  t[1] = 32;
  t[4] = 65;
  t[5] = 192;
  t[6] = 193;
  t[9] = 196;
  t[17] = 66;
  t[18] = 67;
  t[21] = 268;
  t[24] = 68;
  t[28] = 69;
  t[29] = 200;
  t[30] = 201;
  t[32] = 282;
  t[38] = 70;
  t[39] = 71;
  t[44] = 72;
  t[47] = 73;
  t[48] = 204;
  t[49] = 205;
  t[58] = 74;
  t[60] = 75;
  t[62] = 76;
  t[68] = 77;
  t[69] = 78;
  t[75] = 79;
  t[76] = 210;
  t[80] = 214;
  t[87] = 80;
  t[89] = 81;
  t[90] = 82;
  t[92] = 344;
  t[94] = 83;
  t[97] = 352;
  t[100] = 84;
  t[104] = 85;
  t[109] = 220;
  t[115] = 86;
  t[116] = 87;
  t[121] = 88;
  t[122] = 89;
  t[124] = 221;
  t[127] = 90;
  t[129] = 381;
  t[258] = 97;
  t[259] = 224;
  t[260] = 225;
  t[263] = 228;
  t[268] = 261;
  t[271] = 98;
  t[272] = 99;
  t[273] = 263;
  t[275] = 269;
  t[282] = 100;
  t[286] = 101;
  t[287] = 232;
  t[288] = 233;
  t[290] = 283;
  t[295] = 281;
  t[296] = 102;
  t[336] = 103;
  t[346] = 104;
  t[349] = 105;
  t[350] = 236;
  t[351] = 237;
  t[361] = 106;
  t[364] = 107;
  t[367] = 108;
  t[371] = 322;
  t[373] = 109;
  t[374] = 110;
  t[381] = 111;
  t[382] = 242;
  t[383] = 243;
  t[386] = 246;
  t[393] = 112;
  t[395] = 113;
  t[396] = 114;
  t[398] = 345;
  t[400] = 115;
  t[401] = 347;
  t[403] = 353;
  t[410] = 116;
  t[437] = 117;
  t[442] = 252;
  t[448] = 118;
  t[449] = 119;
  t[454] = 120;
  t[455] = 121;
  t[457] = 253;
  t[460] = 122;
  t[462] = 382;
  t[463] = 380;
  t[853] = 44;
  t[855] = 58;
  t[856] = 46;
  t[876] = 47;
  t[878] = 45;
  t[882] = 45;
  t[894] = 40;
  t[895] = 41;
  t[896] = 91;
  t[897] = 93;
  t[923] = 64;
  t[1004] = 48;
  t[1005] = 49;
  t[1006] = 50;
  t[1007] = 51;
  t[1008] = 52;
  t[1009] = 53;
  t[1010] = 54;
  t[1011] = 55;
  t[1012] = 56;
  t[1013] = 57;
  t[1081] = 37;
  t[1085] = 43;
  t[1086] = 45;
});
exports.getSupplementalGlyphMapForCalibri = getSupplementalGlyphMapForCalibri;
function getStandardFontName(name) {
  const fontName = (0, _fonts_utils.normalizeFontName)(name);
  const stdFontMap = getStdFontMap();
  return stdFontMap[fontName];
}

/***/ }),
/* 40 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ToUnicodeMap = exports.IdentityToUnicodeMap = void 0;
var _util = __w_pdfjs_require__(2);
class ToUnicodeMap {
  constructor(cmap = []) {
    this._map = cmap;
  }
  get length() {
    return this._map.length;
  }
  forEach(callback) {
    for (const charCode in this._map) {
      callback(charCode, this._map[charCode].charCodeAt(0));
    }
  }
  has(i) {
    return this._map[i] !== undefined;
  }
  get(i) {
    return this._map[i];
  }
  charCodeOf(value) {
    const map = this._map;
    if (map.length <= 0x10000) {
      return map.indexOf(value);
    }
    for (const charCode in map) {
      if (map[charCode] === value) {
        return charCode | 0;
      }
    }
    return -1;
  }
  amend(map) {
    for (const charCode in map) {
      this._map[charCode] = map[charCode];
    }
  }
}
exports.ToUnicodeMap = ToUnicodeMap;
class IdentityToUnicodeMap {
  constructor(firstChar, lastChar) {
    this.firstChar = firstChar;
    this.lastChar = lastChar;
  }
  get length() {
    return this.lastChar + 1 - this.firstChar;
  }
  forEach(callback) {
    for (let i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
      callback(i, i);
    }
  }
  has(i) {
    return this.firstChar <= i && i <= this.lastChar;
  }
  get(i) {
    if (this.firstChar <= i && i <= this.lastChar) {
      return String.fromCharCode(i);
    }
    return undefined;
  }
  charCodeOf(v) {
    return Number.isInteger(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
  }
  amend(map) {
    (0, _util.unreachable)("Should not call amend()");
  }
}
exports.IdentityToUnicodeMap = IdentityToUnicodeMap;

/***/ }),
/* 41 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CFFFont = void 0;
var _cff_parser = __w_pdfjs_require__(33);
var _fonts_utils = __w_pdfjs_require__(36);
var _util = __w_pdfjs_require__(2);
class CFFFont {
  constructor(file, properties) {
    this.properties = properties;
    const parser = new _cff_parser.CFFParser(file, properties, _fonts_utils.SEAC_ANALYSIS_ENABLED);
    this.cff = parser.parse();
    this.cff.duplicateFirstGlyph();
    const compiler = new _cff_parser.CFFCompiler(this.cff);
    this.seacs = this.cff.seacs;
    try {
      this.data = compiler.compile();
    } catch (e) {
      (0, _util.warn)("Failed to compile font " + properties.loadedName);
      this.data = file;
    }
    this._createBuiltInEncoding();
  }
  get numGlyphs() {
    return this.cff.charStrings.count;
  }
  getCharset() {
    return this.cff.charset.charset;
  }
  getGlyphMapping() {
    const cff = this.cff;
    const properties = this.properties;
    const {
      cidToGidMap,
      cMap
    } = properties;
    const charsets = cff.charset.charset;
    let charCodeToGlyphId;
    let glyphId;
    if (properties.composite) {
      let invCidToGidMap;
      if (cidToGidMap && cidToGidMap.length > 0) {
        invCidToGidMap = Object.create(null);
        for (let i = 0, ii = cidToGidMap.length; i < ii; i++) {
          const gid = cidToGidMap[i];
          if (gid !== undefined) {
            invCidToGidMap[gid] = i;
          }
        }
      }
      charCodeToGlyphId = Object.create(null);
      let charCode;
      if (cff.isCIDFont) {
        for (glyphId = 0; glyphId < charsets.length; glyphId++) {
          const cid = charsets[glyphId];
          charCode = cMap.charCodeOf(cid);
          if (invCidToGidMap && invCidToGidMap[charCode] !== undefined) {
            charCode = invCidToGidMap[charCode];
          }
          charCodeToGlyphId[charCode] = glyphId;
        }
      } else {
        for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
          charCode = cMap.charCodeOf(glyphId);
          charCodeToGlyphId[charCode] = glyphId;
        }
      }
      return charCodeToGlyphId;
    }
    let encoding = cff.encoding ? cff.encoding.encoding : null;
    if (properties.isInternalFont) {
      encoding = properties.defaultEncoding;
    }
    charCodeToGlyphId = (0, _fonts_utils.type1FontGlyphMapping)(properties, encoding, charsets);
    return charCodeToGlyphId;
  }
  hasGlyphId(id) {
    return this.cff.hasGlyphId(id);
  }
  _createBuiltInEncoding() {
    const {
      charset,
      encoding
    } = this.cff;
    if (!charset || !encoding) {
      return;
    }
    const charsets = charset.charset,
      encodings = encoding.encoding;
    const map = [];
    for (const charCode in encodings) {
      const glyphId = encodings[charCode];
      if (glyphId >= 0) {
        const glyphName = charsets[glyphId];
        if (glyphName) {
          map[charCode] = glyphName;
        }
      }
    }
    if (map.length > 0) {
      this.properties.builtInEncoding = map;
    }
  }
}
exports.CFFFont = CFFFont;

/***/ }),
/* 42 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FontRendererFactory = void 0;
var _util = __w_pdfjs_require__(2);
var _cff_parser = __w_pdfjs_require__(33);
var _glyphlist = __w_pdfjs_require__(37);
var _encodings = __w_pdfjs_require__(35);
var _stream = __w_pdfjs_require__(8);
function getUint32(data, offset) {
  return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
}
function getUint16(data, offset) {
  return data[offset] << 8 | data[offset + 1];
}
function getInt16(data, offset) {
  return (data[offset] << 24 | data[offset + 1] << 16) >> 16;
}
function getInt8(data, offset) {
  return data[offset] << 24 >> 24;
}
function getFloat214(data, offset) {
  return getInt16(data, offset) / 16384;
}
function getSubroutineBias(subrs) {
  const numSubrs = subrs.length;
  let bias = 32768;
  if (numSubrs < 1240) {
    bias = 107;
  } else if (numSubrs < 33900) {
    bias = 1131;
  }
  return bias;
}
function parseCmap(data, start, end) {
  const offset = getUint16(data, start + 2) === 1 ? getUint32(data, start + 8) : getUint32(data, start + 16);
  const format = getUint16(data, start + offset);
  let ranges, p, i;
  if (format === 4) {
    getUint16(data, start + offset + 2);
    const segCount = getUint16(data, start + offset + 6) >> 1;
    p = start + offset + 14;
    ranges = [];
    for (i = 0; i < segCount; i++, p += 2) {
      ranges[i] = {
        end: getUint16(data, p)
      };
    }
    p += 2;
    for (i = 0; i < segCount; i++, p += 2) {
      ranges[i].start = getUint16(data, p);
    }
    for (i = 0; i < segCount; i++, p += 2) {
      ranges[i].idDelta = getUint16(data, p);
    }
    for (i = 0; i < segCount; i++, p += 2) {
      let idOffset = getUint16(data, p);
      if (idOffset === 0) {
        continue;
      }
      ranges[i].ids = [];
      for (let j = 0, jj = ranges[i].end - ranges[i].start + 1; j < jj; j++) {
        ranges[i].ids[j] = getUint16(data, p + idOffset);
        idOffset += 2;
      }
    }
    return ranges;
  } else if (format === 12) {
    const groups = getUint32(data, start + offset + 12);
    p = start + offset + 16;
    ranges = [];
    for (i = 0; i < groups; i++) {
      start = getUint32(data, p);
      ranges.push({
        start,
        end: getUint32(data, p + 4),
        idDelta: getUint32(data, p + 8) - start
      });
      p += 12;
    }
    return ranges;
  }
  throw new _util.FormatError(`unsupported cmap: ${format}`);
}
function parseCff(data, start, end, seacAnalysisEnabled) {
  const properties = {};
  const parser = new _cff_parser.CFFParser(new _stream.Stream(data, start, end - start), properties, seacAnalysisEnabled);
  const cff = parser.parse();
  return {
    glyphs: cff.charStrings.objects,
    subrs: cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex && cff.topDict.privateDict.subrsIndex.objects,
    gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects,
    isCFFCIDFont: cff.isCIDFont,
    fdSelect: cff.fdSelect,
    fdArray: cff.fdArray
  };
}
function parseGlyfTable(glyf, loca, isGlyphLocationsLong) {
  let itemSize, itemDecode;
  if (isGlyphLocationsLong) {
    itemSize = 4;
    itemDecode = getUint32;
  } else {
    itemSize = 2;
    itemDecode = (data, offset) => 2 * getUint16(data, offset);
  }
  const glyphs = [];
  let startOffset = itemDecode(loca, 0);
  for (let j = itemSize; j < loca.length; j += itemSize) {
    const endOffset = itemDecode(loca, j);
    glyphs.push(glyf.subarray(startOffset, endOffset));
    startOffset = endOffset;
  }
  return glyphs;
}
function lookupCmap(ranges, unicode) {
  const code = unicode.codePointAt(0);
  let gid = 0,
    l = 0,
    r = ranges.length - 1;
  while (l < r) {
    const c = l + r + 1 >> 1;
    if (code < ranges[c].start) {
      r = c - 1;
    } else {
      l = c;
    }
  }
  if (ranges[l].start <= code && code <= ranges[l].end) {
    gid = ranges[l].idDelta + (ranges[l].ids ? ranges[l].ids[code - ranges[l].start] : code) & 0xffff;
  }
  return {
    charCode: code,
    glyphId: gid
  };
}
function compileGlyf(code, cmds, font) {
  function moveTo(x, y) {
    cmds.push({
      cmd: "moveTo",
      args: [x, y]
    });
  }
  function lineTo(x, y) {
    cmds.push({
      cmd: "lineTo",
      args: [x, y]
    });
  }
  function quadraticCurveTo(xa, ya, x, y) {
    cmds.push({
      cmd: "quadraticCurveTo",
      args: [xa, ya, x, y]
    });
  }
  let i = 0;
  const numberOfContours = getInt16(code, i);
  let flags;
  let x = 0,
    y = 0;
  i += 10;
  if (numberOfContours < 0) {
    do {
      flags = getUint16(code, i);
      const glyphIndex = getUint16(code, i + 2);
      i += 4;
      let arg1, arg2;
      if (flags & 0x01) {
        if (flags & 0x02) {
          arg1 = getInt16(code, i);
          arg2 = getInt16(code, i + 2);
        } else {
          arg1 = getUint16(code, i);
          arg2 = getUint16(code, i + 2);
        }
        i += 4;
      } else {
        if (flags & 0x02) {
          arg1 = getInt8(code, i++);
          arg2 = getInt8(code, i++);
        } else {
          arg1 = code[i++];
          arg2 = code[i++];
        }
      }
      if (flags & 0x02) {
        x = arg1;
        y = arg2;
      } else {
        x = 0;
        y = 0;
      }
      let scaleX = 1,
        scaleY = 1,
        scale01 = 0,
        scale10 = 0;
      if (flags & 0x08) {
        scaleX = scaleY = getFloat214(code, i);
        i += 2;
      } else if (flags & 0x40) {
        scaleX = getFloat214(code, i);
        scaleY = getFloat214(code, i + 2);
        i += 4;
      } else if (flags & 0x80) {
        scaleX = getFloat214(code, i);
        scale01 = getFloat214(code, i + 2);
        scale10 = getFloat214(code, i + 4);
        scaleY = getFloat214(code, i + 6);
        i += 8;
      }
      const subglyph = font.glyphs[glyphIndex];
      if (subglyph) {
        cmds.push({
          cmd: "save"
        }, {
          cmd: "transform",
          args: [scaleX, scale01, scale10, scaleY, x, y]
        });
        if (!(flags & 0x02)) {}
        compileGlyf(subglyph, cmds, font);
        cmds.push({
          cmd: "restore"
        });
      }
    } while (flags & 0x20);
  } else {
    const endPtsOfContours = [];
    let j, jj;
    for (j = 0; j < numberOfContours; j++) {
      endPtsOfContours.push(getUint16(code, i));
      i += 2;
    }
    const instructionLength = getUint16(code, i);
    i += 2 + instructionLength;
    const numberOfPoints = endPtsOfContours.at(-1) + 1;
    const points = [];
    while (points.length < numberOfPoints) {
      flags = code[i++];
      let repeat = 1;
      if (flags & 0x08) {
        repeat += code[i++];
      }
      while (repeat-- > 0) {
        points.push({
          flags
        });
      }
    }
    for (j = 0; j < numberOfPoints; j++) {
      switch (points[j].flags & 0x12) {
        case 0x00:
          x += getInt16(code, i);
          i += 2;
          break;
        case 0x02:
          x -= code[i++];
          break;
        case 0x12:
          x += code[i++];
          break;
      }
      points[j].x = x;
    }
    for (j = 0; j < numberOfPoints; j++) {
      switch (points[j].flags & 0x24) {
        case 0x00:
          y += getInt16(code, i);
          i += 2;
          break;
        case 0x04:
          y -= code[i++];
          break;
        case 0x24:
          y += code[i++];
          break;
      }
      points[j].y = y;
    }
    let startPoint = 0;
    for (i = 0; i < numberOfContours; i++) {
      const endPoint = endPtsOfContours[i];
      const contour = points.slice(startPoint, endPoint + 1);
      if (contour[0].flags & 1) {
        contour.push(contour[0]);
      } else if (contour.at(-1).flags & 1) {
        contour.unshift(contour.at(-1));
      } else {
        const p = {
          flags: 1,
          x: (contour[0].x + contour.at(-1).x) / 2,
          y: (contour[0].y + contour.at(-1).y) / 2
        };
        contour.unshift(p);
        contour.push(p);
      }
      moveTo(contour[0].x, contour[0].y);
      for (j = 1, jj = contour.length; j < jj; j++) {
        if (contour[j].flags & 1) {
          lineTo(contour[j].x, contour[j].y);
        } else if (contour[j + 1].flags & 1) {
          quadraticCurveTo(contour[j].x, contour[j].y, contour[j + 1].x, contour[j + 1].y);
          j++;
        } else {
          quadraticCurveTo(contour[j].x, contour[j].y, (contour[j].x + contour[j + 1].x) / 2, (contour[j].y + contour[j + 1].y) / 2);
        }
      }
      startPoint = endPoint + 1;
    }
  }
}
function compileCharString(charStringCode, cmds, font, glyphId) {
  function moveTo(x, y) {
    cmds.push({
      cmd: "moveTo",
      args: [x, y]
    });
  }
  function lineTo(x, y) {
    cmds.push({
      cmd: "lineTo",
      args: [x, y]
    });
  }
  function bezierCurveTo(x1, y1, x2, y2, x, y) {
    cmds.push({
      cmd: "bezierCurveTo",
      args: [x1, y1, x2, y2, x, y]
    });
  }
  const stack = [];
  let x = 0,
    y = 0;
  let stems = 0;
  function parse(code) {
    let i = 0;
    while (i < code.length) {
      let stackClean = false;
      let v = code[i++];
      let xa, xb, ya, yb, y1, y2, y3, n, subrCode;
      switch (v) {
        case 1:
          stems += stack.length >> 1;
          stackClean = true;
          break;
        case 3:
          stems += stack.length >> 1;
          stackClean = true;
          break;
        case 4:
          y += stack.pop();
          moveTo(x, y);
          stackClean = true;
          break;
        case 5:
          while (stack.length > 0) {
            x += stack.shift();
            y += stack.shift();
            lineTo(x, y);
          }
          break;
        case 6:
          while (stack.length > 0) {
            x += stack.shift();
            lineTo(x, y);
            if (stack.length === 0) {
              break;
            }
            y += stack.shift();
            lineTo(x, y);
          }
          break;
        case 7:
          while (stack.length > 0) {
            y += stack.shift();
            lineTo(x, y);
            if (stack.length === 0) {
              break;
            }
            x += stack.shift();
            lineTo(x, y);
          }
          break;
        case 8:
          while (stack.length > 0) {
            xa = x + stack.shift();
            ya = y + stack.shift();
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb + stack.shift();
            y = yb + stack.shift();
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          break;
        case 10:
          n = stack.pop();
          subrCode = null;
          if (font.isCFFCIDFont) {
            const fdIndex = font.fdSelect.getFDIndex(glyphId);
            if (fdIndex >= 0 && fdIndex < font.fdArray.length) {
              const fontDict = font.fdArray[fdIndex];
              let subrs;
              if (fontDict.privateDict && fontDict.privateDict.subrsIndex) {
                subrs = fontDict.privateDict.subrsIndex.objects;
              }
              if (subrs) {
                n += getSubroutineBias(subrs);
                subrCode = subrs[n];
              }
            } else {
              (0, _util.warn)("Invalid fd index for glyph index.");
            }
          } else {
            subrCode = font.subrs[n + font.subrsBias];
          }
          if (subrCode) {
            parse(subrCode);
          }
          break;
        case 11:
          return;
        case 12:
          v = code[i++];
          switch (v) {
            case 34:
              xa = x + stack.shift();
              xb = xa + stack.shift();
              y1 = y + stack.shift();
              x = xb + stack.shift();
              bezierCurveTo(xa, y, xb, y1, x, y1);
              xa = x + stack.shift();
              xb = xa + stack.shift();
              x = xb + stack.shift();
              bezierCurveTo(xa, y1, xb, y, x, y);
              break;
            case 35:
              xa = x + stack.shift();
              ya = y + stack.shift();
              xb = xa + stack.shift();
              yb = ya + stack.shift();
              x = xb + stack.shift();
              y = yb + stack.shift();
              bezierCurveTo(xa, ya, xb, yb, x, y);
              xa = x + stack.shift();
              ya = y + stack.shift();
              xb = xa + stack.shift();
              yb = ya + stack.shift();
              x = xb + stack.shift();
              y = yb + stack.shift();
              bezierCurveTo(xa, ya, xb, yb, x, y);
              stack.pop();
              break;
            case 36:
              xa = x + stack.shift();
              y1 = y + stack.shift();
              xb = xa + stack.shift();
              y2 = y1 + stack.shift();
              x = xb + stack.shift();
              bezierCurveTo(xa, y1, xb, y2, x, y2);
              xa = x + stack.shift();
              xb = xa + stack.shift();
              y3 = y2 + stack.shift();
              x = xb + stack.shift();
              bezierCurveTo(xa, y2, xb, y3, x, y);
              break;
            case 37:
              const x0 = x,
                y0 = y;
              xa = x + stack.shift();
              ya = y + stack.shift();
              xb = xa + stack.shift();
              yb = ya + stack.shift();
              x = xb + stack.shift();
              y = yb + stack.shift();
              bezierCurveTo(xa, ya, xb, yb, x, y);
              xa = x + stack.shift();
              ya = y + stack.shift();
              xb = xa + stack.shift();
              yb = ya + stack.shift();
              x = xb;
              y = yb;
              if (Math.abs(x - x0) > Math.abs(y - y0)) {
                x += stack.shift();
              } else {
                y += stack.shift();
              }
              bezierCurveTo(xa, ya, xb, yb, x, y);
              break;
            default:
              throw new _util.FormatError(`unknown operator: 12 ${v}`);
          }
          break;
        case 14:
          if (stack.length >= 4) {
            const achar = stack.pop();
            const bchar = stack.pop();
            y = stack.pop();
            x = stack.pop();
            cmds.push({
              cmd: "save"
            }, {
              cmd: "translate",
              args: [x, y]
            });
            let cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[_encodings.StandardEncoding[achar]]));
            compileCharString(font.glyphs[cmap.glyphId], cmds, font, cmap.glyphId);
            cmds.push({
              cmd: "restore"
            });
            cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[_encodings.StandardEncoding[bchar]]));
            compileCharString(font.glyphs[cmap.glyphId], cmds, font, cmap.glyphId);
          }
          return;
        case 18:
          stems += stack.length >> 1;
          stackClean = true;
          break;
        case 19:
          stems += stack.length >> 1;
          i += stems + 7 >> 3;
          stackClean = true;
          break;
        case 20:
          stems += stack.length >> 1;
          i += stems + 7 >> 3;
          stackClean = true;
          break;
        case 21:
          y += stack.pop();
          x += stack.pop();
          moveTo(x, y);
          stackClean = true;
          break;
        case 22:
          x += stack.pop();
          moveTo(x, y);
          stackClean = true;
          break;
        case 23:
          stems += stack.length >> 1;
          stackClean = true;
          break;
        case 24:
          while (stack.length > 2) {
            xa = x + stack.shift();
            ya = y + stack.shift();
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb + stack.shift();
            y = yb + stack.shift();
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          x += stack.shift();
          y += stack.shift();
          lineTo(x, y);
          break;
        case 25:
          while (stack.length > 6) {
            x += stack.shift();
            y += stack.shift();
            lineTo(x, y);
          }
          xa = x + stack.shift();
          ya = y + stack.shift();
          xb = xa + stack.shift();
          yb = ya + stack.shift();
          x = xb + stack.shift();
          y = yb + stack.shift();
          bezierCurveTo(xa, ya, xb, yb, x, y);
          break;
        case 26:
          if (stack.length % 2) {
            x += stack.shift();
          }
          while (stack.length > 0) {
            xa = x;
            ya = y + stack.shift();
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb;
            y = yb + stack.shift();
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          break;
        case 27:
          if (stack.length % 2) {
            y += stack.shift();
          }
          while (stack.length > 0) {
            xa = x + stack.shift();
            ya = y;
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb + stack.shift();
            y = yb;
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          break;
        case 28:
          stack.push((code[i] << 24 | code[i + 1] << 16) >> 16);
          i += 2;
          break;
        case 29:
          n = stack.pop() + font.gsubrsBias;
          subrCode = font.gsubrs[n];
          if (subrCode) {
            parse(subrCode);
          }
          break;
        case 30:
          while (stack.length > 0) {
            xa = x;
            ya = y + stack.shift();
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb + stack.shift();
            y = yb + (stack.length === 1 ? stack.shift() : 0);
            bezierCurveTo(xa, ya, xb, yb, x, y);
            if (stack.length === 0) {
              break;
            }
            xa = x + stack.shift();
            ya = y;
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            y = yb + stack.shift();
            x = xb + (stack.length === 1 ? stack.shift() : 0);
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          break;
        case 31:
          while (stack.length > 0) {
            xa = x + stack.shift();
            ya = y;
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            y = yb + stack.shift();
            x = xb + (stack.length === 1 ? stack.shift() : 0);
            bezierCurveTo(xa, ya, xb, yb, x, y);
            if (stack.length === 0) {
              break;
            }
            xa = x;
            ya = y + stack.shift();
            xb = xa + stack.shift();
            yb = ya + stack.shift();
            x = xb + stack.shift();
            y = yb + (stack.length === 1 ? stack.shift() : 0);
            bezierCurveTo(xa, ya, xb, yb, x, y);
          }
          break;
        default:
          if (v < 32) {
            throw new _util.FormatError(`unknown operator: ${v}`);
          }
          if (v < 247) {
            stack.push(v - 139);
          } else if (v < 251) {
            stack.push((v - 247) * 256 + code[i++] + 108);
          } else if (v < 255) {
            stack.push(-(v - 251) * 256 - code[i++] - 108);
          } else {
            stack.push((code[i] << 24 | code[i + 1] << 16 | code[i + 2] << 8 | code[i + 3]) / 65536);
            i += 4;
          }
          break;
      }
      if (stackClean) {
        stack.length = 0;
      }
    }
  }
  parse(charStringCode);
}
const NOOP = [];
class CompiledFont {
  constructor(fontMatrix) {
    if (this.constructor === CompiledFont) {
      (0, _util.unreachable)("Cannot initialize CompiledFont.");
    }
    this.fontMatrix = fontMatrix;
    this.compiledGlyphs = Object.create(null);
    this.compiledCharCodeToGlyphId = Object.create(null);
  }
  getPathJs(unicode) {
    const {
      charCode,
      glyphId
    } = lookupCmap(this.cmap, unicode);
    let fn = this.compiledGlyphs[glyphId];
    if (!fn) {
      try {
        fn = this.compileGlyph(this.glyphs[glyphId], glyphId);
        this.compiledGlyphs[glyphId] = fn;
      } catch (ex) {
        this.compiledGlyphs[glyphId] = NOOP;
        if (this.compiledCharCodeToGlyphId[charCode] === undefined) {
          this.compiledCharCodeToGlyphId[charCode] = glyphId;
        }
        throw ex;
      }
    }
    if (this.compiledCharCodeToGlyphId[charCode] === undefined) {
      this.compiledCharCodeToGlyphId[charCode] = glyphId;
    }
    return fn;
  }
  compileGlyph(code, glyphId) {
    if (!code || code.length === 0 || code[0] === 14) {
      return NOOP;
    }
    let fontMatrix = this.fontMatrix;
    if (this.isCFFCIDFont) {
      const fdIndex = this.fdSelect.getFDIndex(glyphId);
      if (fdIndex >= 0 && fdIndex < this.fdArray.length) {
        const fontDict = this.fdArray[fdIndex];
        fontMatrix = fontDict.getByName("FontMatrix") || _util.FONT_IDENTITY_MATRIX;
      } else {
        (0, _util.warn)("Invalid fd index for glyph index.");
      }
    }
    const cmds = [{
      cmd: "save"
    }, {
      cmd: "transform",
      args: fontMatrix.slice()
    }, {
      cmd: "scale",
      args: ["size", "-size"]
    }];
    this.compileGlyphImpl(code, cmds, glyphId);
    cmds.push({
      cmd: "restore"
    });
    return cmds;
  }
  compileGlyphImpl() {
    (0, _util.unreachable)("Children classes should implement this.");
  }
  hasBuiltPath(unicode) {
    const {
      charCode,
      glyphId
    } = lookupCmap(this.cmap, unicode);
    return this.compiledGlyphs[glyphId] !== undefined && this.compiledCharCodeToGlyphId[charCode] !== undefined;
  }
}
class TrueTypeCompiled extends CompiledFont {
  constructor(glyphs, cmap, fontMatrix) {
    super(fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0]);
    this.glyphs = glyphs;
    this.cmap = cmap;
  }
  compileGlyphImpl(code, cmds) {
    compileGlyf(code, cmds, this);
  }
}
class Type2Compiled extends CompiledFont {
  constructor(cffInfo, cmap, fontMatrix, glyphNameMap) {
    super(fontMatrix || [0.001, 0, 0, 0.001, 0, 0]);
    this.glyphs = cffInfo.glyphs;
    this.gsubrs = cffInfo.gsubrs || [];
    this.subrs = cffInfo.subrs || [];
    this.cmap = cmap;
    this.glyphNameMap = glyphNameMap || (0, _glyphlist.getGlyphsUnicode)();
    this.gsubrsBias = getSubroutineBias(this.gsubrs);
    this.subrsBias = getSubroutineBias(this.subrs);
    this.isCFFCIDFont = cffInfo.isCFFCIDFont;
    this.fdSelect = cffInfo.fdSelect;
    this.fdArray = cffInfo.fdArray;
  }
  compileGlyphImpl(code, cmds, glyphId) {
    compileCharString(code, cmds, this, glyphId);
  }
}
class FontRendererFactory {
  static create(font, seacAnalysisEnabled) {
    const data = new Uint8Array(font.data);
    let cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
    const numTables = getUint16(data, 4);
    for (let i = 0, p = 12; i < numTables; i++, p += 16) {
      const tag = (0, _util.bytesToString)(data.subarray(p, p + 4));
      const offset = getUint32(data, p + 8);
      const length = getUint32(data, p + 12);
      switch (tag) {
        case "cmap":
          cmap = parseCmap(data, offset, offset + length);
          break;
        case "glyf":
          glyf = data.subarray(offset, offset + length);
          break;
        case "loca":
          loca = data.subarray(offset, offset + length);
          break;
        case "head":
          unitsPerEm = getUint16(data, offset + 18);
          indexToLocFormat = getUint16(data, offset + 50);
          break;
        case "CFF ":
          cff = parseCff(data, offset, offset + length, seacAnalysisEnabled);
          break;
      }
    }
    if (glyf) {
      const fontMatrix = !unitsPerEm ? font.fontMatrix : [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0];
      return new TrueTypeCompiled(parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
    }
    return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
  }
}
exports.FontRendererFactory = FontRendererFactory;

/***/ }),
/* 43 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.getMetrics = exports.getFontBasicMetrics = void 0;
var _core_utils = __w_pdfjs_require__(4);
const getMetrics = (0, _core_utils.getLookupTableFactory)(function (t) {
  t.Courier = 600;
  t["Courier-Bold"] = 600;
  t["Courier-BoldOblique"] = 600;
  t["Courier-Oblique"] = 600;
  t.Helvetica = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 278;
    t.exclam = 278;
    t.quotedbl = 355;
    t.numbersign = 556;
    t.dollar = 556;
    t.percent = 889;
    t.ampersand = 667;
    t.quoteright = 222;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 389;
    t.plus = 584;
    t.comma = 278;
    t.hyphen = 333;
    t.period = 278;
    t.slash = 278;
    t.zero = 556;
    t.one = 556;
    t.two = 556;
    t.three = 556;
    t.four = 556;
    t.five = 556;
    t.six = 556;
    t.seven = 556;
    t.eight = 556;
    t.nine = 556;
    t.colon = 278;
    t.semicolon = 278;
    t.less = 584;
    t.equal = 584;
    t.greater = 584;
    t.question = 556;
    t.at = 1015;
    t.A = 667;
    t.B = 667;
    t.C = 722;
    t.D = 722;
    t.E = 667;
    t.F = 611;
    t.G = 778;
    t.H = 722;
    t.I = 278;
    t.J = 500;
    t.K = 667;
    t.L = 556;
    t.M = 833;
    t.N = 722;
    t.O = 778;
    t.P = 667;
    t.Q = 778;
    t.R = 722;
    t.S = 667;
    t.T = 611;
    t.U = 722;
    t.V = 667;
    t.W = 944;
    t.X = 667;
    t.Y = 667;
    t.Z = 611;
    t.bracketleft = 278;
    t.backslash = 278;
    t.bracketright = 278;
    t.asciicircum = 469;
    t.underscore = 556;
    t.quoteleft = 222;
    t.a = 556;
    t.b = 556;
    t.c = 500;
    t.d = 556;
    t.e = 556;
    t.f = 278;
    t.g = 556;
    t.h = 556;
    t.i = 222;
    t.j = 222;
    t.k = 500;
    t.l = 222;
    t.m = 833;
    t.n = 556;
    t.o = 556;
    t.p = 556;
    t.q = 556;
    t.r = 333;
    t.s = 500;
    t.t = 278;
    t.u = 556;
    t.v = 500;
    t.w = 722;
    t.x = 500;
    t.y = 500;
    t.z = 500;
    t.braceleft = 334;
    t.bar = 260;
    t.braceright = 334;
    t.asciitilde = 584;
    t.exclamdown = 333;
    t.cent = 556;
    t.sterling = 556;
    t.fraction = 167;
    t.yen = 556;
    t.florin = 556;
    t.section = 556;
    t.currency = 556;
    t.quotesingle = 191;
    t.quotedblleft = 333;
    t.guillemotleft = 556;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 500;
    t.fl = 500;
    t.endash = 556;
    t.dagger = 556;
    t.daggerdbl = 556;
    t.periodcentered = 278;
    t.paragraph = 537;
    t.bullet = 350;
    t.quotesinglbase = 222;
    t.quotedblbase = 333;
    t.quotedblright = 333;
    t.guillemotright = 556;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 611;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 1000;
    t.ordfeminine = 370;
    t.Lslash = 556;
    t.Oslash = 778;
    t.OE = 1000;
    t.ordmasculine = 365;
    t.ae = 889;
    t.dotlessi = 278;
    t.lslash = 222;
    t.oslash = 611;
    t.oe = 944;
    t.germandbls = 611;
    t.Idieresis = 278;
    t.eacute = 556;
    t.abreve = 556;
    t.uhungarumlaut = 556;
    t.ecaron = 556;
    t.Ydieresis = 667;
    t.divide = 584;
    t.Yacute = 667;
    t.Acircumflex = 667;
    t.aacute = 556;
    t.Ucircumflex = 722;
    t.yacute = 500;
    t.scommaaccent = 500;
    t.ecircumflex = 556;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 556;
    t.Uacute = 722;
    t.uogonek = 556;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 737;
    t.Emacron = 667;
    t.ccaron = 500;
    t.aring = 556;
    t.Ncommaaccent = 722;
    t.lacute = 222;
    t.agrave = 556;
    t.Tcommaaccent = 611;
    t.Cacute = 722;
    t.atilde = 556;
    t.Edotaccent = 667;
    t.scaron = 500;
    t.scedilla = 500;
    t.iacute = 278;
    t.lozenge = 471;
    t.Rcaron = 722;
    t.Gcommaaccent = 778;
    t.ucircumflex = 556;
    t.acircumflex = 556;
    t.Amacron = 667;
    t.rcaron = 333;
    t.ccedilla = 500;
    t.Zdotaccent = 611;
    t.Thorn = 667;
    t.Omacron = 778;
    t.Racute = 722;
    t.Sacute = 667;
    t.dcaron = 643;
    t.Umacron = 722;
    t.uring = 556;
    t.threesuperior = 333;
    t.Ograve = 778;
    t.Agrave = 667;
    t.Abreve = 667;
    t.multiply = 584;
    t.uacute = 556;
    t.Tcaron = 611;
    t.partialdiff = 476;
    t.ydieresis = 500;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 556;
    t.edieresis = 556;
    t.cacute = 500;
    t.nacute = 556;
    t.umacron = 556;
    t.Ncaron = 722;
    t.Iacute = 278;
    t.plusminus = 584;
    t.brokenbar = 260;
    t.registered = 737;
    t.Gbreve = 778;
    t.Idotaccent = 278;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 333;
    t.omacron = 556;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 722;
    t.lcommaaccent = 222;
    t.tcaron = 317;
    t.eogonek = 556;
    t.Uogonek = 722;
    t.Aacute = 667;
    t.Adieresis = 667;
    t.egrave = 556;
    t.zacute = 500;
    t.iogonek = 222;
    t.Oacute = 778;
    t.oacute = 556;
    t.amacron = 556;
    t.sacute = 500;
    t.idieresis = 278;
    t.Ocircumflex = 778;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 556;
    t.twosuperior = 333;
    t.Odieresis = 778;
    t.mu = 556;
    t.igrave = 278;
    t.ohungarumlaut = 556;
    t.Eogonek = 667;
    t.dcroat = 556;
    t.threequarters = 834;
    t.Scedilla = 667;
    t.lcaron = 299;
    t.Kcommaaccent = 667;
    t.Lacute = 556;
    t.trademark = 1000;
    t.edotaccent = 556;
    t.Igrave = 278;
    t.Imacron = 278;
    t.Lcaron = 556;
    t.onehalf = 834;
    t.lessequal = 549;
    t.ocircumflex = 556;
    t.ntilde = 556;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 556;
    t.gbreve = 556;
    t.onequarter = 834;
    t.Scaron = 667;
    t.Scommaaccent = 667;
    t.Ohungarumlaut = 778;
    t.degree = 400;
    t.ograve = 556;
    t.Ccaron = 722;
    t.ugrave = 556;
    t.radical = 453;
    t.Dcaron = 722;
    t.rcommaaccent = 333;
    t.Ntilde = 722;
    t.otilde = 556;
    t.Rcommaaccent = 722;
    t.Lcommaaccent = 556;
    t.Atilde = 667;
    t.Aogonek = 667;
    t.Aring = 667;
    t.Otilde = 778;
    t.zdotaccent = 500;
    t.Ecaron = 667;
    t.Iogonek = 278;
    t.kcommaaccent = 500;
    t.minus = 584;
    t.Icircumflex = 278;
    t.ncaron = 556;
    t.tcommaaccent = 278;
    t.logicalnot = 584;
    t.odieresis = 556;
    t.udieresis = 556;
    t.notequal = 549;
    t.gcommaaccent = 556;
    t.eth = 556;
    t.zcaron = 500;
    t.ncommaaccent = 556;
    t.onesuperior = 333;
    t.imacron = 278;
    t.Euro = 556;
  });
  t["Helvetica-Bold"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 278;
    t.exclam = 333;
    t.quotedbl = 474;
    t.numbersign = 556;
    t.dollar = 556;
    t.percent = 889;
    t.ampersand = 722;
    t.quoteright = 278;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 389;
    t.plus = 584;
    t.comma = 278;
    t.hyphen = 333;
    t.period = 278;
    t.slash = 278;
    t.zero = 556;
    t.one = 556;
    t.two = 556;
    t.three = 556;
    t.four = 556;
    t.five = 556;
    t.six = 556;
    t.seven = 556;
    t.eight = 556;
    t.nine = 556;
    t.colon = 333;
    t.semicolon = 333;
    t.less = 584;
    t.equal = 584;
    t.greater = 584;
    t.question = 611;
    t.at = 975;
    t.A = 722;
    t.B = 722;
    t.C = 722;
    t.D = 722;
    t.E = 667;
    t.F = 611;
    t.G = 778;
    t.H = 722;
    t.I = 278;
    t.J = 556;
    t.K = 722;
    t.L = 611;
    t.M = 833;
    t.N = 722;
    t.O = 778;
    t.P = 667;
    t.Q = 778;
    t.R = 722;
    t.S = 667;
    t.T = 611;
    t.U = 722;
    t.V = 667;
    t.W = 944;
    t.X = 667;
    t.Y = 667;
    t.Z = 611;
    t.bracketleft = 333;
    t.backslash = 278;
    t.bracketright = 333;
    t.asciicircum = 584;
    t.underscore = 556;
    t.quoteleft = 278;
    t.a = 556;
    t.b = 611;
    t.c = 556;
    t.d = 611;
    t.e = 556;
    t.f = 333;
    t.g = 611;
    t.h = 611;
    t.i = 278;
    t.j = 278;
    t.k = 556;
    t.l = 278;
    t.m = 889;
    t.n = 611;
    t.o = 611;
    t.p = 611;
    t.q = 611;
    t.r = 389;
    t.s = 556;
    t.t = 333;
    t.u = 611;
    t.v = 556;
    t.w = 778;
    t.x = 556;
    t.y = 556;
    t.z = 500;
    t.braceleft = 389;
    t.bar = 280;
    t.braceright = 389;
    t.asciitilde = 584;
    t.exclamdown = 333;
    t.cent = 556;
    t.sterling = 556;
    t.fraction = 167;
    t.yen = 556;
    t.florin = 556;
    t.section = 556;
    t.currency = 556;
    t.quotesingle = 238;
    t.quotedblleft = 500;
    t.guillemotleft = 556;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 611;
    t.fl = 611;
    t.endash = 556;
    t.dagger = 556;
    t.daggerdbl = 556;
    t.periodcentered = 278;
    t.paragraph = 556;
    t.bullet = 350;
    t.quotesinglbase = 278;
    t.quotedblbase = 500;
    t.quotedblright = 500;
    t.guillemotright = 556;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 611;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 1000;
    t.ordfeminine = 370;
    t.Lslash = 611;
    t.Oslash = 778;
    t.OE = 1000;
    t.ordmasculine = 365;
    t.ae = 889;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 611;
    t.oe = 944;
    t.germandbls = 611;
    t.Idieresis = 278;
    t.eacute = 556;
    t.abreve = 556;
    t.uhungarumlaut = 611;
    t.ecaron = 556;
    t.Ydieresis = 667;
    t.divide = 584;
    t.Yacute = 667;
    t.Acircumflex = 722;
    t.aacute = 556;
    t.Ucircumflex = 722;
    t.yacute = 556;
    t.scommaaccent = 556;
    t.ecircumflex = 556;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 556;
    t.Uacute = 722;
    t.uogonek = 611;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 737;
    t.Emacron = 667;
    t.ccaron = 556;
    t.aring = 556;
    t.Ncommaaccent = 722;
    t.lacute = 278;
    t.agrave = 556;
    t.Tcommaaccent = 611;
    t.Cacute = 722;
    t.atilde = 556;
    t.Edotaccent = 667;
    t.scaron = 556;
    t.scedilla = 556;
    t.iacute = 278;
    t.lozenge = 494;
    t.Rcaron = 722;
    t.Gcommaaccent = 778;
    t.ucircumflex = 611;
    t.acircumflex = 556;
    t.Amacron = 722;
    t.rcaron = 389;
    t.ccedilla = 556;
    t.Zdotaccent = 611;
    t.Thorn = 667;
    t.Omacron = 778;
    t.Racute = 722;
    t.Sacute = 667;
    t.dcaron = 743;
    t.Umacron = 722;
    t.uring = 611;
    t.threesuperior = 333;
    t.Ograve = 778;
    t.Agrave = 722;
    t.Abreve = 722;
    t.multiply = 584;
    t.uacute = 611;
    t.Tcaron = 611;
    t.partialdiff = 494;
    t.ydieresis = 556;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 556;
    t.edieresis = 556;
    t.cacute = 556;
    t.nacute = 611;
    t.umacron = 611;
    t.Ncaron = 722;
    t.Iacute = 278;
    t.plusminus = 584;
    t.brokenbar = 280;
    t.registered = 737;
    t.Gbreve = 778;
    t.Idotaccent = 278;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 389;
    t.omacron = 611;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 722;
    t.lcommaaccent = 278;
    t.tcaron = 389;
    t.eogonek = 556;
    t.Uogonek = 722;
    t.Aacute = 722;
    t.Adieresis = 722;
    t.egrave = 556;
    t.zacute = 500;
    t.iogonek = 278;
    t.Oacute = 778;
    t.oacute = 611;
    t.amacron = 556;
    t.sacute = 556;
    t.idieresis = 278;
    t.Ocircumflex = 778;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 611;
    t.twosuperior = 333;
    t.Odieresis = 778;
    t.mu = 611;
    t.igrave = 278;
    t.ohungarumlaut = 611;
    t.Eogonek = 667;
    t.dcroat = 611;
    t.threequarters = 834;
    t.Scedilla = 667;
    t.lcaron = 400;
    t.Kcommaaccent = 722;
    t.Lacute = 611;
    t.trademark = 1000;
    t.edotaccent = 556;
    t.Igrave = 278;
    t.Imacron = 278;
    t.Lcaron = 611;
    t.onehalf = 834;
    t.lessequal = 549;
    t.ocircumflex = 611;
    t.ntilde = 611;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 556;
    t.gbreve = 611;
    t.onequarter = 834;
    t.Scaron = 667;
    t.Scommaaccent = 667;
    t.Ohungarumlaut = 778;
    t.degree = 400;
    t.ograve = 611;
    t.Ccaron = 722;
    t.ugrave = 611;
    t.radical = 549;
    t.Dcaron = 722;
    t.rcommaaccent = 389;
    t.Ntilde = 722;
    t.otilde = 611;
    t.Rcommaaccent = 722;
    t.Lcommaaccent = 611;
    t.Atilde = 722;
    t.Aogonek = 722;
    t.Aring = 722;
    t.Otilde = 778;
    t.zdotaccent = 500;
    t.Ecaron = 667;
    t.Iogonek = 278;
    t.kcommaaccent = 556;
    t.minus = 584;
    t.Icircumflex = 278;
    t.ncaron = 611;
    t.tcommaaccent = 333;
    t.logicalnot = 584;
    t.odieresis = 611;
    t.udieresis = 611;
    t.notequal = 549;
    t.gcommaaccent = 611;
    t.eth = 611;
    t.zcaron = 500;
    t.ncommaaccent = 611;
    t.onesuperior = 333;
    t.imacron = 278;
    t.Euro = 556;
  });
  t["Helvetica-BoldOblique"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 278;
    t.exclam = 333;
    t.quotedbl = 474;
    t.numbersign = 556;
    t.dollar = 556;
    t.percent = 889;
    t.ampersand = 722;
    t.quoteright = 278;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 389;
    t.plus = 584;
    t.comma = 278;
    t.hyphen = 333;
    t.period = 278;
    t.slash = 278;
    t.zero = 556;
    t.one = 556;
    t.two = 556;
    t.three = 556;
    t.four = 556;
    t.five = 556;
    t.six = 556;
    t.seven = 556;
    t.eight = 556;
    t.nine = 556;
    t.colon = 333;
    t.semicolon = 333;
    t.less = 584;
    t.equal = 584;
    t.greater = 584;
    t.question = 611;
    t.at = 975;
    t.A = 722;
    t.B = 722;
    t.C = 722;
    t.D = 722;
    t.E = 667;
    t.F = 611;
    t.G = 778;
    t.H = 722;
    t.I = 278;
    t.J = 556;
    t.K = 722;
    t.L = 611;
    t.M = 833;
    t.N = 722;
    t.O = 778;
    t.P = 667;
    t.Q = 778;
    t.R = 722;
    t.S = 667;
    t.T = 611;
    t.U = 722;
    t.V = 667;
    t.W = 944;
    t.X = 667;
    t.Y = 667;
    t.Z = 611;
    t.bracketleft = 333;
    t.backslash = 278;
    t.bracketright = 333;
    t.asciicircum = 584;
    t.underscore = 556;
    t.quoteleft = 278;
    t.a = 556;
    t.b = 611;
    t.c = 556;
    t.d = 611;
    t.e = 556;
    t.f = 333;
    t.g = 611;
    t.h = 611;
    t.i = 278;
    t.j = 278;
    t.k = 556;
    t.l = 278;
    t.m = 889;
    t.n = 611;
    t.o = 611;
    t.p = 611;
    t.q = 611;
    t.r = 389;
    t.s = 556;
    t.t = 333;
    t.u = 611;
    t.v = 556;
    t.w = 778;
    t.x = 556;
    t.y = 556;
    t.z = 500;
    t.braceleft = 389;
    t.bar = 280;
    t.braceright = 389;
    t.asciitilde = 584;
    t.exclamdown = 333;
    t.cent = 556;
    t.sterling = 556;
    t.fraction = 167;
    t.yen = 556;
    t.florin = 556;
    t.section = 556;
    t.currency = 556;
    t.quotesingle = 238;
    t.quotedblleft = 500;
    t.guillemotleft = 556;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 611;
    t.fl = 611;
    t.endash = 556;
    t.dagger = 556;
    t.daggerdbl = 556;
    t.periodcentered = 278;
    t.paragraph = 556;
    t.bullet = 350;
    t.quotesinglbase = 278;
    t.quotedblbase = 500;
    t.quotedblright = 500;
    t.guillemotright = 556;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 611;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 1000;
    t.ordfeminine = 370;
    t.Lslash = 611;
    t.Oslash = 778;
    t.OE = 1000;
    t.ordmasculine = 365;
    t.ae = 889;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 611;
    t.oe = 944;
    t.germandbls = 611;
    t.Idieresis = 278;
    t.eacute = 556;
    t.abreve = 556;
    t.uhungarumlaut = 611;
    t.ecaron = 556;
    t.Ydieresis = 667;
    t.divide = 584;
    t.Yacute = 667;
    t.Acircumflex = 722;
    t.aacute = 556;
    t.Ucircumflex = 722;
    t.yacute = 556;
    t.scommaaccent = 556;
    t.ecircumflex = 556;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 556;
    t.Uacute = 722;
    t.uogonek = 611;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 737;
    t.Emacron = 667;
    t.ccaron = 556;
    t.aring = 556;
    t.Ncommaaccent = 722;
    t.lacute = 278;
    t.agrave = 556;
    t.Tcommaaccent = 611;
    t.Cacute = 722;
    t.atilde = 556;
    t.Edotaccent = 667;
    t.scaron = 556;
    t.scedilla = 556;
    t.iacute = 278;
    t.lozenge = 494;
    t.Rcaron = 722;
    t.Gcommaaccent = 778;
    t.ucircumflex = 611;
    t.acircumflex = 556;
    t.Amacron = 722;
    t.rcaron = 389;
    t.ccedilla = 556;
    t.Zdotaccent = 611;
    t.Thorn = 667;
    t.Omacron = 778;
    t.Racute = 722;
    t.Sacute = 667;
    t.dcaron = 743;
    t.Umacron = 722;
    t.uring = 611;
    t.threesuperior = 333;
    t.Ograve = 778;
    t.Agrave = 722;
    t.Abreve = 722;
    t.multiply = 584;
    t.uacute = 611;
    t.Tcaron = 611;
    t.partialdiff = 494;
    t.ydieresis = 556;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 556;
    t.edieresis = 556;
    t.cacute = 556;
    t.nacute = 611;
    t.umacron = 611;
    t.Ncaron = 722;
    t.Iacute = 278;
    t.plusminus = 584;
    t.brokenbar = 280;
    t.registered = 737;
    t.Gbreve = 778;
    t.Idotaccent = 278;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 389;
    t.omacron = 611;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 722;
    t.lcommaaccent = 278;
    t.tcaron = 389;
    t.eogonek = 556;
    t.Uogonek = 722;
    t.Aacute = 722;
    t.Adieresis = 722;
    t.egrave = 556;
    t.zacute = 500;
    t.iogonek = 278;
    t.Oacute = 778;
    t.oacute = 611;
    t.amacron = 556;
    t.sacute = 556;
    t.idieresis = 278;
    t.Ocircumflex = 778;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 611;
    t.twosuperior = 333;
    t.Odieresis = 778;
    t.mu = 611;
    t.igrave = 278;
    t.ohungarumlaut = 611;
    t.Eogonek = 667;
    t.dcroat = 611;
    t.threequarters = 834;
    t.Scedilla = 667;
    t.lcaron = 400;
    t.Kcommaaccent = 722;
    t.Lacute = 611;
    t.trademark = 1000;
    t.edotaccent = 556;
    t.Igrave = 278;
    t.Imacron = 278;
    t.Lcaron = 611;
    t.onehalf = 834;
    t.lessequal = 549;
    t.ocircumflex = 611;
    t.ntilde = 611;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 556;
    t.gbreve = 611;
    t.onequarter = 834;
    t.Scaron = 667;
    t.Scommaaccent = 667;
    t.Ohungarumlaut = 778;
    t.degree = 400;
    t.ograve = 611;
    t.Ccaron = 722;
    t.ugrave = 611;
    t.radical = 549;
    t.Dcaron = 722;
    t.rcommaaccent = 389;
    t.Ntilde = 722;
    t.otilde = 611;
    t.Rcommaaccent = 722;
    t.Lcommaaccent = 611;
    t.Atilde = 722;
    t.Aogonek = 722;
    t.Aring = 722;
    t.Otilde = 778;
    t.zdotaccent = 500;
    t.Ecaron = 667;
    t.Iogonek = 278;
    t.kcommaaccent = 556;
    t.minus = 584;
    t.Icircumflex = 278;
    t.ncaron = 611;
    t.tcommaaccent = 333;
    t.logicalnot = 584;
    t.odieresis = 611;
    t.udieresis = 611;
    t.notequal = 549;
    t.gcommaaccent = 611;
    t.eth = 611;
    t.zcaron = 500;
    t.ncommaaccent = 611;
    t.onesuperior = 333;
    t.imacron = 278;
    t.Euro = 556;
  });
  t["Helvetica-Oblique"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 278;
    t.exclam = 278;
    t.quotedbl = 355;
    t.numbersign = 556;
    t.dollar = 556;
    t.percent = 889;
    t.ampersand = 667;
    t.quoteright = 222;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 389;
    t.plus = 584;
    t.comma = 278;
    t.hyphen = 333;
    t.period = 278;
    t.slash = 278;
    t.zero = 556;
    t.one = 556;
    t.two = 556;
    t.three = 556;
    t.four = 556;
    t.five = 556;
    t.six = 556;
    t.seven = 556;
    t.eight = 556;
    t.nine = 556;
    t.colon = 278;
    t.semicolon = 278;
    t.less = 584;
    t.equal = 584;
    t.greater = 584;
    t.question = 556;
    t.at = 1015;
    t.A = 667;
    t.B = 667;
    t.C = 722;
    t.D = 722;
    t.E = 667;
    t.F = 611;
    t.G = 778;
    t.H = 722;
    t.I = 278;
    t.J = 500;
    t.K = 667;
    t.L = 556;
    t.M = 833;
    t.N = 722;
    t.O = 778;
    t.P = 667;
    t.Q = 778;
    t.R = 722;
    t.S = 667;
    t.T = 611;
    t.U = 722;
    t.V = 667;
    t.W = 944;
    t.X = 667;
    t.Y = 667;
    t.Z = 611;
    t.bracketleft = 278;
    t.backslash = 278;
    t.bracketright = 278;
    t.asciicircum = 469;
    t.underscore = 556;
    t.quoteleft = 222;
    t.a = 556;
    t.b = 556;
    t.c = 500;
    t.d = 556;
    t.e = 556;
    t.f = 278;
    t.g = 556;
    t.h = 556;
    t.i = 222;
    t.j = 222;
    t.k = 500;
    t.l = 222;
    t.m = 833;
    t.n = 556;
    t.o = 556;
    t.p = 556;
    t.q = 556;
    t.r = 333;
    t.s = 500;
    t.t = 278;
    t.u = 556;
    t.v = 500;
    t.w = 722;
    t.x = 500;
    t.y = 500;
    t.z = 500;
    t.braceleft = 334;
    t.bar = 260;
    t.braceright = 334;
    t.asciitilde = 584;
    t.exclamdown = 333;
    t.cent = 556;
    t.sterling = 556;
    t.fraction = 167;
    t.yen = 556;
    t.florin = 556;
    t.section = 556;
    t.currency = 556;
    t.quotesingle = 191;
    t.quotedblleft = 333;
    t.guillemotleft = 556;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 500;
    t.fl = 500;
    t.endash = 556;
    t.dagger = 556;
    t.daggerdbl = 556;
    t.periodcentered = 278;
    t.paragraph = 537;
    t.bullet = 350;
    t.quotesinglbase = 222;
    t.quotedblbase = 333;
    t.quotedblright = 333;
    t.guillemotright = 556;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 611;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 1000;
    t.ordfeminine = 370;
    t.Lslash = 556;
    t.Oslash = 778;
    t.OE = 1000;
    t.ordmasculine = 365;
    t.ae = 889;
    t.dotlessi = 278;
    t.lslash = 222;
    t.oslash = 611;
    t.oe = 944;
    t.germandbls = 611;
    t.Idieresis = 278;
    t.eacute = 556;
    t.abreve = 556;
    t.uhungarumlaut = 556;
    t.ecaron = 556;
    t.Ydieresis = 667;
    t.divide = 584;
    t.Yacute = 667;
    t.Acircumflex = 667;
    t.aacute = 556;
    t.Ucircumflex = 722;
    t.yacute = 500;
    t.scommaaccent = 500;
    t.ecircumflex = 556;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 556;
    t.Uacute = 722;
    t.uogonek = 556;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 737;
    t.Emacron = 667;
    t.ccaron = 500;
    t.aring = 556;
    t.Ncommaaccent = 722;
    t.lacute = 222;
    t.agrave = 556;
    t.Tcommaaccent = 611;
    t.Cacute = 722;
    t.atilde = 556;
    t.Edotaccent = 667;
    t.scaron = 500;
    t.scedilla = 500;
    t.iacute = 278;
    t.lozenge = 471;
    t.Rcaron = 722;
    t.Gcommaaccent = 778;
    t.ucircumflex = 556;
    t.acircumflex = 556;
    t.Amacron = 667;
    t.rcaron = 333;
    t.ccedilla = 500;
    t.Zdotaccent = 611;
    t.Thorn = 667;
    t.Omacron = 778;
    t.Racute = 722;
    t.Sacute = 667;
    t.dcaron = 643;
    t.Umacron = 722;
    t.uring = 556;
    t.threesuperior = 333;
    t.Ograve = 778;
    t.Agrave = 667;
    t.Abreve = 667;
    t.multiply = 584;
    t.uacute = 556;
    t.Tcaron = 611;
    t.partialdiff = 476;
    t.ydieresis = 500;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 556;
    t.edieresis = 556;
    t.cacute = 500;
    t.nacute = 556;
    t.umacron = 556;
    t.Ncaron = 722;
    t.Iacute = 278;
    t.plusminus = 584;
    t.brokenbar = 260;
    t.registered = 737;
    t.Gbreve = 778;
    t.Idotaccent = 278;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 333;
    t.omacron = 556;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 722;
    t.lcommaaccent = 222;
    t.tcaron = 317;
    t.eogonek = 556;
    t.Uogonek = 722;
    t.Aacute = 667;
    t.Adieresis = 667;
    t.egrave = 556;
    t.zacute = 500;
    t.iogonek = 222;
    t.Oacute = 778;
    t.oacute = 556;
    t.amacron = 556;
    t.sacute = 500;
    t.idieresis = 278;
    t.Ocircumflex = 778;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 556;
    t.twosuperior = 333;
    t.Odieresis = 778;
    t.mu = 556;
    t.igrave = 278;
    t.ohungarumlaut = 556;
    t.Eogonek = 667;
    t.dcroat = 556;
    t.threequarters = 834;
    t.Scedilla = 667;
    t.lcaron = 299;
    t.Kcommaaccent = 667;
    t.Lacute = 556;
    t.trademark = 1000;
    t.edotaccent = 556;
    t.Igrave = 278;
    t.Imacron = 278;
    t.Lcaron = 556;
    t.onehalf = 834;
    t.lessequal = 549;
    t.ocircumflex = 556;
    t.ntilde = 556;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 556;
    t.gbreve = 556;
    t.onequarter = 834;
    t.Scaron = 667;
    t.Scommaaccent = 667;
    t.Ohungarumlaut = 778;
    t.degree = 400;
    t.ograve = 556;
    t.Ccaron = 722;
    t.ugrave = 556;
    t.radical = 453;
    t.Dcaron = 722;
    t.rcommaaccent = 333;
    t.Ntilde = 722;
    t.otilde = 556;
    t.Rcommaaccent = 722;
    t.Lcommaaccent = 556;
    t.Atilde = 667;
    t.Aogonek = 667;
    t.Aring = 667;
    t.Otilde = 778;
    t.zdotaccent = 500;
    t.Ecaron = 667;
    t.Iogonek = 278;
    t.kcommaaccent = 500;
    t.minus = 584;
    t.Icircumflex = 278;
    t.ncaron = 556;
    t.tcommaaccent = 278;
    t.logicalnot = 584;
    t.odieresis = 556;
    t.udieresis = 556;
    t.notequal = 549;
    t.gcommaaccent = 556;
    t.eth = 556;
    t.zcaron = 500;
    t.ncommaaccent = 556;
    t.onesuperior = 333;
    t.imacron = 278;
    t.Euro = 556;
  });
  t.Symbol = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 250;
    t.exclam = 333;
    t.universal = 713;
    t.numbersign = 500;
    t.existential = 549;
    t.percent = 833;
    t.ampersand = 778;
    t.suchthat = 439;
    t.parenleft = 333;
    t.parenright = 333;
    t.asteriskmath = 500;
    t.plus = 549;
    t.comma = 250;
    t.minus = 549;
    t.period = 250;
    t.slash = 278;
    t.zero = 500;
    t.one = 500;
    t.two = 500;
    t.three = 500;
    t.four = 500;
    t.five = 500;
    t.six = 500;
    t.seven = 500;
    t.eight = 500;
    t.nine = 500;
    t.colon = 278;
    t.semicolon = 278;
    t.less = 549;
    t.equal = 549;
    t.greater = 549;
    t.question = 444;
    t.congruent = 549;
    t.Alpha = 722;
    t.Beta = 667;
    t.Chi = 722;
    t.Delta = 612;
    t.Epsilon = 611;
    t.Phi = 763;
    t.Gamma = 603;
    t.Eta = 722;
    t.Iota = 333;
    t.theta1 = 631;
    t.Kappa = 722;
    t.Lambda = 686;
    t.Mu = 889;
    t.Nu = 722;
    t.Omicron = 722;
    t.Pi = 768;
    t.Theta = 741;
    t.Rho = 556;
    t.Sigma = 592;
    t.Tau = 611;
    t.Upsilon = 690;
    t.sigma1 = 439;
    t.Omega = 768;
    t.Xi = 645;
    t.Psi = 795;
    t.Zeta = 611;
    t.bracketleft = 333;
    t.therefore = 863;
    t.bracketright = 333;
    t.perpendicular = 658;
    t.underscore = 500;
    t.radicalex = 500;
    t.alpha = 631;
    t.beta = 549;
    t.chi = 549;
    t.delta = 494;
    t.epsilon = 439;
    t.phi = 521;
    t.gamma = 411;
    t.eta = 603;
    t.iota = 329;
    t.phi1 = 603;
    t.kappa = 549;
    t.lambda = 549;
    t.mu = 576;
    t.nu = 521;
    t.omicron = 549;
    t.pi = 549;
    t.theta = 521;
    t.rho = 549;
    t.sigma = 603;
    t.tau = 439;
    t.upsilon = 576;
    t.omega1 = 713;
    t.omega = 686;
    t.xi = 493;
    t.psi = 686;
    t.zeta = 494;
    t.braceleft = 480;
    t.bar = 200;
    t.braceright = 480;
    t.similar = 549;
    t.Euro = 750;
    t.Upsilon1 = 620;
    t.minute = 247;
    t.lessequal = 549;
    t.fraction = 167;
    t.infinity = 713;
    t.florin = 500;
    t.club = 753;
    t.diamond = 753;
    t.heart = 753;
    t.spade = 753;
    t.arrowboth = 1042;
    t.arrowleft = 987;
    t.arrowup = 603;
    t.arrowright = 987;
    t.arrowdown = 603;
    t.degree = 400;
    t.plusminus = 549;
    t.second = 411;
    t.greaterequal = 549;
    t.multiply = 549;
    t.proportional = 713;
    t.partialdiff = 494;
    t.bullet = 460;
    t.divide = 549;
    t.notequal = 549;
    t.equivalence = 549;
    t.approxequal = 549;
    t.ellipsis = 1000;
    t.arrowvertex = 603;
    t.arrowhorizex = 1000;
    t.carriagereturn = 658;
    t.aleph = 823;
    t.Ifraktur = 686;
    t.Rfraktur = 795;
    t.weierstrass = 987;
    t.circlemultiply = 768;
    t.circleplus = 768;
    t.emptyset = 823;
    t.intersection = 768;
    t.union = 768;
    t.propersuperset = 713;
    t.reflexsuperset = 713;
    t.notsubset = 713;
    t.propersubset = 713;
    t.reflexsubset = 713;
    t.element = 713;
    t.notelement = 713;
    t.angle = 768;
    t.gradient = 713;
    t.registerserif = 790;
    t.copyrightserif = 790;
    t.trademarkserif = 890;
    t.product = 823;
    t.radical = 549;
    t.dotmath = 250;
    t.logicalnot = 713;
    t.logicaland = 603;
    t.logicalor = 603;
    t.arrowdblboth = 1042;
    t.arrowdblleft = 987;
    t.arrowdblup = 603;
    t.arrowdblright = 987;
    t.arrowdbldown = 603;
    t.lozenge = 494;
    t.angleleft = 329;
    t.registersans = 790;
    t.copyrightsans = 790;
    t.trademarksans = 786;
    t.summation = 713;
    t.parenlefttp = 384;
    t.parenleftex = 384;
    t.parenleftbt = 384;
    t.bracketlefttp = 384;
    t.bracketleftex = 384;
    t.bracketleftbt = 384;
    t.bracelefttp = 494;
    t.braceleftmid = 494;
    t.braceleftbt = 494;
    t.braceex = 494;
    t.angleright = 329;
    t.integral = 274;
    t.integraltp = 686;
    t.integralex = 686;
    t.integralbt = 686;
    t.parenrighttp = 384;
    t.parenrightex = 384;
    t.parenrightbt = 384;
    t.bracketrighttp = 384;
    t.bracketrightex = 384;
    t.bracketrightbt = 384;
    t.bracerighttp = 494;
    t.bracerightmid = 494;
    t.bracerightbt = 494;
    t.apple = 790;
  });
  t["Times-Roman"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 250;
    t.exclam = 333;
    t.quotedbl = 408;
    t.numbersign = 500;
    t.dollar = 500;
    t.percent = 833;
    t.ampersand = 778;
    t.quoteright = 333;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 500;
    t.plus = 564;
    t.comma = 250;
    t.hyphen = 333;
    t.period = 250;
    t.slash = 278;
    t.zero = 500;
    t.one = 500;
    t.two = 500;
    t.three = 500;
    t.four = 500;
    t.five = 500;
    t.six = 500;
    t.seven = 500;
    t.eight = 500;
    t.nine = 500;
    t.colon = 278;
    t.semicolon = 278;
    t.less = 564;
    t.equal = 564;
    t.greater = 564;
    t.question = 444;
    t.at = 921;
    t.A = 722;
    t.B = 667;
    t.C = 667;
    t.D = 722;
    t.E = 611;
    t.F = 556;
    t.G = 722;
    t.H = 722;
    t.I = 333;
    t.J = 389;
    t.K = 722;
    t.L = 611;
    t.M = 889;
    t.N = 722;
    t.O = 722;
    t.P = 556;
    t.Q = 722;
    t.R = 667;
    t.S = 556;
    t.T = 611;
    t.U = 722;
    t.V = 722;
    t.W = 944;
    t.X = 722;
    t.Y = 722;
    t.Z = 611;
    t.bracketleft = 333;
    t.backslash = 278;
    t.bracketright = 333;
    t.asciicircum = 469;
    t.underscore = 500;
    t.quoteleft = 333;
    t.a = 444;
    t.b = 500;
    t.c = 444;
    t.d = 500;
    t.e = 444;
    t.f = 333;
    t.g = 500;
    t.h = 500;
    t.i = 278;
    t.j = 278;
    t.k = 500;
    t.l = 278;
    t.m = 778;
    t.n = 500;
    t.o = 500;
    t.p = 500;
    t.q = 500;
    t.r = 333;
    t.s = 389;
    t.t = 278;
    t.u = 500;
    t.v = 500;
    t.w = 722;
    t.x = 500;
    t.y = 500;
    t.z = 444;
    t.braceleft = 480;
    t.bar = 200;
    t.braceright = 480;
    t.asciitilde = 541;
    t.exclamdown = 333;
    t.cent = 500;
    t.sterling = 500;
    t.fraction = 167;
    t.yen = 500;
    t.florin = 500;
    t.section = 500;
    t.currency = 500;
    t.quotesingle = 180;
    t.quotedblleft = 444;
    t.guillemotleft = 500;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 556;
    t.fl = 556;
    t.endash = 500;
    t.dagger = 500;
    t.daggerdbl = 500;
    t.periodcentered = 250;
    t.paragraph = 453;
    t.bullet = 350;
    t.quotesinglbase = 333;
    t.quotedblbase = 444;
    t.quotedblright = 444;
    t.guillemotright = 500;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 444;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 889;
    t.ordfeminine = 276;
    t.Lslash = 611;
    t.Oslash = 722;
    t.OE = 889;
    t.ordmasculine = 310;
    t.ae = 667;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 500;
    t.oe = 722;
    t.germandbls = 500;
    t.Idieresis = 333;
    t.eacute = 444;
    t.abreve = 444;
    t.uhungarumlaut = 500;
    t.ecaron = 444;
    t.Ydieresis = 722;
    t.divide = 564;
    t.Yacute = 722;
    t.Acircumflex = 722;
    t.aacute = 444;
    t.Ucircumflex = 722;
    t.yacute = 500;
    t.scommaaccent = 389;
    t.ecircumflex = 444;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 444;
    t.Uacute = 722;
    t.uogonek = 500;
    t.Edieresis = 611;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 760;
    t.Emacron = 611;
    t.ccaron = 444;
    t.aring = 444;
    t.Ncommaaccent = 722;
    t.lacute = 278;
    t.agrave = 444;
    t.Tcommaaccent = 611;
    t.Cacute = 667;
    t.atilde = 444;
    t.Edotaccent = 611;
    t.scaron = 389;
    t.scedilla = 389;
    t.iacute = 278;
    t.lozenge = 471;
    t.Rcaron = 667;
    t.Gcommaaccent = 722;
    t.ucircumflex = 500;
    t.acircumflex = 444;
    t.Amacron = 722;
    t.rcaron = 333;
    t.ccedilla = 444;
    t.Zdotaccent = 611;
    t.Thorn = 556;
    t.Omacron = 722;
    t.Racute = 667;
    t.Sacute = 556;
    t.dcaron = 588;
    t.Umacron = 722;
    t.uring = 500;
    t.threesuperior = 300;
    t.Ograve = 722;
    t.Agrave = 722;
    t.Abreve = 722;
    t.multiply = 564;
    t.uacute = 500;
    t.Tcaron = 611;
    t.partialdiff = 476;
    t.ydieresis = 500;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 611;
    t.adieresis = 444;
    t.edieresis = 444;
    t.cacute = 444;
    t.nacute = 500;
    t.umacron = 500;
    t.Ncaron = 722;
    t.Iacute = 333;
    t.plusminus = 564;
    t.brokenbar = 200;
    t.registered = 760;
    t.Gbreve = 722;
    t.Idotaccent = 333;
    t.summation = 600;
    t.Egrave = 611;
    t.racute = 333;
    t.omacron = 500;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 667;
    t.lcommaaccent = 278;
    t.tcaron = 326;
    t.eogonek = 444;
    t.Uogonek = 722;
    t.Aacute = 722;
    t.Adieresis = 722;
    t.egrave = 444;
    t.zacute = 444;
    t.iogonek = 278;
    t.Oacute = 722;
    t.oacute = 500;
    t.amacron = 444;
    t.sacute = 389;
    t.idieresis = 278;
    t.Ocircumflex = 722;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 500;
    t.twosuperior = 300;
    t.Odieresis = 722;
    t.mu = 500;
    t.igrave = 278;
    t.ohungarumlaut = 500;
    t.Eogonek = 611;
    t.dcroat = 500;
    t.threequarters = 750;
    t.Scedilla = 556;
    t.lcaron = 344;
    t.Kcommaaccent = 722;
    t.Lacute = 611;
    t.trademark = 980;
    t.edotaccent = 444;
    t.Igrave = 333;
    t.Imacron = 333;
    t.Lcaron = 611;
    t.onehalf = 750;
    t.lessequal = 549;
    t.ocircumflex = 500;
    t.ntilde = 500;
    t.Uhungarumlaut = 722;
    t.Eacute = 611;
    t.emacron = 444;
    t.gbreve = 500;
    t.onequarter = 750;
    t.Scaron = 556;
    t.Scommaaccent = 556;
    t.Ohungarumlaut = 722;
    t.degree = 400;
    t.ograve = 500;
    t.Ccaron = 667;
    t.ugrave = 500;
    t.radical = 453;
    t.Dcaron = 722;
    t.rcommaaccent = 333;
    t.Ntilde = 722;
    t.otilde = 500;
    t.Rcommaaccent = 667;
    t.Lcommaaccent = 611;
    t.Atilde = 722;
    t.Aogonek = 722;
    t.Aring = 722;
    t.Otilde = 722;
    t.zdotaccent = 444;
    t.Ecaron = 611;
    t.Iogonek = 333;
    t.kcommaaccent = 500;
    t.minus = 564;
    t.Icircumflex = 333;
    t.ncaron = 500;
    t.tcommaaccent = 278;
    t.logicalnot = 564;
    t.odieresis = 500;
    t.udieresis = 500;
    t.notequal = 549;
    t.gcommaaccent = 500;
    t.eth = 500;
    t.zcaron = 444;
    t.ncommaaccent = 500;
    t.onesuperior = 300;
    t.imacron = 278;
    t.Euro = 500;
  });
  t["Times-Bold"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 250;
    t.exclam = 333;
    t.quotedbl = 555;
    t.numbersign = 500;
    t.dollar = 500;
    t.percent = 1000;
    t.ampersand = 833;
    t.quoteright = 333;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 500;
    t.plus = 570;
    t.comma = 250;
    t.hyphen = 333;
    t.period = 250;
    t.slash = 278;
    t.zero = 500;
    t.one = 500;
    t.two = 500;
    t.three = 500;
    t.four = 500;
    t.five = 500;
    t.six = 500;
    t.seven = 500;
    t.eight = 500;
    t.nine = 500;
    t.colon = 333;
    t.semicolon = 333;
    t.less = 570;
    t.equal = 570;
    t.greater = 570;
    t.question = 500;
    t.at = 930;
    t.A = 722;
    t.B = 667;
    t.C = 722;
    t.D = 722;
    t.E = 667;
    t.F = 611;
    t.G = 778;
    t.H = 778;
    t.I = 389;
    t.J = 500;
    t.K = 778;
    t.L = 667;
    t.M = 944;
    t.N = 722;
    t.O = 778;
    t.P = 611;
    t.Q = 778;
    t.R = 722;
    t.S = 556;
    t.T = 667;
    t.U = 722;
    t.V = 722;
    t.W = 1000;
    t.X = 722;
    t.Y = 722;
    t.Z = 667;
    t.bracketleft = 333;
    t.backslash = 278;
    t.bracketright = 333;
    t.asciicircum = 581;
    t.underscore = 500;
    t.quoteleft = 333;
    t.a = 500;
    t.b = 556;
    t.c = 444;
    t.d = 556;
    t.e = 444;
    t.f = 333;
    t.g = 500;
    t.h = 556;
    t.i = 278;
    t.j = 333;
    t.k = 556;
    t.l = 278;
    t.m = 833;
    t.n = 556;
    t.o = 500;
    t.p = 556;
    t.q = 556;
    t.r = 444;
    t.s = 389;
    t.t = 333;
    t.u = 556;
    t.v = 500;
    t.w = 722;
    t.x = 500;
    t.y = 500;
    t.z = 444;
    t.braceleft = 394;
    t.bar = 220;
    t.braceright = 394;
    t.asciitilde = 520;
    t.exclamdown = 333;
    t.cent = 500;
    t.sterling = 500;
    t.fraction = 167;
    t.yen = 500;
    t.florin = 500;
    t.section = 500;
    t.currency = 500;
    t.quotesingle = 278;
    t.quotedblleft = 500;
    t.guillemotleft = 500;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 556;
    t.fl = 556;
    t.endash = 500;
    t.dagger = 500;
    t.daggerdbl = 500;
    t.periodcentered = 250;
    t.paragraph = 540;
    t.bullet = 350;
    t.quotesinglbase = 333;
    t.quotedblbase = 500;
    t.quotedblright = 500;
    t.guillemotright = 500;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 500;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 1000;
    t.ordfeminine = 300;
    t.Lslash = 667;
    t.Oslash = 778;
    t.OE = 1000;
    t.ordmasculine = 330;
    t.ae = 722;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 500;
    t.oe = 722;
    t.germandbls = 556;
    t.Idieresis = 389;
    t.eacute = 444;
    t.abreve = 500;
    t.uhungarumlaut = 556;
    t.ecaron = 444;
    t.Ydieresis = 722;
    t.divide = 570;
    t.Yacute = 722;
    t.Acircumflex = 722;
    t.aacute = 500;
    t.Ucircumflex = 722;
    t.yacute = 500;
    t.scommaaccent = 389;
    t.ecircumflex = 444;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 500;
    t.Uacute = 722;
    t.uogonek = 556;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 747;
    t.Emacron = 667;
    t.ccaron = 444;
    t.aring = 500;
    t.Ncommaaccent = 722;
    t.lacute = 278;
    t.agrave = 500;
    t.Tcommaaccent = 667;
    t.Cacute = 722;
    t.atilde = 500;
    t.Edotaccent = 667;
    t.scaron = 389;
    t.scedilla = 389;
    t.iacute = 278;
    t.lozenge = 494;
    t.Rcaron = 722;
    t.Gcommaaccent = 778;
    t.ucircumflex = 556;
    t.acircumflex = 500;
    t.Amacron = 722;
    t.rcaron = 444;
    t.ccedilla = 444;
    t.Zdotaccent = 667;
    t.Thorn = 611;
    t.Omacron = 778;
    t.Racute = 722;
    t.Sacute = 556;
    t.dcaron = 672;
    t.Umacron = 722;
    t.uring = 556;
    t.threesuperior = 300;
    t.Ograve = 778;
    t.Agrave = 722;
    t.Abreve = 722;
    t.multiply = 570;
    t.uacute = 556;
    t.Tcaron = 667;
    t.partialdiff = 494;
    t.ydieresis = 500;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 500;
    t.edieresis = 444;
    t.cacute = 444;
    t.nacute = 556;
    t.umacron = 556;
    t.Ncaron = 722;
    t.Iacute = 389;
    t.plusminus = 570;
    t.brokenbar = 220;
    t.registered = 747;
    t.Gbreve = 778;
    t.Idotaccent = 389;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 444;
    t.omacron = 500;
    t.Zacute = 667;
    t.Zcaron = 667;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 722;
    t.lcommaaccent = 278;
    t.tcaron = 416;
    t.eogonek = 444;
    t.Uogonek = 722;
    t.Aacute = 722;
    t.Adieresis = 722;
    t.egrave = 444;
    t.zacute = 444;
    t.iogonek = 278;
    t.Oacute = 778;
    t.oacute = 500;
    t.amacron = 500;
    t.sacute = 389;
    t.idieresis = 278;
    t.Ocircumflex = 778;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 556;
    t.twosuperior = 300;
    t.Odieresis = 778;
    t.mu = 556;
    t.igrave = 278;
    t.ohungarumlaut = 500;
    t.Eogonek = 667;
    t.dcroat = 556;
    t.threequarters = 750;
    t.Scedilla = 556;
    t.lcaron = 394;
    t.Kcommaaccent = 778;
    t.Lacute = 667;
    t.trademark = 1000;
    t.edotaccent = 444;
    t.Igrave = 389;
    t.Imacron = 389;
    t.Lcaron = 667;
    t.onehalf = 750;
    t.lessequal = 549;
    t.ocircumflex = 500;
    t.ntilde = 556;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 444;
    t.gbreve = 500;
    t.onequarter = 750;
    t.Scaron = 556;
    t.Scommaaccent = 556;
    t.Ohungarumlaut = 778;
    t.degree = 400;
    t.ograve = 500;
    t.Ccaron = 722;
    t.ugrave = 556;
    t.radical = 549;
    t.Dcaron = 722;
    t.rcommaaccent = 444;
    t.Ntilde = 722;
    t.otilde = 500;
    t.Rcommaaccent = 722;
    t.Lcommaaccent = 667;
    t.Atilde = 722;
    t.Aogonek = 722;
    t.Aring = 722;
    t.Otilde = 778;
    t.zdotaccent = 444;
    t.Ecaron = 667;
    t.Iogonek = 389;
    t.kcommaaccent = 556;
    t.minus = 570;
    t.Icircumflex = 389;
    t.ncaron = 556;
    t.tcommaaccent = 333;
    t.logicalnot = 570;
    t.odieresis = 500;
    t.udieresis = 556;
    t.notequal = 549;
    t.gcommaaccent = 500;
    t.eth = 500;
    t.zcaron = 444;
    t.ncommaaccent = 556;
    t.onesuperior = 300;
    t.imacron = 278;
    t.Euro = 500;
  });
  t["Times-BoldItalic"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 250;
    t.exclam = 389;
    t.quotedbl = 555;
    t.numbersign = 500;
    t.dollar = 500;
    t.percent = 833;
    t.ampersand = 778;
    t.quoteright = 333;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 500;
    t.plus = 570;
    t.comma = 250;
    t.hyphen = 333;
    t.period = 250;
    t.slash = 278;
    t.zero = 500;
    t.one = 500;
    t.two = 500;
    t.three = 500;
    t.four = 500;
    t.five = 500;
    t.six = 500;
    t.seven = 500;
    t.eight = 500;
    t.nine = 500;
    t.colon = 333;
    t.semicolon = 333;
    t.less = 570;
    t.equal = 570;
    t.greater = 570;
    t.question = 500;
    t.at = 832;
    t.A = 667;
    t.B = 667;
    t.C = 667;
    t.D = 722;
    t.E = 667;
    t.F = 667;
    t.G = 722;
    t.H = 778;
    t.I = 389;
    t.J = 500;
    t.K = 667;
    t.L = 611;
    t.M = 889;
    t.N = 722;
    t.O = 722;
    t.P = 611;
    t.Q = 722;
    t.R = 667;
    t.S = 556;
    t.T = 611;
    t.U = 722;
    t.V = 667;
    t.W = 889;
    t.X = 667;
    t.Y = 611;
    t.Z = 611;
    t.bracketleft = 333;
    t.backslash = 278;
    t.bracketright = 333;
    t.asciicircum = 570;
    t.underscore = 500;
    t.quoteleft = 333;
    t.a = 500;
    t.b = 500;
    t.c = 444;
    t.d = 500;
    t.e = 444;
    t.f = 333;
    t.g = 500;
    t.h = 556;
    t.i = 278;
    t.j = 278;
    t.k = 500;
    t.l = 278;
    t.m = 778;
    t.n = 556;
    t.o = 500;
    t.p = 500;
    t.q = 500;
    t.r = 389;
    t.s = 389;
    t.t = 278;
    t.u = 556;
    t.v = 444;
    t.w = 667;
    t.x = 500;
    t.y = 444;
    t.z = 389;
    t.braceleft = 348;
    t.bar = 220;
    t.braceright = 348;
    t.asciitilde = 570;
    t.exclamdown = 389;
    t.cent = 500;
    t.sterling = 500;
    t.fraction = 167;
    t.yen = 500;
    t.florin = 500;
    t.section = 500;
    t.currency = 500;
    t.quotesingle = 278;
    t.quotedblleft = 500;
    t.guillemotleft = 500;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 556;
    t.fl = 556;
    t.endash = 500;
    t.dagger = 500;
    t.daggerdbl = 500;
    t.periodcentered = 250;
    t.paragraph = 500;
    t.bullet = 350;
    t.quotesinglbase = 333;
    t.quotedblbase = 500;
    t.quotedblright = 500;
    t.guillemotright = 500;
    t.ellipsis = 1000;
    t.perthousand = 1000;
    t.questiondown = 500;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 1000;
    t.AE = 944;
    t.ordfeminine = 266;
    t.Lslash = 611;
    t.Oslash = 722;
    t.OE = 944;
    t.ordmasculine = 300;
    t.ae = 722;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 500;
    t.oe = 722;
    t.germandbls = 500;
    t.Idieresis = 389;
    t.eacute = 444;
    t.abreve = 500;
    t.uhungarumlaut = 556;
    t.ecaron = 444;
    t.Ydieresis = 611;
    t.divide = 570;
    t.Yacute = 611;
    t.Acircumflex = 667;
    t.aacute = 500;
    t.Ucircumflex = 722;
    t.yacute = 444;
    t.scommaaccent = 389;
    t.ecircumflex = 444;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 500;
    t.Uacute = 722;
    t.uogonek = 556;
    t.Edieresis = 667;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 747;
    t.Emacron = 667;
    t.ccaron = 444;
    t.aring = 500;
    t.Ncommaaccent = 722;
    t.lacute = 278;
    t.agrave = 500;
    t.Tcommaaccent = 611;
    t.Cacute = 667;
    t.atilde = 500;
    t.Edotaccent = 667;
    t.scaron = 389;
    t.scedilla = 389;
    t.iacute = 278;
    t.lozenge = 494;
    t.Rcaron = 667;
    t.Gcommaaccent = 722;
    t.ucircumflex = 556;
    t.acircumflex = 500;
    t.Amacron = 667;
    t.rcaron = 389;
    t.ccedilla = 444;
    t.Zdotaccent = 611;
    t.Thorn = 611;
    t.Omacron = 722;
    t.Racute = 667;
    t.Sacute = 556;
    t.dcaron = 608;
    t.Umacron = 722;
    t.uring = 556;
    t.threesuperior = 300;
    t.Ograve = 722;
    t.Agrave = 667;
    t.Abreve = 667;
    t.multiply = 570;
    t.uacute = 556;
    t.Tcaron = 611;
    t.partialdiff = 494;
    t.ydieresis = 444;
    t.Nacute = 722;
    t.icircumflex = 278;
    t.Ecircumflex = 667;
    t.adieresis = 500;
    t.edieresis = 444;
    t.cacute = 444;
    t.nacute = 556;
    t.umacron = 556;
    t.Ncaron = 722;
    t.Iacute = 389;
    t.plusminus = 570;
    t.brokenbar = 220;
    t.registered = 747;
    t.Gbreve = 722;
    t.Idotaccent = 389;
    t.summation = 600;
    t.Egrave = 667;
    t.racute = 389;
    t.omacron = 500;
    t.Zacute = 611;
    t.Zcaron = 611;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 667;
    t.lcommaaccent = 278;
    t.tcaron = 366;
    t.eogonek = 444;
    t.Uogonek = 722;
    t.Aacute = 667;
    t.Adieresis = 667;
    t.egrave = 444;
    t.zacute = 389;
    t.iogonek = 278;
    t.Oacute = 722;
    t.oacute = 500;
    t.amacron = 500;
    t.sacute = 389;
    t.idieresis = 278;
    t.Ocircumflex = 722;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 500;
    t.twosuperior = 300;
    t.Odieresis = 722;
    t.mu = 576;
    t.igrave = 278;
    t.ohungarumlaut = 500;
    t.Eogonek = 667;
    t.dcroat = 500;
    t.threequarters = 750;
    t.Scedilla = 556;
    t.lcaron = 382;
    t.Kcommaaccent = 667;
    t.Lacute = 611;
    t.trademark = 1000;
    t.edotaccent = 444;
    t.Igrave = 389;
    t.Imacron = 389;
    t.Lcaron = 611;
    t.onehalf = 750;
    t.lessequal = 549;
    t.ocircumflex = 500;
    t.ntilde = 556;
    t.Uhungarumlaut = 722;
    t.Eacute = 667;
    t.emacron = 444;
    t.gbreve = 500;
    t.onequarter = 750;
    t.Scaron = 556;
    t.Scommaaccent = 556;
    t.Ohungarumlaut = 722;
    t.degree = 400;
    t.ograve = 500;
    t.Ccaron = 667;
    t.ugrave = 556;
    t.radical = 549;
    t.Dcaron = 722;
    t.rcommaaccent = 389;
    t.Ntilde = 722;
    t.otilde = 500;
    t.Rcommaaccent = 667;
    t.Lcommaaccent = 611;
    t.Atilde = 667;
    t.Aogonek = 667;
    t.Aring = 667;
    t.Otilde = 722;
    t.zdotaccent = 389;
    t.Ecaron = 667;
    t.Iogonek = 389;
    t.kcommaaccent = 500;
    t.minus = 606;
    t.Icircumflex = 389;
    t.ncaron = 556;
    t.tcommaaccent = 278;
    t.logicalnot = 606;
    t.odieresis = 500;
    t.udieresis = 556;
    t.notequal = 549;
    t.gcommaaccent = 500;
    t.eth = 500;
    t.zcaron = 389;
    t.ncommaaccent = 556;
    t.onesuperior = 300;
    t.imacron = 278;
    t.Euro = 500;
  });
  t["Times-Italic"] = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 250;
    t.exclam = 333;
    t.quotedbl = 420;
    t.numbersign = 500;
    t.dollar = 500;
    t.percent = 833;
    t.ampersand = 778;
    t.quoteright = 333;
    t.parenleft = 333;
    t.parenright = 333;
    t.asterisk = 500;
    t.plus = 675;
    t.comma = 250;
    t.hyphen = 333;
    t.period = 250;
    t.slash = 278;
    t.zero = 500;
    t.one = 500;
    t.two = 500;
    t.three = 500;
    t.four = 500;
    t.five = 500;
    t.six = 500;
    t.seven = 500;
    t.eight = 500;
    t.nine = 500;
    t.colon = 333;
    t.semicolon = 333;
    t.less = 675;
    t.equal = 675;
    t.greater = 675;
    t.question = 500;
    t.at = 920;
    t.A = 611;
    t.B = 611;
    t.C = 667;
    t.D = 722;
    t.E = 611;
    t.F = 611;
    t.G = 722;
    t.H = 722;
    t.I = 333;
    t.J = 444;
    t.K = 667;
    t.L = 556;
    t.M = 833;
    t.N = 667;
    t.O = 722;
    t.P = 611;
    t.Q = 722;
    t.R = 611;
    t.S = 500;
    t.T = 556;
    t.U = 722;
    t.V = 611;
    t.W = 833;
    t.X = 611;
    t.Y = 556;
    t.Z = 556;
    t.bracketleft = 389;
    t.backslash = 278;
    t.bracketright = 389;
    t.asciicircum = 422;
    t.underscore = 500;
    t.quoteleft = 333;
    t.a = 500;
    t.b = 500;
    t.c = 444;
    t.d = 500;
    t.e = 444;
    t.f = 278;
    t.g = 500;
    t.h = 500;
    t.i = 278;
    t.j = 278;
    t.k = 444;
    t.l = 278;
    t.m = 722;
    t.n = 500;
    t.o = 500;
    t.p = 500;
    t.q = 500;
    t.r = 389;
    t.s = 389;
    t.t = 278;
    t.u = 500;
    t.v = 444;
    t.w = 667;
    t.x = 444;
    t.y = 444;
    t.z = 389;
    t.braceleft = 400;
    t.bar = 275;
    t.braceright = 400;
    t.asciitilde = 541;
    t.exclamdown = 389;
    t.cent = 500;
    t.sterling = 500;
    t.fraction = 167;
    t.yen = 500;
    t.florin = 500;
    t.section = 500;
    t.currency = 500;
    t.quotesingle = 214;
    t.quotedblleft = 556;
    t.guillemotleft = 500;
    t.guilsinglleft = 333;
    t.guilsinglright = 333;
    t.fi = 500;
    t.fl = 500;
    t.endash = 500;
    t.dagger = 500;
    t.daggerdbl = 500;
    t.periodcentered = 250;
    t.paragraph = 523;
    t.bullet = 350;
    t.quotesinglbase = 333;
    t.quotedblbase = 556;
    t.quotedblright = 556;
    t.guillemotright = 500;
    t.ellipsis = 889;
    t.perthousand = 1000;
    t.questiondown = 500;
    t.grave = 333;
    t.acute = 333;
    t.circumflex = 333;
    t.tilde = 333;
    t.macron = 333;
    t.breve = 333;
    t.dotaccent = 333;
    t.dieresis = 333;
    t.ring = 333;
    t.cedilla = 333;
    t.hungarumlaut = 333;
    t.ogonek = 333;
    t.caron = 333;
    t.emdash = 889;
    t.AE = 889;
    t.ordfeminine = 276;
    t.Lslash = 556;
    t.Oslash = 722;
    t.OE = 944;
    t.ordmasculine = 310;
    t.ae = 667;
    t.dotlessi = 278;
    t.lslash = 278;
    t.oslash = 500;
    t.oe = 667;
    t.germandbls = 500;
    t.Idieresis = 333;
    t.eacute = 444;
    t.abreve = 500;
    t.uhungarumlaut = 500;
    t.ecaron = 444;
    t.Ydieresis = 556;
    t.divide = 675;
    t.Yacute = 556;
    t.Acircumflex = 611;
    t.aacute = 500;
    t.Ucircumflex = 722;
    t.yacute = 444;
    t.scommaaccent = 389;
    t.ecircumflex = 444;
    t.Uring = 722;
    t.Udieresis = 722;
    t.aogonek = 500;
    t.Uacute = 722;
    t.uogonek = 500;
    t.Edieresis = 611;
    t.Dcroat = 722;
    t.commaaccent = 250;
    t.copyright = 760;
    t.Emacron = 611;
    t.ccaron = 444;
    t.aring = 500;
    t.Ncommaaccent = 667;
    t.lacute = 278;
    t.agrave = 500;
    t.Tcommaaccent = 556;
    t.Cacute = 667;
    t.atilde = 500;
    t.Edotaccent = 611;
    t.scaron = 389;
    t.scedilla = 389;
    t.iacute = 278;
    t.lozenge = 471;
    t.Rcaron = 611;
    t.Gcommaaccent = 722;
    t.ucircumflex = 500;
    t.acircumflex = 500;
    t.Amacron = 611;
    t.rcaron = 389;
    t.ccedilla = 444;
    t.Zdotaccent = 556;
    t.Thorn = 611;
    t.Omacron = 722;
    t.Racute = 611;
    t.Sacute = 500;
    t.dcaron = 544;
    t.Umacron = 722;
    t.uring = 500;
    t.threesuperior = 300;
    t.Ograve = 722;
    t.Agrave = 611;
    t.Abreve = 611;
    t.multiply = 675;
    t.uacute = 500;
    t.Tcaron = 556;
    t.partialdiff = 476;
    t.ydieresis = 444;
    t.Nacute = 667;
    t.icircumflex = 278;
    t.Ecircumflex = 611;
    t.adieresis = 500;
    t.edieresis = 444;
    t.cacute = 444;
    t.nacute = 500;
    t.umacron = 500;
    t.Ncaron = 667;
    t.Iacute = 333;
    t.plusminus = 675;
    t.brokenbar = 275;
    t.registered = 760;
    t.Gbreve = 722;
    t.Idotaccent = 333;
    t.summation = 600;
    t.Egrave = 611;
    t.racute = 389;
    t.omacron = 500;
    t.Zacute = 556;
    t.Zcaron = 556;
    t.greaterequal = 549;
    t.Eth = 722;
    t.Ccedilla = 667;
    t.lcommaaccent = 278;
    t.tcaron = 300;
    t.eogonek = 444;
    t.Uogonek = 722;
    t.Aacute = 611;
    t.Adieresis = 611;
    t.egrave = 444;
    t.zacute = 389;
    t.iogonek = 278;
    t.Oacute = 722;
    t.oacute = 500;
    t.amacron = 500;
    t.sacute = 389;
    t.idieresis = 278;
    t.Ocircumflex = 722;
    t.Ugrave = 722;
    t.Delta = 612;
    t.thorn = 500;
    t.twosuperior = 300;
    t.Odieresis = 722;
    t.mu = 500;
    t.igrave = 278;
    t.ohungarumlaut = 500;
    t.Eogonek = 611;
    t.dcroat = 500;
    t.threequarters = 750;
    t.Scedilla = 500;
    t.lcaron = 300;
    t.Kcommaaccent = 667;
    t.Lacute = 556;
    t.trademark = 980;
    t.edotaccent = 444;
    t.Igrave = 333;
    t.Imacron = 333;
    t.Lcaron = 611;
    t.onehalf = 750;
    t.lessequal = 549;
    t.ocircumflex = 500;
    t.ntilde = 500;
    t.Uhungarumlaut = 722;
    t.Eacute = 611;
    t.emacron = 444;
    t.gbreve = 500;
    t.onequarter = 750;
    t.Scaron = 500;
    t.Scommaaccent = 500;
    t.Ohungarumlaut = 722;
    t.degree = 400;
    t.ograve = 500;
    t.Ccaron = 667;
    t.ugrave = 500;
    t.radical = 453;
    t.Dcaron = 722;
    t.rcommaaccent = 389;
    t.Ntilde = 667;
    t.otilde = 500;
    t.Rcommaaccent = 611;
    t.Lcommaaccent = 556;
    t.Atilde = 611;
    t.Aogonek = 611;
    t.Aring = 611;
    t.Otilde = 722;
    t.zdotaccent = 389;
    t.Ecaron = 611;
    t.Iogonek = 333;
    t.kcommaaccent = 444;
    t.minus = 675;
    t.Icircumflex = 333;
    t.ncaron = 500;
    t.tcommaaccent = 278;
    t.logicalnot = 675;
    t.odieresis = 500;
    t.udieresis = 500;
    t.notequal = 549;
    t.gcommaaccent = 500;
    t.eth = 500;
    t.zcaron = 389;
    t.ncommaaccent = 500;
    t.onesuperior = 300;
    t.imacron = 278;
    t.Euro = 500;
  });
  t.ZapfDingbats = (0, _core_utils.getLookupTableFactory)(function (t) {
    t.space = 278;
    t.a1 = 974;
    t.a2 = 961;
    t.a202 = 974;
    t.a3 = 980;
    t.a4 = 719;
    t.a5 = 789;
    t.a119 = 790;
    t.a118 = 791;
    t.a117 = 690;
    t.a11 = 960;
    t.a12 = 939;
    t.a13 = 549;
    t.a14 = 855;
    t.a15 = 911;
    t.a16 = 933;
    t.a105 = 911;
    t.a17 = 945;
    t.a18 = 974;
    t.a19 = 755;
    t.a20 = 846;
    t.a21 = 762;
    t.a22 = 761;
    t.a23 = 571;
    t.a24 = 677;
    t.a25 = 763;
    t.a26 = 760;
    t.a27 = 759;
    t.a28 = 754;
    t.a6 = 494;
    t.a7 = 552;
    t.a8 = 537;
    t.a9 = 577;
    t.a10 = 692;
    t.a29 = 786;
    t.a30 = 788;
    t.a31 = 788;
    t.a32 = 790;
    t.a33 = 793;
    t.a34 = 794;
    t.a35 = 816;
    t.a36 = 823;
    t.a37 = 789;
    t.a38 = 841;
    t.a39 = 823;
    t.a40 = 833;
    t.a41 = 816;
    t.a42 = 831;
    t.a43 = 923;
    t.a44 = 744;
    t.a45 = 723;
    t.a46 = 749;
    t.a47 = 790;
    t.a48 = 792;
    t.a49 = 695;
    t.a50 = 776;
    t.a51 = 768;
    t.a52 = 792;
    t.a53 = 759;
    t.a54 = 707;
    t.a55 = 708;
    t.a56 = 682;
    t.a57 = 701;
    t.a58 = 826;
    t.a59 = 815;
    t.a60 = 789;
    t.a61 = 789;
    t.a62 = 707;
    t.a63 = 687;
    t.a64 = 696;
    t.a65 = 689;
    t.a66 = 786;
    t.a67 = 787;
    t.a68 = 713;
    t.a69 = 791;
    t.a70 = 785;
    t.a71 = 791;
    t.a72 = 873;
    t.a73 = 761;
    t.a74 = 762;
    t.a203 = 762;
    t.a75 = 759;
    t.a204 = 759;
    t.a76 = 892;
    t.a77 = 892;
    t.a78 = 788;
    t.a79 = 784;
    t.a81 = 438;
    t.a82 = 138;
    t.a83 = 277;
    t.a84 = 415;
    t.a97 = 392;
    t.a98 = 392;
    t.a99 = 668;
    t.a100 = 668;
    t.a89 = 390;
    t.a90 = 390;
    t.a93 = 317;
    t.a94 = 317;
    t.a91 = 276;
    t.a92 = 276;
    t.a205 = 509;
    t.a85 = 509;
    t.a206 = 410;
    t.a86 = 410;
    t.a87 = 234;
    t.a88 = 234;
    t.a95 = 334;
    t.a96 = 334;
    t.a101 = 732;
    t.a102 = 544;
    t.a103 = 544;
    t.a104 = 910;
    t.a106 = 667;
    t.a107 = 760;
    t.a108 = 760;
    t.a112 = 776;
    t.a111 = 595;
    t.a110 = 694;
    t.a109 = 626;
    t.a120 = 788;
    t.a121 = 788;
    t.a122 = 788;
    t.a123 = 788;
    t.a124 = 788;
    t.a125 = 788;
    t.a126 = 788;
    t.a127 = 788;
    t.a128 = 788;
    t.a129 = 788;
    t.a130 = 788;
    t.a131 = 788;
    t.a132 = 788;
    t.a133 = 788;
    t.a134 = 788;
    t.a135 = 788;
    t.a136 = 788;
    t.a137 = 788;
    t.a138 = 788;
    t.a139 = 788;
    t.a140 = 788;
    t.a141 = 788;
    t.a142 = 788;
    t.a143 = 788;
    t.a144 = 788;
    t.a145 = 788;
    t.a146 = 788;
    t.a147 = 788;
    t.a148 = 788;
    t.a149 = 788;
    t.a150 = 788;
    t.a151 = 788;
    t.a152 = 788;
    t.a153 = 788;
    t.a154 = 788;
    t.a155 = 788;
    t.a156 = 788;
    t.a157 = 788;
    t.a158 = 788;
    t.a159 = 788;
    t.a160 = 894;
    t.a161 = 838;
    t.a163 = 1016;
    t.a164 = 458;
    t.a196 = 748;
    t.a165 = 924;
    t.a192 = 748;
    t.a166 = 918;
    t.a167 = 927;
    t.a168 = 928;
    t.a169 = 928;
    t.a170 = 834;
    t.a171 = 873;
    t.a172 = 828;
    t.a173 = 924;
    t.a162 = 924;
    t.a174 = 917;
    t.a175 = 930;
    t.a176 = 931;
    t.a177 = 463;
    t.a178 = 883;
    t.a179 = 836;
    t.a193 = 836;
    t.a180 = 867;
    t.a199 = 867;
    t.a181 = 696;
    t.a200 = 696;
    t.a182 = 874;
    t.a201 = 874;
    t.a183 = 760;
    t.a184 = 946;
    t.a197 = 771;
    t.a185 = 865;
    t.a194 = 771;
    t.a198 = 888;
    t.a186 = 967;
    t.a195 = 888;
    t.a187 = 831;
    t.a188 = 873;
    t.a189 = 927;
    t.a190 = 970;
    t.a191 = 918;
  });
});
exports.getMetrics = getMetrics;
const getFontBasicMetrics = (0, _core_utils.getLookupTableFactory)(function (t) {
  t.Courier = {
    ascent: 629,
    descent: -157,
    capHeight: 562,
    xHeight: -426
  };
  t["Courier-Bold"] = {
    ascent: 629,
    descent: -157,
    capHeight: 562,
    xHeight: 439
  };
  t["Courier-Oblique"] = {
    ascent: 629,
    descent: -157,
    capHeight: 562,
    xHeight: 426
  };
  t["Courier-BoldOblique"] = {
    ascent: 629,
    descent: -157,
    capHeight: 562,
    xHeight: 426
  };
  t.Helvetica = {
    ascent: 718,
    descent: -207,
    capHeight: 718,
    xHeight: 523
  };
  t["Helvetica-Bold"] = {
    ascent: 718,
    descent: -207,
    capHeight: 718,
    xHeight: 532
  };
  t["Helvetica-Oblique"] = {
    ascent: 718,
    descent: -207,
    capHeight: 718,
    xHeight: 523
  };
  t["Helvetica-BoldOblique"] = {
    ascent: 718,
    descent: -207,
    capHeight: 718,
    xHeight: 532
  };
  t["Times-Roman"] = {
    ascent: 683,
    descent: -217,
    capHeight: 662,
    xHeight: 450
  };
  t["Times-Bold"] = {
    ascent: 683,
    descent: -217,
    capHeight: 676,
    xHeight: 461
  };
  t["Times-Italic"] = {
    ascent: 683,
    descent: -217,
    capHeight: 653,
    xHeight: 441
  };
  t["Times-BoldItalic"] = {
    ascent: 683,
    descent: -217,
    capHeight: 669,
    xHeight: 462
  };
  t.Symbol = {
    ascent: Math.NaN,
    descent: Math.NaN,
    capHeight: Math.NaN,
    xHeight: Math.NaN
  };
  t.ZapfDingbats = {
    ascent: Math.NaN,
    descent: Math.NaN,
    capHeight: Math.NaN,
    xHeight: Math.NaN
  };
});
exports.getFontBasicMetrics = getFontBasicMetrics;

/***/ }),
/* 44 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.GlyfTable = void 0;
const ON_CURVE_POINT = 1 << 0;
const X_SHORT_VECTOR = 1 << 1;
const Y_SHORT_VECTOR = 1 << 2;
const REPEAT_FLAG = 1 << 3;
const X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR = 1 << 4;
const Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR = 1 << 5;
const OVERLAP_SIMPLE = 1 << 6;
const ARG_1_AND_2_ARE_WORDS = 1 << 0;
const ARGS_ARE_XY_VALUES = 1 << 1;
const WE_HAVE_A_SCALE = 1 << 3;
const MORE_COMPONENTS = 1 << 5;
const WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6;
const WE_HAVE_A_TWO_BY_TWO = 1 << 7;
const WE_HAVE_INSTRUCTIONS = 1 << 8;
class GlyfTable {
  constructor({
    glyfTable,
    isGlyphLocationsLong,
    locaTable,
    numGlyphs
  }) {
    this.glyphs = [];
    const loca = new DataView(locaTable.buffer, locaTable.byteOffset, locaTable.byteLength);
    const glyf = new DataView(glyfTable.buffer, glyfTable.byteOffset, glyfTable.byteLength);
    const offsetSize = isGlyphLocationsLong ? 4 : 2;
    let prev = isGlyphLocationsLong ? loca.getUint32(0) : 2 * loca.getUint16(0);
    let pos = 0;
    for (let i = 0; i < numGlyphs; i++) {
      pos += offsetSize;
      const next = isGlyphLocationsLong ? loca.getUint32(pos) : 2 * loca.getUint16(pos);
      if (next === prev) {
        this.glyphs.push(new Glyph({}));
        continue;
      }
      const glyph = Glyph.parse(prev, glyf);
      this.glyphs.push(glyph);
      prev = next;
    }
  }
  getSize() {
    return this.glyphs.reduce((a, g) => {
      const size = g.getSize();
      return a + (size + 3 & ~3);
    }, 0);
  }
  write() {
    const totalSize = this.getSize();
    const glyfTable = new DataView(new ArrayBuffer(totalSize));
    const isLocationLong = totalSize > 0x1fffe;
    const offsetSize = isLocationLong ? 4 : 2;
    const locaTable = new DataView(new ArrayBuffer((this.glyphs.length + 1) * offsetSize));
    if (isLocationLong) {
      locaTable.setUint32(0, 0);
    } else {
      locaTable.setUint16(0, 0);
    }
    let pos = 0;
    let locaIndex = 0;
    for (const glyph of this.glyphs) {
      pos += glyph.write(pos, glyfTable);
      pos = pos + 3 & ~3;
      locaIndex += offsetSize;
      if (isLocationLong) {
        locaTable.setUint32(locaIndex, pos);
      } else {
        locaTable.setUint16(locaIndex, pos >> 1);
      }
    }
    return {
      isLocationLong,
      loca: new Uint8Array(locaTable.buffer),
      glyf: new Uint8Array(glyfTable.buffer)
    };
  }
  scale(factors) {
    for (let i = 0, ii = this.glyphs.length; i < ii; i++) {
      this.glyphs[i].scale(factors[i]);
    }
  }
}
exports.GlyfTable = GlyfTable;
class Glyph {
  constructor({
    header = null,
    simple = null,
    composites = null
  }) {
    this.header = header;
    this.simple = simple;
    this.composites = composites;
  }
  static parse(pos, glyf) {
    const [read, header] = GlyphHeader.parse(pos, glyf);
    pos += read;
    if (header.numberOfContours < 0) {
      const composites = [];
      while (true) {
        const [n, composite] = CompositeGlyph.parse(pos, glyf);
        pos += n;
        composites.push(composite);
        if (!(composite.flags & MORE_COMPONENTS)) {
          break;
        }
      }
      return new Glyph({
        header,
        composites
      });
    }
    const simple = SimpleGlyph.parse(pos, glyf, header.numberOfContours);
    return new Glyph({
      header,
      simple
    });
  }
  getSize() {
    if (!this.header) {
      return 0;
    }
    const size = this.simple ? this.simple.getSize() : this.composites.reduce((a, c) => a + c.getSize(), 0);
    return this.header.getSize() + size;
  }
  write(pos, buf) {
    if (!this.header) {
      return 0;
    }
    const spos = pos;
    pos += this.header.write(pos, buf);
    if (this.simple) {
      pos += this.simple.write(pos, buf);
    } else {
      for (const composite of this.composites) {
        pos += composite.write(pos, buf);
      }
    }
    return pos - spos;
  }
  scale(factor) {
    if (!this.header) {
      return;
    }
    const xMiddle = (this.header.xMin + this.header.xMax) / 2;
    this.header.scale(xMiddle, factor);
    if (this.simple) {
      this.simple.scale(xMiddle, factor);
    } else {
      for (const composite of this.composites) {
        composite.scale(xMiddle, factor);
      }
    }
  }
}
class GlyphHeader {
  constructor({
    numberOfContours,
    xMin,
    yMin,
    xMax,
    yMax
  }) {
    this.numberOfContours = numberOfContours;
    this.xMin = xMin;
    this.yMin = yMin;
    this.xMax = xMax;
    this.yMax = yMax;
  }
  static parse(pos, glyf) {
    return [10, new GlyphHeader({
      numberOfContours: glyf.getInt16(pos),
      xMin: glyf.getInt16(pos + 2),
      yMin: glyf.getInt16(pos + 4),
      xMax: glyf.getInt16(pos + 6),
      yMax: glyf.getInt16(pos + 8)
    })];
  }
  getSize() {
    return 10;
  }
  write(pos, buf) {
    buf.setInt16(pos, this.numberOfContours);
    buf.setInt16(pos + 2, this.xMin);
    buf.setInt16(pos + 4, this.yMin);
    buf.setInt16(pos + 6, this.xMax);
    buf.setInt16(pos + 8, this.yMax);
    return 10;
  }
  scale(x, factor) {
    this.xMin = Math.round(x + (this.xMin - x) * factor);
    this.xMax = Math.round(x + (this.xMax - x) * factor);
  }
}
class Contour {
  constructor({
    flags,
    xCoordinates,
    yCoordinates
  }) {
    this.xCoordinates = xCoordinates;
    this.yCoordinates = yCoordinates;
    this.flags = flags;
  }
}
class SimpleGlyph {
  constructor({
    contours,
    instructions
  }) {
    this.contours = contours;
    this.instructions = instructions;
  }
  static parse(pos, glyf, numberOfContours) {
    const endPtsOfContours = [];
    for (let i = 0; i < numberOfContours; i++) {
      const endPt = glyf.getUint16(pos);
      pos += 2;
      endPtsOfContours.push(endPt);
    }
    const numberOfPt = endPtsOfContours[numberOfContours - 1] + 1;
    const instructionLength = glyf.getUint16(pos);
    pos += 2;
    const instructions = new Uint8Array(glyf).slice(pos, pos + instructionLength);
    pos += instructionLength;
    const flags = [];
    for (let i = 0; i < numberOfPt; pos++, i++) {
      let flag = glyf.getUint8(pos);
      flags.push(flag);
      if (flag & REPEAT_FLAG) {
        const count = glyf.getUint8(++pos);
        flag ^= REPEAT_FLAG;
        for (let m = 0; m < count; m++) {
          flags.push(flag);
        }
        i += count;
      }
    }
    const allXCoordinates = [];
    let xCoordinates = [];
    let yCoordinates = [];
    let pointFlags = [];
    const contours = [];
    let endPtsOfContoursIndex = 0;
    let lastCoordinate = 0;
    for (let i = 0; i < numberOfPt; i++) {
      const flag = flags[i];
      if (flag & X_SHORT_VECTOR) {
        const x = glyf.getUint8(pos++);
        lastCoordinate += flag & X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR ? x : -x;
        xCoordinates.push(lastCoordinate);
      } else if (flag & X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR) {
        xCoordinates.push(lastCoordinate);
      } else {
        lastCoordinate += glyf.getInt16(pos);
        pos += 2;
        xCoordinates.push(lastCoordinate);
      }
      if (endPtsOfContours[endPtsOfContoursIndex] === i) {
        endPtsOfContoursIndex++;
        allXCoordinates.push(xCoordinates);
        xCoordinates = [];
      }
    }
    lastCoordinate = 0;
    endPtsOfContoursIndex = 0;
    for (let i = 0; i < numberOfPt; i++) {
      const flag = flags[i];
      if (flag & Y_SHORT_VECTOR) {
        const y = glyf.getUint8(pos++);
        lastCoordinate += flag & Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR ? y : -y;
        yCoordinates.push(lastCoordinate);
      } else if (flag & Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR) {
        yCoordinates.push(lastCoordinate);
      } else {
        lastCoordinate += glyf.getInt16(pos);
        pos += 2;
        yCoordinates.push(lastCoordinate);
      }
      pointFlags.push(flag & ON_CURVE_POINT | flag & OVERLAP_SIMPLE);
      if (endPtsOfContours[endPtsOfContoursIndex] === i) {
        xCoordinates = allXCoordinates[endPtsOfContoursIndex];
        endPtsOfContoursIndex++;
        contours.push(new Contour({
          flags: pointFlags,
          xCoordinates,
          yCoordinates
        }));
        yCoordinates = [];
        pointFlags = [];
      }
    }
    return new SimpleGlyph({
      contours,
      instructions
    });
  }
  getSize() {
    let size = this.contours.length * 2 + 2 + this.instructions.length;
    let lastX = 0;
    let lastY = 0;
    for (const contour of this.contours) {
      size += contour.flags.length;
      for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
        const x = contour.xCoordinates[i];
        const y = contour.yCoordinates[i];
        let abs = Math.abs(x - lastX);
        if (abs > 255) {
          size += 2;
        } else if (abs > 0) {
          size += 1;
        }
        lastX = x;
        abs = Math.abs(y - lastY);
        if (abs > 255) {
          size += 2;
        } else if (abs > 0) {
          size += 1;
        }
        lastY = y;
      }
    }
    return size;
  }
  write(pos, buf) {
    const spos = pos;
    const xCoordinates = [];
    const yCoordinates = [];
    const flags = [];
    let lastX = 0;
    let lastY = 0;
    for (const contour of this.contours) {
      for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
        let flag = contour.flags[i];
        const x = contour.xCoordinates[i];
        let delta = x - lastX;
        if (delta === 0) {
          flag |= X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR;
          xCoordinates.push(0);
        } else {
          const abs = Math.abs(delta);
          if (abs <= 255) {
            flag |= delta >= 0 ? X_SHORT_VECTOR | X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR : X_SHORT_VECTOR;
            xCoordinates.push(abs);
          } else {
            xCoordinates.push(delta);
          }
        }
        lastX = x;
        const y = contour.yCoordinates[i];
        delta = y - lastY;
        if (delta === 0) {
          flag |= Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR;
          yCoordinates.push(0);
        } else {
          const abs = Math.abs(delta);
          if (abs <= 255) {
            flag |= delta >= 0 ? Y_SHORT_VECTOR | Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR : Y_SHORT_VECTOR;
            yCoordinates.push(abs);
          } else {
            yCoordinates.push(delta);
          }
        }
        lastY = y;
        flags.push(flag);
      }
      buf.setUint16(pos, xCoordinates.length - 1);
      pos += 2;
    }
    buf.setUint16(pos, this.instructions.length);
    pos += 2;
    if (this.instructions.length) {
      new Uint8Array(buf.buffer, 0, buf.buffer.byteLength).set(this.instructions, pos);
      pos += this.instructions.length;
    }
    for (const flag of flags) {
      buf.setUint8(pos++, flag);
    }
    for (let i = 0, ii = xCoordinates.length; i < ii; i++) {
      const x = xCoordinates[i];
      const flag = flags[i];
      if (flag & X_SHORT_VECTOR) {
        buf.setUint8(pos++, x);
      } else if (!(flag & X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR)) {
        buf.setInt16(pos, x);
        pos += 2;
      }
    }
    for (let i = 0, ii = yCoordinates.length; i < ii; i++) {
      const y = yCoordinates[i];
      const flag = flags[i];
      if (flag & Y_SHORT_VECTOR) {
        buf.setUint8(pos++, y);
      } else if (!(flag & Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR)) {
        buf.setInt16(pos, y);
        pos += 2;
      }
    }
    return pos - spos;
  }
  scale(x, factor) {
    for (const contour of this.contours) {
      if (contour.xCoordinates.length === 0) {
        continue;
      }
      for (let i = 0, ii = contour.xCoordinates.length; i < ii; i++) {
        contour.xCoordinates[i] = Math.round(x + (contour.xCoordinates[i] - x) * factor);
      }
    }
  }
}
class CompositeGlyph {
  constructor({
    flags,
    glyphIndex,
    argument1,
    argument2,
    transf,
    instructions
  }) {
    this.flags = flags;
    this.glyphIndex = glyphIndex;
    this.argument1 = argument1;
    this.argument2 = argument2;
    this.transf = transf;
    this.instructions = instructions;
  }
  static parse(pos, glyf) {
    const spos = pos;
    const transf = [];
    let flags = glyf.getUint16(pos);
    const glyphIndex = glyf.getUint16(pos + 2);
    pos += 4;
    let argument1, argument2;
    if (flags & ARG_1_AND_2_ARE_WORDS) {
      if (flags & ARGS_ARE_XY_VALUES) {
        argument1 = glyf.getInt16(pos);
        argument2 = glyf.getInt16(pos + 2);
      } else {
        argument1 = glyf.getUint16(pos);
        argument2 = glyf.getUint16(pos + 2);
      }
      pos += 4;
      flags ^= ARG_1_AND_2_ARE_WORDS;
    } else {
      if (flags & ARGS_ARE_XY_VALUES) {
        argument1 = glyf.getInt8(pos);
        argument2 = glyf.getInt8(pos + 1);
      } else {
        argument1 = glyf.getUint8(pos);
        argument2 = glyf.getUint8(pos + 1);
      }
      pos += 2;
    }
    if (flags & WE_HAVE_A_SCALE) {
      transf.push(glyf.getUint16(pos));
      pos += 2;
    } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
      transf.push(glyf.getUint16(pos), glyf.getUint16(pos + 2));
      pos += 4;
    } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
      transf.push(glyf.getUint16(pos), glyf.getUint16(pos + 2), glyf.getUint16(pos + 4), glyf.getUint16(pos + 6));
      pos += 8;
    }
    let instructions = null;
    if (flags & WE_HAVE_INSTRUCTIONS) {
      const instructionLength = glyf.getUint16(pos);
      pos += 2;
      instructions = new Uint8Array(glyf).slice(pos, pos + instructionLength);
      pos += instructionLength;
    }
    return [pos - spos, new CompositeGlyph({
      flags,
      glyphIndex,
      argument1,
      argument2,
      transf,
      instructions
    })];
  }
  getSize() {
    let size = 2 + 2 + this.transf.length * 2;
    if (this.flags & WE_HAVE_INSTRUCTIONS) {
      size += 2 + this.instructions.length;
    }
    size += 2;
    if (this.flags & 2) {
      if (!(this.argument1 >= -128 && this.argument1 <= 127 && this.argument2 >= -128 && this.argument2 <= 127)) {
        size += 2;
      }
    } else {
      if (!(this.argument1 >= 0 && this.argument1 <= 255 && this.argument2 >= 0 && this.argument2 <= 255)) {
        size += 2;
      }
    }
    return size;
  }
  write(pos, buf) {
    const spos = pos;
    if (this.flags & ARGS_ARE_XY_VALUES) {
      if (!(this.argument1 >= -128 && this.argument1 <= 127 && this.argument2 >= -128 && this.argument2 <= 127)) {
        this.flags |= ARG_1_AND_2_ARE_WORDS;
      }
    } else {
      if (!(this.argument1 >= 0 && this.argument1 <= 255 && this.argument2 >= 0 && this.argument2 <= 255)) {
        this.flags |= ARG_1_AND_2_ARE_WORDS;
      }
    }
    buf.setUint16(pos, this.flags);
    buf.setUint16(pos + 2, this.glyphIndex);
    pos += 4;
    if (this.flags & ARG_1_AND_2_ARE_WORDS) {
      if (this.flags & ARGS_ARE_XY_VALUES) {
        buf.setInt16(pos, this.argument1);
        buf.setInt16(pos + 2, this.argument2);
      } else {
        buf.setUint16(pos, this.argument1);
        buf.setUint16(pos + 2, this.argument2);
      }
      pos += 4;
    } else {
      buf.setUint8(pos, this.argument1);
      buf.setUint8(pos + 1, this.argument2);
      pos += 2;
    }
    if (this.flags & WE_HAVE_INSTRUCTIONS) {
      buf.setUint16(pos, this.instructions.length);
      pos += 2;
      if (this.instructions.length) {
        new Uint8Array(buf.buffer, 0, buf.buffer.byteLength).set(this.instructions, pos);
        pos += this.instructions.length;
      }
    }
    return pos - spos;
  }
  scale(x, factor) {}
}

/***/ }),
/* 45 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.OpenTypeFileBuilder = void 0;
var _core_utils = __w_pdfjs_require__(4);
var _util = __w_pdfjs_require__(2);
function writeInt16(dest, offset, num) {
  dest[offset] = num >> 8 & 0xff;
  dest[offset + 1] = num & 0xff;
}
function writeInt32(dest, offset, num) {
  dest[offset] = num >> 24 & 0xff;
  dest[offset + 1] = num >> 16 & 0xff;
  dest[offset + 2] = num >> 8 & 0xff;
  dest[offset + 3] = num & 0xff;
}
function writeData(dest, offset, data) {
  if (data instanceof Uint8Array) {
    dest.set(data, offset);
  } else if (typeof data === "string") {
    for (let i = 0, ii = data.length; i < ii; i++) {
      dest[offset++] = data.charCodeAt(i) & 0xff;
    }
  } else {
    for (const num of data) {
      dest[offset++] = num & 0xff;
    }
  }
}
const OTF_HEADER_SIZE = 12;
const OTF_TABLE_ENTRY_SIZE = 16;
class OpenTypeFileBuilder {
  constructor(sfnt) {
    this.sfnt = sfnt;
    this.tables = Object.create(null);
  }
  static getSearchParams(entriesCount, entrySize) {
    let maxPower2 = 1,
      log2 = 0;
    while ((maxPower2 ^ entriesCount) > maxPower2) {
      maxPower2 <<= 1;
      log2++;
    }
    const searchRange = maxPower2 * entrySize;
    return {
      range: searchRange,
      entry: log2,
      rangeShift: entrySize * entriesCount - searchRange
    };
  }
  toArray() {
    let sfnt = this.sfnt;
    const tables = this.tables;
    const tablesNames = Object.keys(tables);
    tablesNames.sort();
    const numTables = tablesNames.length;
    let i, j, jj, table, tableName;
    let offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
    const tableOffsets = [offset];
    for (i = 0; i < numTables; i++) {
      table = tables[tablesNames[i]];
      const paddedLength = (table.length + 3 & ~3) >>> 0;
      offset += paddedLength;
      tableOffsets.push(offset);
    }
    const file = new Uint8Array(offset);
    for (i = 0; i < numTables; i++) {
      table = tables[tablesNames[i]];
      writeData(file, tableOffsets[i], table);
    }
    if (sfnt === "true") {
      sfnt = (0, _util.string32)(0x00010000);
    }
    file[0] = sfnt.charCodeAt(0) & 0xff;
    file[1] = sfnt.charCodeAt(1) & 0xff;
    file[2] = sfnt.charCodeAt(2) & 0xff;
    file[3] = sfnt.charCodeAt(3) & 0xff;
    writeInt16(file, 4, numTables);
    const searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
    writeInt16(file, 6, searchParams.range);
    writeInt16(file, 8, searchParams.entry);
    writeInt16(file, 10, searchParams.rangeShift);
    offset = OTF_HEADER_SIZE;
    for (i = 0; i < numTables; i++) {
      tableName = tablesNames[i];
      file[offset] = tableName.charCodeAt(0) & 0xff;
      file[offset + 1] = tableName.charCodeAt(1) & 0xff;
      file[offset + 2] = tableName.charCodeAt(2) & 0xff;
      file[offset + 3] = tableName.charCodeAt(3) & 0xff;
      let checksum = 0;
      for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
        const quad = (0, _core_utils.readUint32)(file, j);
        checksum = checksum + quad >>> 0;
      }
      writeInt32(file, offset + 4, checksum);
      writeInt32(file, offset + 8, tableOffsets[i]);
      writeInt32(file, offset + 12, tables[tableName].length);
      offset += OTF_TABLE_ENTRY_SIZE;
    }
    return file;
  }
  addTable(tag, data) {
    if (tag in this.tables) {
      throw new Error("Table " + tag + " already exists");
    }
    this.tables[tag] = data;
  }
}
exports.OpenTypeFileBuilder = OpenTypeFileBuilder;

/***/ }),
/* 46 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Type1Font = void 0;
var _cff_parser = __w_pdfjs_require__(33);
var _util = __w_pdfjs_require__(2);
var _fonts_utils = __w_pdfjs_require__(36);
var _core_utils = __w_pdfjs_require__(4);
var _stream = __w_pdfjs_require__(8);
var _type1_parser = __w_pdfjs_require__(47);
function findBlock(streamBytes, signature, startIndex) {
  const streamBytesLength = streamBytes.length;
  const signatureLength = signature.length;
  const scanLength = streamBytesLength - signatureLength;
  let i = startIndex,
    found = false;
  while (i < scanLength) {
    let j = 0;
    while (j < signatureLength && streamBytes[i + j] === signature[j]) {
      j++;
    }
    if (j >= signatureLength) {
      i += j;
      while (i < streamBytesLength && (0, _core_utils.isWhiteSpace)(streamBytes[i])) {
        i++;
      }
      found = true;
      break;
    }
    i++;
  }
  return {
    found,
    length: i
  };
}
function getHeaderBlock(stream, suggestedLength) {
  const EEXEC_SIGNATURE = [0x65, 0x65, 0x78, 0x65, 0x63];
  const streamStartPos = stream.pos;
  let headerBytes, headerBytesLength, block;
  try {
    headerBytes = stream.getBytes(suggestedLength);
    headerBytesLength = headerBytes.length;
  } catch (ex) {}
  if (headerBytesLength === suggestedLength) {
    block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length);
    if (block.found && block.length === suggestedLength) {
      return {
        stream: new _stream.Stream(headerBytes),
        length: suggestedLength
      };
    }
  }
  (0, _util.warn)('Invalid "Length1" property in Type1 font -- trying to recover.');
  stream.pos = streamStartPos;
  const SCAN_BLOCK_LENGTH = 2048;
  let actualLength;
  while (true) {
    const scanBytes = stream.peekBytes(SCAN_BLOCK_LENGTH);
    block = findBlock(scanBytes, EEXEC_SIGNATURE, 0);
    if (block.length === 0) {
      break;
    }
    stream.pos += block.length;
    if (block.found) {
      actualLength = stream.pos - streamStartPos;
      break;
    }
  }
  stream.pos = streamStartPos;
  if (actualLength) {
    return {
      stream: new _stream.Stream(stream.getBytes(actualLength)),
      length: actualLength
    };
  }
  (0, _util.warn)('Unable to recover "Length1" property in Type1 font -- using as is.');
  return {
    stream: new _stream.Stream(stream.getBytes(suggestedLength)),
    length: suggestedLength
  };
}
function getEexecBlock(stream, suggestedLength) {
  const eexecBytes = stream.getBytes();
  if (eexecBytes.length === 0) {
    throw new _util.FormatError("getEexecBlock - no font program found.");
  }
  return {
    stream: new _stream.Stream(eexecBytes),
    length: eexecBytes.length
  };
}
class Type1Font {
  constructor(name, file, properties) {
    const PFB_HEADER_SIZE = 6;
    let headerBlockLength = properties.length1;
    let eexecBlockLength = properties.length2;
    let pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
    const pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
    if (pfbHeaderPresent) {
      file.skip(PFB_HEADER_SIZE);
      headerBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
    }
    const headerBlock = getHeaderBlock(file, headerBlockLength);
    const headerBlockParser = new _type1_parser.Type1Parser(headerBlock.stream, false, _fonts_utils.SEAC_ANALYSIS_ENABLED);
    headerBlockParser.extractFontHeader(properties);
    if (pfbHeaderPresent) {
      pfbHeader = file.getBytes(PFB_HEADER_SIZE);
      eexecBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
    }
    const eexecBlock = getEexecBlock(file, eexecBlockLength);
    const eexecBlockParser = new _type1_parser.Type1Parser(eexecBlock.stream, true, _fonts_utils.SEAC_ANALYSIS_ENABLED);
    const data = eexecBlockParser.extractFontProgram(properties);
    for (const key in data.properties) {
      properties[key] = data.properties[key];
    }
    const charstrings = data.charstrings;
    const type2Charstrings = this.getType2Charstrings(charstrings);
    const subrs = this.getType2Subrs(data.subrs);
    this.charstrings = charstrings;
    this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties);
    this.seacs = this.getSeacs(data.charstrings);
  }
  get numGlyphs() {
    return this.charstrings.length + 1;
  }
  getCharset() {
    const charset = [".notdef"];
    for (const {
      glyphName
    } of this.charstrings) {
      charset.push(glyphName);
    }
    return charset;
  }
  getGlyphMapping(properties) {
    const charstrings = this.charstrings;
    if (properties.composite) {
      const charCodeToGlyphId = Object.create(null);
      for (let glyphId = 0, charstringsLen = charstrings.length; glyphId < charstringsLen; glyphId++) {
        const charCode = properties.cMap.charCodeOf(glyphId);
        charCodeToGlyphId[charCode] = glyphId + 1;
      }
      return charCodeToGlyphId;
    }
    const glyphNames = [".notdef"];
    let builtInEncoding, glyphId;
    for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
      glyphNames.push(charstrings[glyphId].glyphName);
    }
    const encoding = properties.builtInEncoding;
    if (encoding) {
      builtInEncoding = Object.create(null);
      for (const charCode in encoding) {
        glyphId = glyphNames.indexOf(encoding[charCode]);
        if (glyphId >= 0) {
          builtInEncoding[charCode] = glyphId;
        }
      }
    }
    return (0, _fonts_utils.type1FontGlyphMapping)(properties, builtInEncoding, glyphNames);
  }
  hasGlyphId(id) {
    if (id < 0 || id >= this.numGlyphs) {
      return false;
    }
    if (id === 0) {
      return true;
    }
    const glyph = this.charstrings[id - 1];
    return glyph.charstring.length > 0;
  }
  getSeacs(charstrings) {
    const seacMap = [];
    for (let i = 0, ii = charstrings.length; i < ii; i++) {
      const charstring = charstrings[i];
      if (charstring.seac) {
        seacMap[i + 1] = charstring.seac;
      }
    }
    return seacMap;
  }
  getType2Charstrings(type1Charstrings) {
    const type2Charstrings = [];
    for (const type1Charstring of type1Charstrings) {
      type2Charstrings.push(type1Charstring.charstring);
    }
    return type2Charstrings;
  }
  getType2Subrs(type1Subrs) {
    let bias = 0;
    const count = type1Subrs.length;
    if (count < 1133) {
      bias = 107;
    } else if (count < 33769) {
      bias = 1131;
    } else {
      bias = 32768;
    }
    const type2Subrs = [];
    let i;
    for (i = 0; i < bias; i++) {
      type2Subrs.push([0x0b]);
    }
    for (i = 0; i < count; i++) {
      type2Subrs.push(type1Subrs[i]);
    }
    return type2Subrs;
  }
  wrap(name, glyphs, charstrings, subrs, properties) {
    const cff = new _cff_parser.CFF();
    cff.header = new _cff_parser.CFFHeader(1, 0, 4, 4);
    cff.names = [name];
    const topDict = new _cff_parser.CFFTopDict();
    topDict.setByName("version", 391);
    topDict.setByName("Notice", 392);
    topDict.setByName("FullName", 393);
    topDict.setByName("FamilyName", 394);
    topDict.setByName("Weight", 395);
    topDict.setByName("Encoding", null);
    topDict.setByName("FontMatrix", properties.fontMatrix);
    topDict.setByName("FontBBox", properties.bbox);
    topDict.setByName("charset", null);
    topDict.setByName("CharStrings", null);
    topDict.setByName("Private", null);
    cff.topDict = topDict;
    const strings = new _cff_parser.CFFStrings();
    strings.add("Version 0.11");
    strings.add("See original notice");
    strings.add(name);
    strings.add(name);
    strings.add("Medium");
    cff.strings = strings;
    cff.globalSubrIndex = new _cff_parser.CFFIndex();
    const count = glyphs.length;
    const charsetArray = [".notdef"];
    let i, ii;
    for (i = 0; i < count; i++) {
      const glyphName = charstrings[i].glyphName;
      const index = _cff_parser.CFFStandardStrings.indexOf(glyphName);
      if (index === -1) {
        strings.add(glyphName);
      }
      charsetArray.push(glyphName);
    }
    cff.charset = new _cff_parser.CFFCharset(false, 0, charsetArray);
    const charStringsIndex = new _cff_parser.CFFIndex();
    charStringsIndex.add([0x8b, 0x0e]);
    for (i = 0; i < count; i++) {
      charStringsIndex.add(glyphs[i]);
    }
    cff.charStrings = charStringsIndex;
    const privateDict = new _cff_parser.CFFPrivateDict();
    privateDict.setByName("Subrs", null);
    const fields = ["BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StemSnapH", "StemSnapV", "BlueShift", "BlueFuzz", "BlueScale", "LanguageGroup", "ExpansionFactor", "ForceBold", "StdHW", "StdVW"];
    for (i = 0, ii = fields.length; i < ii; i++) {
      const field = fields[i];
      if (!(field in properties.privateData)) {
        continue;
      }
      const value = properties.privateData[field];
      if (Array.isArray(value)) {
        for (let j = value.length - 1; j > 0; j--) {
          value[j] -= value[j - 1];
        }
      }
      privateDict.setByName(field, value);
    }
    cff.topDict.privateDict = privateDict;
    const subrIndex = new _cff_parser.CFFIndex();
    for (i = 0, ii = subrs.length; i < ii; i++) {
      subrIndex.add(subrs[i]);
    }
    privateDict.subrsIndex = subrIndex;
    const compiler = new _cff_parser.CFFCompiler(cff);
    return compiler.compile();
  }
}
exports.Type1Font = Type1Font;

/***/ }),
/* 47 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Type1Parser = void 0;
var _encodings = __w_pdfjs_require__(35);
var _core_utils = __w_pdfjs_require__(4);
var _stream = __w_pdfjs_require__(8);
var _util = __w_pdfjs_require__(2);
const HINTING_ENABLED = false;
const COMMAND_MAP = {
  hstem: [1],
  vstem: [3],
  vmoveto: [4],
  rlineto: [5],
  hlineto: [6],
  vlineto: [7],
  rrcurveto: [8],
  callsubr: [10],
  flex: [12, 35],
  drop: [12, 18],
  endchar: [14],
  rmoveto: [21],
  hmoveto: [22],
  vhcurveto: [30],
  hvcurveto: [31]
};
class Type1CharString {
  constructor() {
    this.width = 0;
    this.lsb = 0;
    this.flexing = false;
    this.output = [];
    this.stack = [];
  }
  convert(encoded, subrs, seacAnalysisEnabled) {
    const count = encoded.length;
    let error = false;
    let wx, sbx, subrNumber;
    for (let i = 0; i < count; i++) {
      let value = encoded[i];
      if (value < 32) {
        if (value === 12) {
          value = (value << 8) + encoded[++i];
        }
        switch (value) {
          case 1:
            if (!HINTING_ENABLED) {
              this.stack = [];
              break;
            }
            error = this.executeCommand(2, COMMAND_MAP.hstem);
            break;
          case 3:
            if (!HINTING_ENABLED) {
              this.stack = [];
              break;
            }
            error = this.executeCommand(2, COMMAND_MAP.vstem);
            break;
          case 4:
            if (this.flexing) {
              if (this.stack.length < 1) {
                error = true;
                break;
              }
              const dy = this.stack.pop();
              this.stack.push(0, dy);
              break;
            }
            error = this.executeCommand(1, COMMAND_MAP.vmoveto);
            break;
          case 5:
            error = this.executeCommand(2, COMMAND_MAP.rlineto);
            break;
          case 6:
            error = this.executeCommand(1, COMMAND_MAP.hlineto);
            break;
          case 7:
            error = this.executeCommand(1, COMMAND_MAP.vlineto);
            break;
          case 8:
            error = this.executeCommand(6, COMMAND_MAP.rrcurveto);
            break;
          case 9:
            this.stack = [];
            break;
          case 10:
            if (this.stack.length < 1) {
              error = true;
              break;
            }
            subrNumber = this.stack.pop();
            if (!subrs[subrNumber]) {
              error = true;
              break;
            }
            error = this.convert(subrs[subrNumber], subrs, seacAnalysisEnabled);
            break;
          case 11:
            return error;
          case 13:
            if (this.stack.length < 2) {
              error = true;
              break;
            }
            wx = this.stack.pop();
            sbx = this.stack.pop();
            this.lsb = sbx;
            this.width = wx;
            this.stack.push(wx, sbx);
            error = this.executeCommand(2, COMMAND_MAP.hmoveto);
            break;
          case 14:
            this.output.push(COMMAND_MAP.endchar[0]);
            break;
          case 21:
            if (this.flexing) {
              break;
            }
            error = this.executeCommand(2, COMMAND_MAP.rmoveto);
            break;
          case 22:
            if (this.flexing) {
              this.stack.push(0);
              break;
            }
            error = this.executeCommand(1, COMMAND_MAP.hmoveto);
            break;
          case 30:
            error = this.executeCommand(4, COMMAND_MAP.vhcurveto);
            break;
          case 31:
            error = this.executeCommand(4, COMMAND_MAP.hvcurveto);
            break;
          case (12 << 8) + 0:
            this.stack = [];
            break;
          case (12 << 8) + 1:
            if (!HINTING_ENABLED) {
              this.stack = [];
              break;
            }
            error = this.executeCommand(2, COMMAND_MAP.vstem);
            break;
          case (12 << 8) + 2:
            if (!HINTING_ENABLED) {
              this.stack = [];
              break;
            }
            error = this.executeCommand(2, COMMAND_MAP.hstem);
            break;
          case (12 << 8) + 6:
            if (seacAnalysisEnabled) {
              const asb = this.stack.at(-5);
              this.seac = this.stack.splice(-4, 4);
              this.seac[0] += this.lsb - asb;
              error = this.executeCommand(0, COMMAND_MAP.endchar);
            } else {
              error = this.executeCommand(4, COMMAND_MAP.endchar);
            }
            break;
          case (12 << 8) + 7:
            if (this.stack.length < 4) {
              error = true;
              break;
            }
            this.stack.pop();
            wx = this.stack.pop();
            const sby = this.stack.pop();
            sbx = this.stack.pop();
            this.lsb = sbx;
            this.width = wx;
            this.stack.push(wx, sbx, sby);
            error = this.executeCommand(3, COMMAND_MAP.rmoveto);
            break;
          case (12 << 8) + 12:
            if (this.stack.length < 2) {
              error = true;
              break;
            }
            const num2 = this.stack.pop();
            const num1 = this.stack.pop();
            this.stack.push(num1 / num2);
            break;
          case (12 << 8) + 16:
            if (this.stack.length < 2) {
              error = true;
              break;
            }
            subrNumber = this.stack.pop();
            const numArgs = this.stack.pop();
            if (subrNumber === 0 && numArgs === 3) {
              const flexArgs = this.stack.splice(this.stack.length - 17, 17);
              this.stack.push(flexArgs[2] + flexArgs[0], flexArgs[3] + flexArgs[1], flexArgs[4], flexArgs[5], flexArgs[6], flexArgs[7], flexArgs[8], flexArgs[9], flexArgs[10], flexArgs[11], flexArgs[12], flexArgs[13], flexArgs[14]);
              error = this.executeCommand(13, COMMAND_MAP.flex, true);
              this.flexing = false;
              this.stack.push(flexArgs[15], flexArgs[16]);
            } else if (subrNumber === 1 && numArgs === 0) {
              this.flexing = true;
            }
            break;
          case (12 << 8) + 17:
            break;
          case (12 << 8) + 33:
            this.stack = [];
            break;
          default:
            (0, _util.warn)('Unknown type 1 charstring command of "' + value + '"');
            break;
        }
        if (error) {
          break;
        }
        continue;
      } else if (value <= 246) {
        value -= 139;
      } else if (value <= 250) {
        value = (value - 247) * 256 + encoded[++i] + 108;
      } else if (value <= 254) {
        value = -((value - 251) * 256) - encoded[++i] - 108;
      } else {
        value = (encoded[++i] & 0xff) << 24 | (encoded[++i] & 0xff) << 16 | (encoded[++i] & 0xff) << 8 | (encoded[++i] & 0xff) << 0;
      }
      this.stack.push(value);
    }
    return error;
  }
  executeCommand(howManyArgs, command, keepStack) {
    const stackLength = this.stack.length;
    if (howManyArgs > stackLength) {
      return true;
    }
    const start = stackLength - howManyArgs;
    for (let i = start; i < stackLength; i++) {
      let value = this.stack[i];
      if (Number.isInteger(value)) {
        this.output.push(28, value >> 8 & 0xff, value & 0xff);
      } else {
        value = 65536 * value | 0;
        this.output.push(255, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
      }
    }
    this.output.push(...command);
    if (keepStack) {
      this.stack.splice(start, howManyArgs);
    } else {
      this.stack.length = 0;
    }
    return false;
  }
}
const EEXEC_ENCRYPT_KEY = 55665;
const CHAR_STRS_ENCRYPT_KEY = 4330;
function isHexDigit(code) {
  return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
}
function decrypt(data, key, discardNumber) {
  if (discardNumber >= data.length) {
    return new Uint8Array(0);
  }
  const c1 = 52845,
    c2 = 22719;
  let r = key | 0,
    i,
    j;
  for (i = 0; i < discardNumber; i++) {
    r = (data[i] + r) * c1 + c2 & (1 << 16) - 1;
  }
  const count = data.length - discardNumber;
  const decrypted = new Uint8Array(count);
  for (i = discardNumber, j = 0; j < count; i++, j++) {
    const value = data[i];
    decrypted[j] = value ^ r >> 8;
    r = (value + r) * c1 + c2 & (1 << 16) - 1;
  }
  return decrypted;
}
function decryptAscii(data, key, discardNumber) {
  const c1 = 52845,
    c2 = 22719;
  let r = key | 0;
  const count = data.length,
    maybeLength = count >>> 1;
  const decrypted = new Uint8Array(maybeLength);
  let i, j;
  for (i = 0, j = 0; i < count; i++) {
    const digit1 = data[i];
    if (!isHexDigit(digit1)) {
      continue;
    }
    i++;
    let digit2;
    while (i < count && !isHexDigit(digit2 = data[i])) {
      i++;
    }
    if (i < count) {
      const value = parseInt(String.fromCharCode(digit1, digit2), 16);
      decrypted[j++] = value ^ r >> 8;
      r = (value + r) * c1 + c2 & (1 << 16) - 1;
    }
  }
  return decrypted.slice(discardNumber, j);
}
function isSpecial(c) {
  return c === 0x2f || c === 0x5b || c === 0x5d || c === 0x7b || c === 0x7d || c === 0x28 || c === 0x29;
}
class Type1Parser {
  constructor(stream, encrypted, seacAnalysisEnabled) {
    if (encrypted) {
      const data = stream.getBytes();
      const isBinary = !((isHexDigit(data[0]) || (0, _core_utils.isWhiteSpace)(data[0])) && isHexDigit(data[1]) && isHexDigit(data[2]) && isHexDigit(data[3]) && isHexDigit(data[4]) && isHexDigit(data[5]) && isHexDigit(data[6]) && isHexDigit(data[7]));
      stream = new _stream.Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) : decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
    }
    this.seacAnalysisEnabled = !!seacAnalysisEnabled;
    this.stream = stream;
    this.nextChar();
  }
  readNumberArray() {
    this.getToken();
    const array = [];
    while (true) {
      const token = this.getToken();
      if (token === null || token === "]" || token === "}") {
        break;
      }
      array.push(parseFloat(token || 0));
    }
    return array;
  }
  readNumber() {
    const token = this.getToken();
    return parseFloat(token || 0);
  }
  readInt() {
    const token = this.getToken();
    return parseInt(token || 0, 10) | 0;
  }
  readBoolean() {
    const token = this.getToken();
    return token === "true" ? 1 : 0;
  }
  nextChar() {
    return this.currentChar = this.stream.getByte();
  }
  prevChar() {
    this.stream.skip(-2);
    return this.currentChar = this.stream.getByte();
  }
  getToken() {
    let comment = false;
    let ch = this.currentChar;
    while (true) {
      if (ch === -1) {
        return null;
      }
      if (comment) {
        if (ch === 0x0a || ch === 0x0d) {
          comment = false;
        }
      } else if (ch === 0x25) {
        comment = true;
      } else if (!(0, _core_utils.isWhiteSpace)(ch)) {
        break;
      }
      ch = this.nextChar();
    }
    if (isSpecial(ch)) {
      this.nextChar();
      return String.fromCharCode(ch);
    }
    let token = "";
    do {
      token += String.fromCharCode(ch);
      ch = this.nextChar();
    } while (ch >= 0 && !(0, _core_utils.isWhiteSpace)(ch) && !isSpecial(ch));
    return token;
  }
  readCharStrings(bytes, lenIV) {
    if (lenIV === -1) {
      return bytes;
    }
    return decrypt(bytes, CHAR_STRS_ENCRYPT_KEY, lenIV);
  }
  extractFontProgram(properties) {
    const stream = this.stream;
    const subrs = [],
      charstrings = [];
    const privateData = Object.create(null);
    privateData.lenIV = 4;
    const program = {
      subrs: [],
      charstrings: [],
      properties: {
        privateData
      }
    };
    let token, length, data, lenIV;
    while ((token = this.getToken()) !== null) {
      if (token !== "/") {
        continue;
      }
      token = this.getToken();
      switch (token) {
        case "CharStrings":
          this.getToken();
          this.getToken();
          this.getToken();
          this.getToken();
          while (true) {
            token = this.getToken();
            if (token === null || token === "end") {
              break;
            }
            if (token !== "/") {
              continue;
            }
            const glyph = this.getToken();
            length = this.readInt();
            this.getToken();
            data = length > 0 ? stream.getBytes(length) : new Uint8Array(0);
            lenIV = program.properties.privateData.lenIV;
            const encoded = this.readCharStrings(data, lenIV);
            this.nextChar();
            token = this.getToken();
            if (token === "noaccess") {
              this.getToken();
            } else if (token === "/") {
              this.prevChar();
            }
            charstrings.push({
              glyph,
              encoded
            });
          }
          break;
        case "Subrs":
          this.readInt();
          this.getToken();
          while (this.getToken() === "dup") {
            const index = this.readInt();
            length = this.readInt();
            this.getToken();
            data = length > 0 ? stream.getBytes(length) : new Uint8Array(0);
            lenIV = program.properties.privateData.lenIV;
            const encoded = this.readCharStrings(data, lenIV);
            this.nextChar();
            token = this.getToken();
            if (token === "noaccess") {
              this.getToken();
            }
            subrs[index] = encoded;
          }
          break;
        case "BlueValues":
        case "OtherBlues":
        case "FamilyBlues":
        case "FamilyOtherBlues":
          const blueArray = this.readNumberArray();
          if (blueArray.length > 0 && blueArray.length % 2 === 0 && HINTING_ENABLED) {
            program.properties.privateData[token] = blueArray;
          }
          break;
        case "StemSnapH":
        case "StemSnapV":
          program.properties.privateData[token] = this.readNumberArray();
          break;
        case "StdHW":
        case "StdVW":
          program.properties.privateData[token] = this.readNumberArray()[0];
          break;
        case "BlueShift":
        case "lenIV":
        case "BlueFuzz":
        case "BlueScale":
        case "LanguageGroup":
          program.properties.privateData[token] = this.readNumber();
          break;
        case "ExpansionFactor":
          program.properties.privateData[token] = this.readNumber() || 0.06;
          break;
        case "ForceBold":
          program.properties.privateData[token] = this.readBoolean();
          break;
      }
    }
    for (const {
      encoded,
      glyph
    } of charstrings) {
      const charString = new Type1CharString();
      const error = charString.convert(encoded, subrs, this.seacAnalysisEnabled);
      let output = charString.output;
      if (error) {
        output = [14];
      }
      const charStringObject = {
        glyphName: glyph,
        charstring: output,
        width: charString.width,
        lsb: charString.lsb,
        seac: charString.seac
      };
      if (glyph === ".notdef") {
        program.charstrings.unshift(charStringObject);
      } else {
        program.charstrings.push(charStringObject);
      }
      if (properties.builtInEncoding) {
        const index = properties.builtInEncoding.indexOf(glyph);
        if (index > -1 && properties.widths[index] === undefined && index >= properties.firstChar && index <= properties.lastChar) {
          properties.widths[index] = charString.width;
        }
      }
    }
    return program;
  }
  extractFontHeader(properties) {
    let token;
    while ((token = this.getToken()) !== null) {
      if (token !== "/") {
        continue;
      }
      token = this.getToken();
      switch (token) {
        case "FontMatrix":
          const matrix = this.readNumberArray();
          properties.fontMatrix = matrix;
          break;
        case "Encoding":
          const encodingArg = this.getToken();
          let encoding;
          if (!/^\d+$/.test(encodingArg)) {
            encoding = (0, _encodings.getEncoding)(encodingArg);
          } else {
            encoding = [];
            const size = parseInt(encodingArg, 10) | 0;
            this.getToken();
            for (let j = 0; j < size; j++) {
              token = this.getToken();
              while (token !== "dup" && token !== "def") {
                token = this.getToken();
                if (token === null) {
                  return;
                }
              }
              if (token === "def") {
                break;
              }
              const index = this.readInt();
              this.getToken();
              const glyph = this.getToken();
              encoding[index] = glyph;
              this.getToken();
            }
          }
          properties.builtInEncoding = encoding;
          break;
        case "FontBBox":
          const fontBBox = this.readNumberArray();
          properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
          properties.descent = Math.min(fontBBox[1], fontBBox[3]);
          properties.ascentScaled = true;
          break;
      }
    }
  }
}
exports.Type1Parser = Type1Parser;

/***/ }),
/* 48 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Pattern = void 0;
exports.getTilingPatternIR = getTilingPatternIR;
var _util = __w_pdfjs_require__(2);
var _base_stream = __w_pdfjs_require__(5);
var _colorspace = __w_pdfjs_require__(12);
var _core_utils = __w_pdfjs_require__(4);
const ShadingType = {
  FUNCTION_BASED: 1,
  AXIAL: 2,
  RADIAL: 3,
  FREE_FORM_MESH: 4,
  LATTICE_FORM_MESH: 5,
  COONS_PATCH_MESH: 6,
  TENSOR_PATCH_MESH: 7
};
class Pattern {
  constructor() {
    (0, _util.unreachable)("Cannot initialize Pattern.");
  }
  static parseShading(shading, xref, res, handler, pdfFunctionFactory, localColorSpaceCache) {
    const dict = shading instanceof _base_stream.BaseStream ? shading.dict : shading;
    const type = dict.get("ShadingType");
    try {
      switch (type) {
        case ShadingType.AXIAL:
        case ShadingType.RADIAL:
          return new RadialAxialShading(dict, xref, res, pdfFunctionFactory, localColorSpaceCache);
        case ShadingType.FREE_FORM_MESH:
        case ShadingType.LATTICE_FORM_MESH:
        case ShadingType.COONS_PATCH_MESH:
        case ShadingType.TENSOR_PATCH_MESH:
          return new MeshShading(shading, xref, res, pdfFunctionFactory, localColorSpaceCache);
        default:
          throw new _util.FormatError("Unsupported ShadingType: " + type);
      }
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      handler.send("UnsupportedFeature", {
        featureId: _util.UNSUPPORTED_FEATURES.shadingPattern
      });
      (0, _util.warn)(ex);
      return new DummyShading();
    }
  }
}
exports.Pattern = Pattern;
class BaseShading {
  static get SMALL_NUMBER() {
    return (0, _util.shadow)(this, "SMALL_NUMBER", 1e-6);
  }
  constructor() {
    if (this.constructor === BaseShading) {
      (0, _util.unreachable)("Cannot initialize BaseShading.");
    }
  }
  getIR() {
    (0, _util.unreachable)("Abstract method `getIR` called.");
  }
}
class RadialAxialShading extends BaseShading {
  constructor(dict, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
    super();
    this.coordsArr = dict.getArray("Coords");
    this.shadingType = dict.get("ShadingType");
    const cs = _colorspace.ColorSpace.parse({
      cs: dict.getRaw("CS") || dict.getRaw("ColorSpace"),
      xref,
      resources,
      pdfFunctionFactory,
      localColorSpaceCache
    });
    const bbox = dict.getArray("BBox");
    if (Array.isArray(bbox) && bbox.length === 4) {
      this.bbox = _util.Util.normalizeRect(bbox);
    } else {
      this.bbox = null;
    }
    let t0 = 0.0,
      t1 = 1.0;
    if (dict.has("Domain")) {
      const domainArr = dict.getArray("Domain");
      t0 = domainArr[0];
      t1 = domainArr[1];
    }
    let extendStart = false,
      extendEnd = false;
    if (dict.has("Extend")) {
      const extendArr = dict.getArray("Extend");
      extendStart = extendArr[0];
      extendEnd = extendArr[1];
    }
    if (this.shadingType === ShadingType.RADIAL && (!extendStart || !extendEnd)) {
      const [x1, y1, r1, x2, y2, r2] = this.coordsArr;
      const distance = Math.hypot(x1 - x2, y1 - y2);
      if (r1 <= r2 + distance && r2 <= r1 + distance) {
        (0, _util.warn)("Unsupported radial gradient.");
      }
    }
    this.extendStart = extendStart;
    this.extendEnd = extendEnd;
    const fnObj = dict.getRaw("Function");
    const fn = pdfFunctionFactory.createFromArray(fnObj);
    const NUMBER_OF_SAMPLES = 10;
    const step = (t1 - t0) / NUMBER_OF_SAMPLES;
    const colorStops = this.colorStops = [];
    if (t0 >= t1 || step <= 0) {
      (0, _util.info)("Bad shading domain.");
      return;
    }
    const color = new Float32Array(cs.numComps),
      ratio = new Float32Array(1);
    let rgbColor;
    for (let i = 0; i <= NUMBER_OF_SAMPLES; i++) {
      ratio[0] = t0 + i * step;
      fn(ratio, 0, color, 0);
      rgbColor = cs.getRgb(color, 0);
      const cssColor = _util.Util.makeHexColor(rgbColor[0], rgbColor[1], rgbColor[2]);
      colorStops.push([i / NUMBER_OF_SAMPLES, cssColor]);
    }
    let background = "transparent";
    if (dict.has("Background")) {
      rgbColor = cs.getRgb(dict.get("Background"), 0);
      background = _util.Util.makeHexColor(rgbColor[0], rgbColor[1], rgbColor[2]);
    }
    if (!extendStart) {
      colorStops.unshift([0, background]);
      colorStops[1][0] += BaseShading.SMALL_NUMBER;
    }
    if (!extendEnd) {
      colorStops.at(-1)[0] -= BaseShading.SMALL_NUMBER;
      colorStops.push([1, background]);
    }
    this.colorStops = colorStops;
  }
  getIR() {
    const coordsArr = this.coordsArr;
    const shadingType = this.shadingType;
    let type, p0, p1, r0, r1;
    if (shadingType === ShadingType.AXIAL) {
      p0 = [coordsArr[0], coordsArr[1]];
      p1 = [coordsArr[2], coordsArr[3]];
      r0 = null;
      r1 = null;
      type = "axial";
    } else if (shadingType === ShadingType.RADIAL) {
      p0 = [coordsArr[0], coordsArr[1]];
      p1 = [coordsArr[3], coordsArr[4]];
      r0 = coordsArr[2];
      r1 = coordsArr[5];
      type = "radial";
    } else {
      (0, _util.unreachable)(`getPattern type unknown: ${shadingType}`);
    }
    return ["RadialAxial", type, this.bbox, this.colorStops, p0, p1, r0, r1];
  }
}
class MeshStreamReader {
  constructor(stream, context) {
    this.stream = stream;
    this.context = context;
    this.buffer = 0;
    this.bufferLength = 0;
    const numComps = context.numComps;
    this.tmpCompsBuf = new Float32Array(numComps);
    const csNumComps = context.colorSpace.numComps;
    this.tmpCsCompsBuf = context.colorFn ? new Float32Array(csNumComps) : this.tmpCompsBuf;
  }
  get hasData() {
    if (this.stream.end) {
      return this.stream.pos < this.stream.end;
    }
    if (this.bufferLength > 0) {
      return true;
    }
    const nextByte = this.stream.getByte();
    if (nextByte < 0) {
      return false;
    }
    this.buffer = nextByte;
    this.bufferLength = 8;
    return true;
  }
  readBits(n) {
    let buffer = this.buffer;
    let bufferLength = this.bufferLength;
    if (n === 32) {
      if (bufferLength === 0) {
        return (this.stream.getByte() << 24 | this.stream.getByte() << 16 | this.stream.getByte() << 8 | this.stream.getByte()) >>> 0;
      }
      buffer = buffer << 24 | this.stream.getByte() << 16 | this.stream.getByte() << 8 | this.stream.getByte();
      const nextByte = this.stream.getByte();
      this.buffer = nextByte & (1 << bufferLength) - 1;
      return (buffer << 8 - bufferLength | (nextByte & 0xff) >> bufferLength) >>> 0;
    }
    if (n === 8 && bufferLength === 0) {
      return this.stream.getByte();
    }
    while (bufferLength < n) {
      buffer = buffer << 8 | this.stream.getByte();
      bufferLength += 8;
    }
    bufferLength -= n;
    this.bufferLength = bufferLength;
    this.buffer = buffer & (1 << bufferLength) - 1;
    return buffer >> bufferLength;
  }
  align() {
    this.buffer = 0;
    this.bufferLength = 0;
  }
  readFlag() {
    return this.readBits(this.context.bitsPerFlag);
  }
  readCoordinate() {
    const bitsPerCoordinate = this.context.bitsPerCoordinate;
    const xi = this.readBits(bitsPerCoordinate);
    const yi = this.readBits(bitsPerCoordinate);
    const decode = this.context.decode;
    const scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) : 2.3283064365386963e-10;
    return [xi * scale * (decode[1] - decode[0]) + decode[0], yi * scale * (decode[3] - decode[2]) + decode[2]];
  }
  readComponents() {
    const numComps = this.context.numComps;
    const bitsPerComponent = this.context.bitsPerComponent;
    const scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) : 2.3283064365386963e-10;
    const decode = this.context.decode;
    const components = this.tmpCompsBuf;
    for (let i = 0, j = 4; i < numComps; i++, j += 2) {
      const ci = this.readBits(bitsPerComponent);
      components[i] = ci * scale * (decode[j + 1] - decode[j]) + decode[j];
    }
    const color = this.tmpCsCompsBuf;
    if (this.context.colorFn) {
      this.context.colorFn(components, 0, color, 0);
    }
    return this.context.colorSpace.getRgb(color, 0);
  }
}
const getB = function getBClosure() {
  function buildB(count) {
    const lut = [];
    for (let i = 0; i <= count; i++) {
      const t = i / count,
        t_ = 1 - t;
      lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_, 3 * t * t * t_, t * t * t]));
    }
    return lut;
  }
  const cache = [];
  return function (count) {
    if (!cache[count]) {
      cache[count] = buildB(count);
    }
    return cache[count];
  };
}();
class MeshShading extends BaseShading {
  static get MIN_SPLIT_PATCH_CHUNKS_AMOUNT() {
    return (0, _util.shadow)(this, "MIN_SPLIT_PATCH_CHUNKS_AMOUNT", 3);
  }
  static get MAX_SPLIT_PATCH_CHUNKS_AMOUNT() {
    return (0, _util.shadow)(this, "MAX_SPLIT_PATCH_CHUNKS_AMOUNT", 20);
  }
  static get TRIANGLE_DENSITY() {
    return (0, _util.shadow)(this, "TRIANGLE_DENSITY", 20);
  }
  constructor(stream, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
    super();
    if (!(stream instanceof _base_stream.BaseStream)) {
      throw new _util.FormatError("Mesh data is not a stream");
    }
    const dict = stream.dict;
    this.shadingType = dict.get("ShadingType");
    const bbox = dict.getArray("BBox");
    if (Array.isArray(bbox) && bbox.length === 4) {
      this.bbox = _util.Util.normalizeRect(bbox);
    } else {
      this.bbox = null;
    }
    const cs = _colorspace.ColorSpace.parse({
      cs: dict.getRaw("CS") || dict.getRaw("ColorSpace"),
      xref,
      resources,
      pdfFunctionFactory,
      localColorSpaceCache
    });
    this.background = dict.has("Background") ? cs.getRgb(dict.get("Background"), 0) : null;
    const fnObj = dict.getRaw("Function");
    const fn = fnObj ? pdfFunctionFactory.createFromArray(fnObj) : null;
    this.coords = [];
    this.colors = [];
    this.figures = [];
    const decodeContext = {
      bitsPerCoordinate: dict.get("BitsPerCoordinate"),
      bitsPerComponent: dict.get("BitsPerComponent"),
      bitsPerFlag: dict.get("BitsPerFlag"),
      decode: dict.getArray("Decode"),
      colorFn: fn,
      colorSpace: cs,
      numComps: fn ? 1 : cs.numComps
    };
    const reader = new MeshStreamReader(stream, decodeContext);
    let patchMesh = false;
    switch (this.shadingType) {
      case ShadingType.FREE_FORM_MESH:
        this._decodeType4Shading(reader);
        break;
      case ShadingType.LATTICE_FORM_MESH:
        const verticesPerRow = dict.get("VerticesPerRow") | 0;
        if (verticesPerRow < 2) {
          throw new _util.FormatError("Invalid VerticesPerRow");
        }
        this._decodeType5Shading(reader, verticesPerRow);
        break;
      case ShadingType.COONS_PATCH_MESH:
        this._decodeType6Shading(reader);
        patchMesh = true;
        break;
      case ShadingType.TENSOR_PATCH_MESH:
        this._decodeType7Shading(reader);
        patchMesh = true;
        break;
      default:
        (0, _util.unreachable)("Unsupported mesh type.");
        break;
    }
    if (patchMesh) {
      this._updateBounds();
      for (let i = 0, ii = this.figures.length; i < ii; i++) {
        this._buildFigureFromPatch(i);
      }
    }
    this._updateBounds();
    this._packData();
  }
  _decodeType4Shading(reader) {
    const coords = this.coords;
    const colors = this.colors;
    const operators = [];
    const ps = [];
    let verticesLeft = 0;
    while (reader.hasData) {
      const f = reader.readFlag();
      const coord = reader.readCoordinate();
      const color = reader.readComponents();
      if (verticesLeft === 0) {
        if (!(0 <= f && f <= 2)) {
          throw new _util.FormatError("Unknown type4 flag");
        }
        switch (f) {
          case 0:
            verticesLeft = 3;
            break;
          case 1:
            ps.push(ps.at(-2), ps.at(-1));
            verticesLeft = 1;
            break;
          case 2:
            ps.push(ps.at(-3), ps.at(-1));
            verticesLeft = 1;
            break;
        }
        operators.push(f);
      }
      ps.push(coords.length);
      coords.push(coord);
      colors.push(color);
      verticesLeft--;
      reader.align();
    }
    this.figures.push({
      type: "triangles",
      coords: new Int32Array(ps),
      colors: new Int32Array(ps)
    });
  }
  _decodeType5Shading(reader, verticesPerRow) {
    const coords = this.coords;
    const colors = this.colors;
    const ps = [];
    while (reader.hasData) {
      const coord = reader.readCoordinate();
      const color = reader.readComponents();
      ps.push(coords.length);
      coords.push(coord);
      colors.push(color);
    }
    this.figures.push({
      type: "lattice",
      coords: new Int32Array(ps),
      colors: new Int32Array(ps),
      verticesPerRow
    });
  }
  _decodeType6Shading(reader) {
    const coords = this.coords;
    const colors = this.colors;
    const ps = new Int32Array(16);
    const cs = new Int32Array(4);
    while (reader.hasData) {
      const f = reader.readFlag();
      if (!(0 <= f && f <= 3)) {
        throw new _util.FormatError("Unknown type6 flag");
      }
      const pi = coords.length;
      for (let i = 0, ii = f !== 0 ? 8 : 12; i < ii; i++) {
        coords.push(reader.readCoordinate());
      }
      const ci = colors.length;
      for (let i = 0, ii = f !== 0 ? 2 : 4; i < ii; i++) {
        colors.push(reader.readComponents());
      }
      let tmp1, tmp2, tmp3, tmp4;
      switch (f) {
        case 0:
          ps[12] = pi + 3;
          ps[13] = pi + 4;
          ps[14] = pi + 5;
          ps[15] = pi + 6;
          ps[8] = pi + 2;
          ps[11] = pi + 7;
          ps[4] = pi + 1;
          ps[7] = pi + 8;
          ps[0] = pi;
          ps[1] = pi + 11;
          ps[2] = pi + 10;
          ps[3] = pi + 9;
          cs[2] = ci + 1;
          cs[3] = ci + 2;
          cs[0] = ci;
          cs[1] = ci + 3;
          break;
        case 1:
          tmp1 = ps[12];
          tmp2 = ps[13];
          tmp3 = ps[14];
          tmp4 = ps[15];
          ps[12] = tmp4;
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = tmp3;
          ps[11] = pi + 3;
          ps[4] = tmp2;
          ps[7] = pi + 4;
          ps[0] = tmp1;
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          tmp1 = cs[2];
          tmp2 = cs[3];
          cs[2] = tmp2;
          cs[3] = ci;
          cs[0] = tmp1;
          cs[1] = ci + 1;
          break;
        case 2:
          tmp1 = ps[15];
          tmp2 = ps[11];
          ps[12] = ps[3];
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = ps[7];
          ps[11] = pi + 3;
          ps[4] = tmp2;
          ps[7] = pi + 4;
          ps[0] = tmp1;
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          tmp1 = cs[3];
          cs[2] = cs[1];
          cs[3] = ci;
          cs[0] = tmp1;
          cs[1] = ci + 1;
          break;
        case 3:
          ps[12] = ps[0];
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = ps[1];
          ps[11] = pi + 3;
          ps[4] = ps[2];
          ps[7] = pi + 4;
          ps[0] = ps[3];
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          cs[2] = cs[0];
          cs[3] = ci;
          cs[0] = cs[1];
          cs[1] = ci + 1;
          break;
      }
      ps[5] = coords.length;
      coords.push([(-4 * coords[ps[0]][0] - coords[ps[15]][0] + 6 * (coords[ps[4]][0] + coords[ps[1]][0]) - 2 * (coords[ps[12]][0] + coords[ps[3]][0]) + 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9, (-4 * coords[ps[0]][1] - coords[ps[15]][1] + 6 * (coords[ps[4]][1] + coords[ps[1]][1]) - 2 * (coords[ps[12]][1] + coords[ps[3]][1]) + 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9]);
      ps[6] = coords.length;
      coords.push([(-4 * coords[ps[3]][0] - coords[ps[12]][0] + 6 * (coords[ps[2]][0] + coords[ps[7]][0]) - 2 * (coords[ps[0]][0] + coords[ps[15]][0]) + 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9, (-4 * coords[ps[3]][1] - coords[ps[12]][1] + 6 * (coords[ps[2]][1] + coords[ps[7]][1]) - 2 * (coords[ps[0]][1] + coords[ps[15]][1]) + 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9]);
      ps[9] = coords.length;
      coords.push([(-4 * coords[ps[12]][0] - coords[ps[3]][0] + 6 * (coords[ps[8]][0] + coords[ps[13]][0]) - 2 * (coords[ps[0]][0] + coords[ps[15]][0]) + 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9, (-4 * coords[ps[12]][1] - coords[ps[3]][1] + 6 * (coords[ps[8]][1] + coords[ps[13]][1]) - 2 * (coords[ps[0]][1] + coords[ps[15]][1]) + 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9]);
      ps[10] = coords.length;
      coords.push([(-4 * coords[ps[15]][0] - coords[ps[0]][0] + 6 * (coords[ps[11]][0] + coords[ps[14]][0]) - 2 * (coords[ps[12]][0] + coords[ps[3]][0]) + 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9, (-4 * coords[ps[15]][1] - coords[ps[0]][1] + 6 * (coords[ps[11]][1] + coords[ps[14]][1]) - 2 * (coords[ps[12]][1] + coords[ps[3]][1]) + 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9]);
      this.figures.push({
        type: "patch",
        coords: new Int32Array(ps),
        colors: new Int32Array(cs)
      });
    }
  }
  _decodeType7Shading(reader) {
    const coords = this.coords;
    const colors = this.colors;
    const ps = new Int32Array(16);
    const cs = new Int32Array(4);
    while (reader.hasData) {
      const f = reader.readFlag();
      if (!(0 <= f && f <= 3)) {
        throw new _util.FormatError("Unknown type7 flag");
      }
      const pi = coords.length;
      for (let i = 0, ii = f !== 0 ? 12 : 16; i < ii; i++) {
        coords.push(reader.readCoordinate());
      }
      const ci = colors.length;
      for (let i = 0, ii = f !== 0 ? 2 : 4; i < ii; i++) {
        colors.push(reader.readComponents());
      }
      let tmp1, tmp2, tmp3, tmp4;
      switch (f) {
        case 0:
          ps[12] = pi + 3;
          ps[13] = pi + 4;
          ps[14] = pi + 5;
          ps[15] = pi + 6;
          ps[8] = pi + 2;
          ps[9] = pi + 13;
          ps[10] = pi + 14;
          ps[11] = pi + 7;
          ps[4] = pi + 1;
          ps[5] = pi + 12;
          ps[6] = pi + 15;
          ps[7] = pi + 8;
          ps[0] = pi;
          ps[1] = pi + 11;
          ps[2] = pi + 10;
          ps[3] = pi + 9;
          cs[2] = ci + 1;
          cs[3] = ci + 2;
          cs[0] = ci;
          cs[1] = ci + 3;
          break;
        case 1:
          tmp1 = ps[12];
          tmp2 = ps[13];
          tmp3 = ps[14];
          tmp4 = ps[15];
          ps[12] = tmp4;
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = tmp3;
          ps[9] = pi + 9;
          ps[10] = pi + 10;
          ps[11] = pi + 3;
          ps[4] = tmp2;
          ps[5] = pi + 8;
          ps[6] = pi + 11;
          ps[7] = pi + 4;
          ps[0] = tmp1;
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          tmp1 = cs[2];
          tmp2 = cs[3];
          cs[2] = tmp2;
          cs[3] = ci;
          cs[0] = tmp1;
          cs[1] = ci + 1;
          break;
        case 2:
          tmp1 = ps[15];
          tmp2 = ps[11];
          ps[12] = ps[3];
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = ps[7];
          ps[9] = pi + 9;
          ps[10] = pi + 10;
          ps[11] = pi + 3;
          ps[4] = tmp2;
          ps[5] = pi + 8;
          ps[6] = pi + 11;
          ps[7] = pi + 4;
          ps[0] = tmp1;
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          tmp1 = cs[3];
          cs[2] = cs[1];
          cs[3] = ci;
          cs[0] = tmp1;
          cs[1] = ci + 1;
          break;
        case 3:
          ps[12] = ps[0];
          ps[13] = pi + 0;
          ps[14] = pi + 1;
          ps[15] = pi + 2;
          ps[8] = ps[1];
          ps[9] = pi + 9;
          ps[10] = pi + 10;
          ps[11] = pi + 3;
          ps[4] = ps[2];
          ps[5] = pi + 8;
          ps[6] = pi + 11;
          ps[7] = pi + 4;
          ps[0] = ps[3];
          ps[1] = pi + 7;
          ps[2] = pi + 6;
          ps[3] = pi + 5;
          cs[2] = cs[0];
          cs[3] = ci;
          cs[0] = cs[1];
          cs[1] = ci + 1;
          break;
      }
      this.figures.push({
        type: "patch",
        coords: new Int32Array(ps),
        colors: new Int32Array(cs)
      });
    }
  }
  _buildFigureFromPatch(index) {
    const figure = this.figures[index];
    (0, _util.assert)(figure.type === "patch", "Unexpected patch mesh figure");
    const coords = this.coords,
      colors = this.colors;
    const pi = figure.coords;
    const ci = figure.colors;
    const figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0], coords[pi[12]][0], coords[pi[15]][0]);
    const figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1], coords[pi[12]][1], coords[pi[15]][1]);
    const figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0], coords[pi[12]][0], coords[pi[15]][0]);
    const figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1], coords[pi[12]][1], coords[pi[15]][1]);
    let splitXBy = Math.ceil((figureMaxX - figureMinX) * MeshShading.TRIANGLE_DENSITY / (this.bounds[2] - this.bounds[0]));
    splitXBy = Math.max(MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT, Math.min(MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));
    let splitYBy = Math.ceil((figureMaxY - figureMinY) * MeshShading.TRIANGLE_DENSITY / (this.bounds[3] - this.bounds[1]));
    splitYBy = Math.max(MeshShading.MIN_SPLIT_PATCH_CHUNKS_AMOUNT, Math.min(MeshShading.MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));
    const verticesPerRow = splitXBy + 1;
    const figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);
    const figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);
    let k = 0;
    const cl = new Uint8Array(3),
      cr = new Uint8Array(3);
    const c0 = colors[ci[0]],
      c1 = colors[ci[1]],
      c2 = colors[ci[2]],
      c3 = colors[ci[3]];
    const bRow = getB(splitYBy),
      bCol = getB(splitXBy);
    for (let row = 0; row <= splitYBy; row++) {
      cl[0] = (c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy | 0;
      cl[1] = (c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy | 0;
      cl[2] = (c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy | 0;
      cr[0] = (c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy | 0;
      cr[1] = (c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy | 0;
      cr[2] = (c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy | 0;
      for (let col = 0; col <= splitXBy; col++, k++) {
        if ((row === 0 || row === splitYBy) && (col === 0 || col === splitXBy)) {
          continue;
        }
        let x = 0,
          y = 0;
        let q = 0;
        for (let i = 0; i <= 3; i++) {
          for (let j = 0; j <= 3; j++, q++) {
            const m = bRow[row][i] * bCol[col][j];
            x += coords[pi[q]][0] * m;
            y += coords[pi[q]][1] * m;
          }
        }
        figureCoords[k] = coords.length;
        coords.push([x, y]);
        figureColors[k] = colors.length;
        const newColor = new Uint8Array(3);
        newColor[0] = (cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy | 0;
        newColor[1] = (cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy | 0;
        newColor[2] = (cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy | 0;
        colors.push(newColor);
      }
    }
    figureCoords[0] = pi[0];
    figureColors[0] = ci[0];
    figureCoords[splitXBy] = pi[3];
    figureColors[splitXBy] = ci[1];
    figureCoords[verticesPerRow * splitYBy] = pi[12];
    figureColors[verticesPerRow * splitYBy] = ci[2];
    figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];
    figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];
    this.figures[index] = {
      type: "lattice",
      coords: figureCoords,
      colors: figureColors,
      verticesPerRow
    };
  }
  _updateBounds() {
    let minX = this.coords[0][0],
      minY = this.coords[0][1],
      maxX = minX,
      maxY = minY;
    for (let i = 1, ii = this.coords.length; i < ii; i++) {
      const x = this.coords[i][0],
        y = this.coords[i][1];
      minX = minX > x ? x : minX;
      minY = minY > y ? y : minY;
      maxX = maxX < x ? x : maxX;
      maxY = maxY < y ? y : maxY;
    }
    this.bounds = [minX, minY, maxX, maxY];
  }
  _packData() {
    let i, ii, j, jj;
    const coords = this.coords;
    const coordsPacked = new Float32Array(coords.length * 2);
    for (i = 0, j = 0, ii = coords.length; i < ii; i++) {
      const xy = coords[i];
      coordsPacked[j++] = xy[0];
      coordsPacked[j++] = xy[1];
    }
    this.coords = coordsPacked;
    const colors = this.colors;
    const colorsPacked = new Uint8Array(colors.length * 3);
    for (i = 0, j = 0, ii = colors.length; i < ii; i++) {
      const c = colors[i];
      colorsPacked[j++] = c[0];
      colorsPacked[j++] = c[1];
      colorsPacked[j++] = c[2];
    }
    this.colors = colorsPacked;
    const figures = this.figures;
    for (i = 0, ii = figures.length; i < ii; i++) {
      const figure = figures[i],
        ps = figure.coords,
        cs = figure.colors;
      for (j = 0, jj = ps.length; j < jj; j++) {
        ps[j] *= 2;
        cs[j] *= 3;
      }
    }
  }
  getIR() {
    return ["Mesh", this.shadingType, this.coords, this.colors, this.figures, this.bounds, this.bbox, this.background];
  }
}
class DummyShading extends BaseShading {
  getIR() {
    return ["Dummy"];
  }
}
function getTilingPatternIR(operatorList, dict, color) {
  const matrix = dict.getArray("Matrix");
  const bbox = _util.Util.normalizeRect(dict.getArray("BBox"));
  const xstep = dict.get("XStep");
  const ystep = dict.get("YStep");
  const paintType = dict.get("PaintType");
  const tilingType = dict.get("TilingType");
  if (bbox[2] - bbox[0] === 0 || bbox[3] - bbox[1] === 0) {
    throw new _util.FormatError(`Invalid getTilingPatternIR /BBox array: [${bbox}].`);
  }
  return ["TilingPattern", color, operatorList, matrix, bbox, xstep, ystep, paintType, tilingType];
}

/***/ }),
/* 49 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.getXfaFontDict = getXfaFontDict;
exports.getXfaFontName = getXfaFontName;
var _calibri_factors = __w_pdfjs_require__(50);
var _primitives = __w_pdfjs_require__(3);
var _helvetica_factors = __w_pdfjs_require__(51);
var _liberationsans_widths = __w_pdfjs_require__(52);
var _myriadpro_factors = __w_pdfjs_require__(53);
var _segoeui_factors = __w_pdfjs_require__(54);
var _core_utils = __w_pdfjs_require__(4);
var _fonts_utils = __w_pdfjs_require__(36);
const getXFAFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
  t["MyriadPro-Regular"] = t["PdfJS-Fallback-Regular"] = {
    name: "LiberationSans-Regular",
    factors: _myriadpro_factors.MyriadProRegularFactors,
    baseWidths: _liberationsans_widths.LiberationSansRegularWidths,
    baseMapping: _liberationsans_widths.LiberationSansRegularMapping,
    metrics: _myriadpro_factors.MyriadProRegularMetrics
  };
  t["MyriadPro-Bold"] = t["PdfJS-Fallback-Bold"] = {
    name: "LiberationSans-Bold",
    factors: _myriadpro_factors.MyriadProBoldFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldMapping,
    metrics: _myriadpro_factors.MyriadProBoldMetrics
  };
  t["MyriadPro-It"] = t["MyriadPro-Italic"] = t["PdfJS-Fallback-Italic"] = {
    name: "LiberationSans-Italic",
    factors: _myriadpro_factors.MyriadProItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansItalicMapping,
    metrics: _myriadpro_factors.MyriadProItalicMetrics
  };
  t["MyriadPro-BoldIt"] = t["MyriadPro-BoldItalic"] = t["PdfJS-Fallback-BoldItalic"] = {
    name: "LiberationSans-BoldItalic",
    factors: _myriadpro_factors.MyriadProBoldItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldItalicMapping,
    metrics: _myriadpro_factors.MyriadProBoldItalicMetrics
  };
  t.ArialMT = t.Arial = t["Arial-Regular"] = {
    name: "LiberationSans-Regular",
    baseWidths: _liberationsans_widths.LiberationSansRegularWidths,
    baseMapping: _liberationsans_widths.LiberationSansRegularMapping
  };
  t["Arial-BoldMT"] = t["Arial-Bold"] = {
    name: "LiberationSans-Bold",
    baseWidths: _liberationsans_widths.LiberationSansBoldWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldMapping
  };
  t["Arial-ItalicMT"] = t["Arial-Italic"] = {
    name: "LiberationSans-Italic",
    baseWidths: _liberationsans_widths.LiberationSansItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansItalicMapping
  };
  t["Arial-BoldItalicMT"] = t["Arial-BoldItalic"] = {
    name: "LiberationSans-BoldItalic",
    baseWidths: _liberationsans_widths.LiberationSansBoldItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldItalicMapping
  };
  t["Calibri-Regular"] = {
    name: "LiberationSans-Regular",
    factors: _calibri_factors.CalibriRegularFactors,
    baseWidths: _liberationsans_widths.LiberationSansRegularWidths,
    baseMapping: _liberationsans_widths.LiberationSansRegularMapping,
    metrics: _calibri_factors.CalibriRegularMetrics
  };
  t["Calibri-Bold"] = {
    name: "LiberationSans-Bold",
    factors: _calibri_factors.CalibriBoldFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldMapping,
    metrics: _calibri_factors.CalibriBoldMetrics
  };
  t["Calibri-Italic"] = {
    name: "LiberationSans-Italic",
    factors: _calibri_factors.CalibriItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansItalicMapping,
    metrics: _calibri_factors.CalibriItalicMetrics
  };
  t["Calibri-BoldItalic"] = {
    name: "LiberationSans-BoldItalic",
    factors: _calibri_factors.CalibriBoldItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldItalicMapping,
    metrics: _calibri_factors.CalibriBoldItalicMetrics
  };
  t["Segoeui-Regular"] = {
    name: "LiberationSans-Regular",
    factors: _segoeui_factors.SegoeuiRegularFactors,
    baseWidths: _liberationsans_widths.LiberationSansRegularWidths,
    baseMapping: _liberationsans_widths.LiberationSansRegularMapping,
    metrics: _segoeui_factors.SegoeuiRegularMetrics
  };
  t["Segoeui-Bold"] = {
    name: "LiberationSans-Bold",
    factors: _segoeui_factors.SegoeuiBoldFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldMapping,
    metrics: _segoeui_factors.SegoeuiBoldMetrics
  };
  t["Segoeui-Italic"] = {
    name: "LiberationSans-Italic",
    factors: _segoeui_factors.SegoeuiItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansItalicMapping,
    metrics: _segoeui_factors.SegoeuiItalicMetrics
  };
  t["Segoeui-BoldItalic"] = {
    name: "LiberationSans-BoldItalic",
    factors: _segoeui_factors.SegoeuiBoldItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldItalicMapping,
    metrics: _segoeui_factors.SegoeuiBoldItalicMetrics
  };
  t["Helvetica-Regular"] = t.Helvetica = {
    name: "LiberationSans-Regular",
    factors: _helvetica_factors.HelveticaRegularFactors,
    baseWidths: _liberationsans_widths.LiberationSansRegularWidths,
    baseMapping: _liberationsans_widths.LiberationSansRegularMapping,
    metrics: _helvetica_factors.HelveticaRegularMetrics
  };
  t["Helvetica-Bold"] = {
    name: "LiberationSans-Bold",
    factors: _helvetica_factors.HelveticaBoldFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldMapping,
    metrics: _helvetica_factors.HelveticaBoldMetrics
  };
  t["Helvetica-Italic"] = {
    name: "LiberationSans-Italic",
    factors: _helvetica_factors.HelveticaItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansItalicMapping,
    metrics: _helvetica_factors.HelveticaItalicMetrics
  };
  t["Helvetica-BoldItalic"] = {
    name: "LiberationSans-BoldItalic",
    factors: _helvetica_factors.HelveticaBoldItalicFactors,
    baseWidths: _liberationsans_widths.LiberationSansBoldItalicWidths,
    baseMapping: _liberationsans_widths.LiberationSansBoldItalicMapping,
    metrics: _helvetica_factors.HelveticaBoldItalicMetrics
  };
});
function getXfaFontName(name) {
  const fontName = (0, _fonts_utils.normalizeFontName)(name);
  const fontMap = getXFAFontMap();
  return fontMap[fontName];
}
function getXfaFontWidths(name) {
  const info = getXfaFontName(name);
  if (!info) {
    return null;
  }
  const {
    baseWidths,
    baseMapping,
    factors
  } = info;
  let rescaledBaseWidths;
  if (!factors) {
    rescaledBaseWidths = baseWidths;
  } else {
    rescaledBaseWidths = baseWidths.map((w, i) => w * factors[i]);
  }
  let currentCode = -2;
  let currentArray;
  const newWidths = [];
  for (const [unicode, glyphIndex] of baseMapping.map((charUnicode, index) => [charUnicode, index]).sort(([unicode1], [unicode2]) => unicode1 - unicode2)) {
    if (unicode === -1) {
      continue;
    }
    if (unicode === currentCode + 1) {
      currentArray.push(rescaledBaseWidths[glyphIndex]);
      currentCode += 1;
    } else {
      currentCode = unicode;
      currentArray = [rescaledBaseWidths[glyphIndex]];
      newWidths.push(unicode, currentArray);
    }
  }
  return newWidths;
}
function getXfaFontDict(name) {
  const widths = getXfaFontWidths(name);
  const dict = new _primitives.Dict(null);
  dict.set("BaseFont", _primitives.Name.get(name));
  dict.set("Type", _primitives.Name.get("Font"));
  dict.set("Subtype", _primitives.Name.get("CIDFontType2"));
  dict.set("Encoding", _primitives.Name.get("Identity-H"));
  dict.set("CIDToGIDMap", _primitives.Name.get("Identity"));
  dict.set("W", widths);
  dict.set("FirstChar", widths[0]);
  dict.set("LastChar", widths.at(-2) + widths.at(-1).length - 1);
  const descriptor = new _primitives.Dict(null);
  dict.set("FontDescriptor", descriptor);
  const systemInfo = new _primitives.Dict(null);
  systemInfo.set("Ordering", "Identity");
  systemInfo.set("Registry", "Adobe");
  systemInfo.set("Supplement", 0);
  dict.set("CIDSystemInfo", systemInfo);
  return dict;
}

/***/ }),
/* 50 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.CalibriRegularMetrics = exports.CalibriRegularFactors = exports.CalibriItalicMetrics = exports.CalibriItalicFactors = exports.CalibriBoldMetrics = exports.CalibriBoldItalicMetrics = exports.CalibriBoldItalicFactors = exports.CalibriBoldFactors = void 0;
const CalibriBoldFactors = [1.3877, 1, 1, 1, 0.97801, 0.92482, 0.89552, 0.91133, 0.81988, 0.97566, 0.98152, 0.93548, 0.93548, 1.2798, 0.85284, 0.92794, 1, 0.96134, 1.54657, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.82845, 0.82845, 0.85284, 0.85284, 0.85284, 0.75859, 0.92138, 0.83908, 0.7762, 0.73293, 0.87289, 0.73133, 0.7514, 0.81921, 0.87356, 0.95958, 0.59526, 0.75727, 0.69225, 1.04924, 0.9121, 0.86943, 0.79795, 0.88198, 0.77958, 0.70864, 0.81055, 0.90399, 0.88653, 0.96017, 0.82577, 0.77892, 0.78257, 0.97507, 1.54657, 0.97507, 0.85284, 0.89552, 0.90176, 0.88762, 0.8785, 0.75241, 0.8785, 0.90518, 0.95015, 0.77618, 0.8785, 0.88401, 0.91916, 0.86304, 0.88401, 0.91488, 0.8785, 0.8801, 0.8785, 0.8785, 0.91343, 0.7173, 1.04106, 0.8785, 0.85075, 0.95794, 0.82616, 0.85162, 0.79492, 0.88331, 1.69808, 0.88331, 0.85284, 0.97801, 0.89552, 0.91133, 0.89552, 0.91133, 1.7801, 0.89552, 1.24487, 1.13254, 1.12401, 0.96839, 0.85284, 0.68787, 0.70645, 0.85592, 0.90747, 1.01466, 1.0088, 0.90323, 1, 1.07463, 1, 0.91056, 0.75806, 1.19118, 0.96839, 0.78864, 0.82845, 0.84133, 0.75859, 0.83908, 0.83908, 0.83908, 0.83908, 0.83908, 0.83908, 0.77539, 0.73293, 0.73133, 0.73133, 0.73133, 0.73133, 0.95958, 0.95958, 0.95958, 0.95958, 0.88506, 0.9121, 0.86943, 0.86943, 0.86943, 0.86943, 0.86943, 0.85284, 0.87508, 0.90399, 0.90399, 0.90399, 0.90399, 0.77892, 0.79795, 0.90807, 0.88762, 0.88762, 0.88762, 0.88762, 0.88762, 0.88762, 0.8715, 0.75241, 0.90518, 0.90518, 0.90518, 0.90518, 0.88401, 0.88401, 0.88401, 0.88401, 0.8785, 0.8785, 0.8801, 0.8801, 0.8801, 0.8801, 0.8801, 0.90747, 0.89049, 0.8785, 0.8785, 0.8785, 0.8785, 0.85162, 0.8785, 0.85162, 0.83908, 0.88762, 0.83908, 0.88762, 0.83908, 0.88762, 0.73293, 0.75241, 0.73293, 0.75241, 0.73293, 0.75241, 0.73293, 0.75241, 0.87289, 0.83016, 0.88506, 0.93125, 0.73133, 0.90518, 0.73133, 0.90518, 0.73133, 0.90518, 0.73133, 0.90518, 0.73133, 0.90518, 0.81921, 0.77618, 0.81921, 0.77618, 0.81921, 0.77618, 1, 1, 0.87356, 0.8785, 0.91075, 0.89608, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.76229, 0.90167, 0.59526, 0.91916, 1, 1, 0.86304, 0.69225, 0.88401, 1, 1, 0.70424, 0.79468, 0.91926, 0.88175, 0.70823, 0.94903, 0.9121, 0.8785, 1, 1, 0.9121, 0.8785, 0.87802, 0.88656, 0.8785, 0.86943, 0.8801, 0.86943, 0.8801, 0.86943, 0.8801, 0.87402, 0.89291, 0.77958, 0.91343, 1, 1, 0.77958, 0.91343, 0.70864, 0.7173, 0.70864, 0.7173, 0.70864, 0.7173, 0.70864, 0.7173, 1, 1, 0.81055, 0.75841, 0.81055, 1.06452, 0.90399, 0.8785, 0.90399, 0.8785, 0.90399, 0.8785, 0.90399, 0.8785, 0.90399, 0.8785, 0.90399, 0.8785, 0.96017, 0.95794, 0.77892, 0.85162, 0.77892, 0.78257, 0.79492, 0.78257, 0.79492, 0.78257, 0.79492, 0.9297, 0.56892, 0.83908, 0.88762, 0.77539, 0.8715, 0.87508, 0.89049, 1, 1, 0.81055, 1.04106, 1.20528, 1.20528, 1, 1.15543, 0.70674, 0.98387, 0.94721, 1.33431, 1.45894, 0.95161, 1.06303, 0.83908, 0.80352, 0.57184, 0.6965, 0.56289, 0.82001, 0.56029, 0.81235, 1.02988, 0.83908, 0.7762, 0.68156, 0.80367, 0.73133, 0.78257, 0.87356, 0.86943, 0.95958, 0.75727, 0.89019, 1.04924, 0.9121, 0.7648, 0.86943, 0.87356, 0.79795, 0.78275, 0.81055, 0.77892, 0.9762, 0.82577, 0.99819, 0.84896, 0.95958, 0.77892, 0.96108, 1.01407, 0.89049, 1.02988, 0.94211, 0.96108, 0.8936, 0.84021, 0.87842, 0.96399, 0.79109, 0.89049, 1.00813, 1.02988, 0.86077, 0.87445, 0.92099, 0.84723, 0.86513, 0.8801, 0.75638, 0.85714, 0.78216, 0.79586, 0.87965, 0.94211, 0.97747, 0.78287, 0.97926, 0.84971, 1.02988, 0.94211, 0.8801, 0.94211, 0.84971, 0.73133, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90264, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90518, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90548, 1, 1, 1, 1, 1, 1, 0.96017, 0.95794, 0.96017, 0.95794, 0.96017, 0.95794, 0.77892, 0.85162, 1, 1, 0.89552, 0.90527, 1, 0.90363, 0.92794, 0.92794, 0.92794, 0.92794, 0.87012, 0.87012, 0.87012, 0.89552, 0.89552, 1.42259, 0.71143, 1.06152, 1, 1, 1.03372, 1.03372, 0.97171, 1.4956, 2.2807, 0.93835, 0.83406, 0.91133, 0.84107, 0.91133, 1, 1, 1, 0.72021, 1, 1.23108, 0.83489, 0.88525, 0.88525, 0.81499, 0.90527, 1.81055, 0.90527, 1.81055, 1.31006, 1.53711, 0.94434, 1.08696, 1, 0.95018, 0.77192, 0.85284, 0.90747, 1.17534, 0.69825, 0.9716, 1.37077, 0.90747, 0.90747, 0.85356, 0.90747, 0.90747, 1.44947, 0.85284, 0.8941, 0.8941, 0.70572, 0.8, 0.70572, 0.70572, 0.70572, 0.70572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.99862, 0.99862, 1, 1, 1, 1, 1, 1.08004, 0.91027, 1, 1, 1, 0.99862, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90727, 0.90727, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.CalibriBoldFactors = CalibriBoldFactors;
const CalibriBoldMetrics = {
  lineHeight: 1.2207,
  lineGap: 0.2207
};
exports.CalibriBoldMetrics = CalibriBoldMetrics;
const CalibriBoldItalicFactors = [1.3877, 1, 1, 1, 0.97801, 0.92482, 0.89552, 0.91133, 0.81988, 0.97566, 0.98152, 0.93548, 0.93548, 1.2798, 0.85284, 0.92794, 1, 0.96134, 1.56239, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.82845, 0.82845, 0.85284, 0.85284, 0.85284, 0.75859, 0.92138, 0.83908, 0.7762, 0.71805, 0.87289, 0.73133, 0.7514, 0.81921, 0.87356, 0.95958, 0.59526, 0.75727, 0.69225, 1.04924, 0.90872, 0.85938, 0.79795, 0.87068, 0.77958, 0.69766, 0.81055, 0.90399, 0.88653, 0.96068, 0.82577, 0.77892, 0.78257, 0.97507, 1.529, 0.97507, 0.85284, 0.89552, 0.90176, 0.94908, 0.86411, 0.74012, 0.86411, 0.88323, 0.95015, 0.86411, 0.86331, 0.88401, 0.91916, 0.86304, 0.88401, 0.9039, 0.86331, 0.86331, 0.86411, 0.86411, 0.90464, 0.70852, 1.04106, 0.86331, 0.84372, 0.95794, 0.82616, 0.84548, 0.79492, 0.88331, 1.69808, 0.88331, 0.85284, 0.97801, 0.89552, 0.91133, 0.89552, 0.91133, 1.7801, 0.89552, 1.24487, 1.13254, 1.19129, 0.96839, 0.85284, 0.68787, 0.70645, 0.85592, 0.90747, 1.01466, 1.0088, 0.90323, 1, 1.07463, 1, 0.91056, 0.75806, 1.19118, 0.96839, 0.78864, 0.82845, 0.84133, 0.75859, 0.83908, 0.83908, 0.83908, 0.83908, 0.83908, 0.83908, 0.77539, 0.71805, 0.73133, 0.73133, 0.73133, 0.73133, 0.95958, 0.95958, 0.95958, 0.95958, 0.88506, 0.90872, 0.85938, 0.85938, 0.85938, 0.85938, 0.85938, 0.85284, 0.87068, 0.90399, 0.90399, 0.90399, 0.90399, 0.77892, 0.79795, 0.90807, 0.94908, 0.94908, 0.94908, 0.94908, 0.94908, 0.94908, 0.85887, 0.74012, 0.88323, 0.88323, 0.88323, 0.88323, 0.88401, 0.88401, 0.88401, 0.88401, 0.8785, 0.86331, 0.86331, 0.86331, 0.86331, 0.86331, 0.86331, 0.90747, 0.89049, 0.86331, 0.86331, 0.86331, 0.86331, 0.84548, 0.86411, 0.84548, 0.83908, 0.94908, 0.83908, 0.94908, 0.83908, 0.94908, 0.71805, 0.74012, 0.71805, 0.74012, 0.71805, 0.74012, 0.71805, 0.74012, 0.87289, 0.79538, 0.88506, 0.92726, 0.73133, 0.88323, 0.73133, 0.88323, 0.73133, 0.88323, 0.73133, 0.88323, 0.73133, 0.88323, 0.81921, 0.86411, 0.81921, 0.86411, 0.81921, 0.86411, 1, 1, 0.87356, 0.86331, 0.91075, 0.8777, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.95958, 0.88401, 0.76467, 0.90167, 0.59526, 0.91916, 1, 1, 0.86304, 0.69225, 0.88401, 1, 1, 0.70424, 0.77312, 0.91926, 0.88175, 0.70823, 0.94903, 0.90872, 0.86331, 1, 1, 0.90872, 0.86331, 0.86906, 0.88116, 0.86331, 0.85938, 0.86331, 0.85938, 0.86331, 0.85938, 0.86331, 0.87402, 0.86549, 0.77958, 0.90464, 1, 1, 0.77958, 0.90464, 0.69766, 0.70852, 0.69766, 0.70852, 0.69766, 0.70852, 0.69766, 0.70852, 1, 1, 0.81055, 0.75841, 0.81055, 1.06452, 0.90399, 0.86331, 0.90399, 0.86331, 0.90399, 0.86331, 0.90399, 0.86331, 0.90399, 0.86331, 0.90399, 0.86331, 0.96068, 0.95794, 0.77892, 0.84548, 0.77892, 0.78257, 0.79492, 0.78257, 0.79492, 0.78257, 0.79492, 0.9297, 0.56892, 0.83908, 0.94908, 0.77539, 0.85887, 0.87068, 0.89049, 1, 1, 0.81055, 1.04106, 1.20528, 1.20528, 1, 1.15543, 0.70088, 0.98387, 0.94721, 1.33431, 1.45894, 0.95161, 1.48387, 0.83908, 0.80352, 0.57118, 0.6965, 0.56347, 0.79179, 0.55853, 0.80346, 1.02988, 0.83908, 0.7762, 0.67174, 0.86036, 0.73133, 0.78257, 0.87356, 0.86441, 0.95958, 0.75727, 0.89019, 1.04924, 0.90872, 0.74889, 0.85938, 0.87891, 0.79795, 0.7957, 0.81055, 0.77892, 0.97447, 0.82577, 0.97466, 0.87179, 0.95958, 0.77892, 0.94252, 0.95612, 0.8753, 1.02988, 0.92733, 0.94252, 0.87411, 0.84021, 0.8728, 0.95612, 0.74081, 0.8753, 1.02189, 1.02988, 0.84814, 0.87445, 0.91822, 0.84723, 0.85668, 0.86331, 0.81344, 0.87581, 0.76422, 0.82046, 0.96057, 0.92733, 0.99375, 0.78022, 0.95452, 0.86015, 1.02988, 0.92733, 0.86331, 0.92733, 0.86015, 0.73133, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90631, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.88323, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.85174, 1, 1, 1, 1, 1, 1, 0.96068, 0.95794, 0.96068, 0.95794, 0.96068, 0.95794, 0.77892, 0.84548, 1, 1, 0.89552, 0.90527, 1, 0.90363, 0.92794, 0.92794, 0.92794, 0.89807, 0.87012, 0.87012, 0.87012, 0.89552, 0.89552, 1.42259, 0.71094, 1.06152, 1, 1, 1.03372, 1.03372, 0.97171, 1.4956, 2.2807, 0.92972, 0.83406, 0.91133, 0.83326, 0.91133, 1, 1, 1, 0.72021, 1, 1.23108, 0.83489, 0.88525, 0.88525, 0.81499, 0.90616, 1.81055, 0.90527, 1.81055, 1.3107, 1.53711, 0.94434, 1.08696, 1, 0.95018, 0.77192, 0.85284, 0.90747, 1.17534, 0.69825, 0.9716, 1.37077, 0.90747, 0.90747, 0.85356, 0.90747, 0.90747, 1.44947, 0.85284, 0.8941, 0.8941, 0.70572, 0.8, 0.70572, 0.70572, 0.70572, 0.70572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.99862, 0.99862, 1, 1, 1, 1, 1, 1.08004, 0.91027, 1, 1, 1, 0.99862, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90727, 0.90727, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.CalibriBoldItalicFactors = CalibriBoldItalicFactors;
const CalibriBoldItalicMetrics = {
  lineHeight: 1.2207,
  lineGap: 0.2207
};
exports.CalibriBoldItalicMetrics = CalibriBoldItalicMetrics;
const CalibriItalicFactors = [1.3877, 1, 1, 1, 1.17223, 1.1293, 0.89552, 0.91133, 0.80395, 1.02269, 1.15601, 0.91056, 0.91056, 1.2798, 0.85284, 0.89807, 1, 0.90861, 1.39543, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.96309, 0.96309, 0.85284, 0.85284, 0.85284, 0.83319, 0.88071, 0.8675, 0.81552, 0.72346, 0.85193, 0.73206, 0.7522, 0.81105, 0.86275, 0.90685, 0.6377, 0.77892, 0.75593, 1.02638, 0.89249, 0.84118, 0.77452, 0.85374, 0.75186, 0.67789, 0.79776, 0.88844, 0.85066, 0.94309, 0.77818, 0.7306, 0.76659, 1.10369, 1.38313, 1.10369, 1.06139, 0.89552, 0.8739, 0.9245, 0.9245, 0.83203, 0.9245, 0.85865, 1.09842, 0.9245, 0.9245, 1.03297, 1.07692, 0.90918, 1.03297, 0.94959, 0.9245, 0.92274, 0.9245, 0.9245, 1.02933, 0.77832, 1.20562, 0.9245, 0.8916, 0.98986, 0.86621, 0.89453, 0.79004, 0.94152, 1.77256, 0.94152, 0.85284, 0.97801, 0.89552, 0.91133, 0.89552, 0.91133, 1.91729, 0.89552, 1.17889, 1.13254, 1.16359, 0.92098, 0.85284, 0.68787, 0.71353, 0.84737, 0.90747, 1.0088, 1.0044, 0.87683, 1, 1.09091, 1, 0.92229, 0.739, 1.15642, 0.92098, 0.76288, 0.80504, 0.80972, 0.75859, 0.8675, 0.8675, 0.8675, 0.8675, 0.8675, 0.8675, 0.76318, 0.72346, 0.73206, 0.73206, 0.73206, 0.73206, 0.90685, 0.90685, 0.90685, 0.90685, 0.86477, 0.89249, 0.84118, 0.84118, 0.84118, 0.84118, 0.84118, 0.85284, 0.84557, 0.88844, 0.88844, 0.88844, 0.88844, 0.7306, 0.77452, 0.86331, 0.9245, 0.9245, 0.9245, 0.9245, 0.9245, 0.9245, 0.84843, 0.83203, 0.85865, 0.85865, 0.85865, 0.85865, 0.82601, 0.82601, 0.82601, 0.82601, 0.94469, 0.9245, 0.92274, 0.92274, 0.92274, 0.92274, 0.92274, 0.90747, 0.86651, 0.9245, 0.9245, 0.9245, 0.9245, 0.89453, 0.9245, 0.89453, 0.8675, 0.9245, 0.8675, 0.9245, 0.8675, 0.9245, 0.72346, 0.83203, 0.72346, 0.83203, 0.72346, 0.83203, 0.72346, 0.83203, 0.85193, 0.8875, 0.86477, 0.99034, 0.73206, 0.85865, 0.73206, 0.85865, 0.73206, 0.85865, 0.73206, 0.85865, 0.73206, 0.85865, 0.81105, 0.9245, 0.81105, 0.9245, 0.81105, 0.9245, 1, 1, 0.86275, 0.9245, 0.90872, 0.93591, 0.90685, 0.82601, 0.90685, 0.82601, 0.90685, 0.82601, 0.90685, 1.03297, 0.90685, 0.82601, 0.77896, 1.05611, 0.6377, 1.07692, 1, 1, 0.90918, 0.75593, 1.03297, 1, 1, 0.76032, 0.9375, 0.98156, 0.93407, 0.77261, 1.11429, 0.89249, 0.9245, 1, 1, 0.89249, 0.9245, 0.92534, 0.86698, 0.9245, 0.84118, 0.92274, 0.84118, 0.92274, 0.84118, 0.92274, 0.8667, 0.86291, 0.75186, 1.02933, 1, 1, 0.75186, 1.02933, 0.67789, 0.77832, 0.67789, 0.77832, 0.67789, 0.77832, 0.67789, 0.77832, 1, 1, 0.79776, 0.97655, 0.79776, 1.23023, 0.88844, 0.9245, 0.88844, 0.9245, 0.88844, 0.9245, 0.88844, 0.9245, 0.88844, 0.9245, 0.88844, 0.9245, 0.94309, 0.98986, 0.7306, 0.89453, 0.7306, 0.76659, 0.79004, 0.76659, 0.79004, 0.76659, 0.79004, 1.09231, 0.54873, 0.8675, 0.9245, 0.76318, 0.84843, 0.84557, 0.86651, 1, 1, 0.79776, 1.20562, 1.18622, 1.18622, 1, 1.1437, 0.67009, 0.96334, 0.93695, 1.35191, 1.40909, 0.95161, 1.48387, 0.8675, 0.90861, 0.6192, 0.7363, 0.64824, 0.82411, 0.56321, 0.85696, 1.23516, 0.8675, 0.81552, 0.7286, 0.84134, 0.73206, 0.76659, 0.86275, 0.84369, 0.90685, 0.77892, 0.85871, 1.02638, 0.89249, 0.75828, 0.84118, 0.85984, 0.77452, 0.76466, 0.79776, 0.7306, 0.90782, 0.77818, 0.903, 0.87291, 0.90685, 0.7306, 0.99058, 1.03667, 0.94635, 1.23516, 0.9849, 0.99058, 0.92393, 0.8916, 0.942, 1.03667, 0.75026, 0.94635, 1.0297, 1.23516, 0.90918, 0.94048, 0.98217, 0.89746, 0.84153, 0.92274, 0.82507, 0.88832, 0.84438, 0.88178, 1.03525, 0.9849, 1.00225, 0.78086, 0.97248, 0.89404, 1.23516, 0.9849, 0.92274, 0.9849, 0.89404, 0.73206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.89693, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.85865, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.90933, 1, 1, 1, 1, 1, 1, 0.94309, 0.98986, 0.94309, 0.98986, 0.94309, 0.98986, 0.7306, 0.89453, 1, 1, 0.89552, 0.90527, 1, 0.90186, 1.12308, 1.12308, 1.12308, 1.12308, 1.2566, 1.2566, 1.2566, 0.89552, 0.89552, 1.42259, 0.68994, 1.03809, 1, 1, 1.0176, 1.0176, 1.11523, 1.4956, 2.01462, 0.97858, 0.82616, 0.91133, 0.83437, 0.91133, 1, 1, 1, 0.70508, 1, 1.23108, 0.79801, 0.84426, 0.84426, 0.774, 0.90572, 1.81055, 0.90749, 1.81055, 1.28809, 1.55469, 0.94434, 1.07806, 1, 0.97094, 0.7589, 0.85284, 0.90747, 1.19658, 0.69825, 0.97622, 1.33512, 0.90747, 0.90747, 0.85284, 0.90747, 0.90747, 1.44947, 0.85284, 0.8941, 0.8941, 0.70572, 0.8, 0.70572, 0.70572, 0.70572, 0.70572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.99862, 0.99862, 1, 1, 1, 1, 1, 1.0336, 0.91027, 1, 1, 1, 0.99862, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05859, 1.05859, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.CalibriItalicFactors = CalibriItalicFactors;
const CalibriItalicMetrics = {
  lineHeight: 1.2207,
  lineGap: 0.2207
};
exports.CalibriItalicMetrics = CalibriItalicMetrics;
const CalibriRegularFactors = [1.3877, 1, 1, 1, 1.17223, 1.1293, 0.89552, 0.91133, 0.80395, 1.02269, 1.15601, 0.91056, 0.91056, 1.2798, 0.85284, 0.89807, 1, 0.90861, 1.39016, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.91133, 0.96309, 0.96309, 0.85284, 0.85284, 0.85284, 0.83319, 0.88071, 0.8675, 0.81552, 0.73834, 0.85193, 0.73206, 0.7522, 0.81105, 0.86275, 0.90685, 0.6377, 0.77892, 0.75593, 1.02638, 0.89385, 0.85122, 0.77452, 0.86503, 0.75186, 0.68887, 0.79776, 0.88844, 0.85066, 0.94258, 0.77818, 0.7306, 0.76659, 1.10369, 1.39016, 1.10369, 1.06139, 0.89552, 0.8739, 0.86128, 0.94469, 0.8457, 0.94469, 0.89464, 1.09842, 0.84636, 0.94469, 1.03297, 1.07692, 0.90918, 1.03297, 0.95897, 0.94469, 0.9482, 0.94469, 0.94469, 1.04692, 0.78223, 1.20562, 0.94469, 0.90332, 0.98986, 0.86621, 0.90527, 0.79004, 0.94152, 1.77256, 0.94152, 0.85284, 0.97801, 0.89552, 0.91133, 0.89552, 0.91133, 1.91729, 0.89552, 1.17889, 1.13254, 1.08707, 0.92098, 0.85284, 0.68787, 0.71353, 0.84737, 0.90747, 1.0088, 1.0044, 0.87683, 1, 1.09091, 1, 0.92229, 0.739, 1.15642, 0.92098, 0.76288, 0.80504, 0.80972, 0.75859, 0.8675, 0.8675, 0.8675, 0.8675, 0.8675, 0.8675, 0.76318, 0.73834, 0.73206, 0.73206, 0.73206, 0.73206, 0.90685, 0.90685, 0.90685, 0.90685, 0.86477, 0.89385, 0.85122, 0.85122, 0.85122, 0.85122, 0.85122, 0.85284, 0.85311, 0.88844, 0.88844, 0.88844, 0.88844, 0.7306, 0.77452, 0.86331, 0.86128, 0.86128, 0.86128, 0.86128, 0.86128, 0.86128, 0.8693, 0.8457, 0.89464, 0.89464, 0.89464, 0.89464, 0.82601, 0.82601, 0.82601, 0.82601, 0.94469, 0.94469, 0.9482, 0.9482, 0.9482, 0.9482, 0.9482, 0.90747, 0.86651, 0.94469, 0.94469, 0.94469, 0.94469, 0.90527, 0.94469, 0.90527, 0.8675, 0.86128, 0.8675, 0.86128, 0.8675, 0.86128, 0.73834, 0.8457, 0.73834, 0.8457, 0.73834, 0.8457, 0.73834, 0.8457, 0.85193, 0.92454, 0.86477, 0.9921, 0.73206, 0.89464, 0.73206, 0.89464, 0.73206, 0.89464, 0.73206, 0.89464, 0.73206, 0.89464, 0.81105, 0.84636, 0.81105, 0.84636, 0.81105, 0.84636, 1, 1, 0.86275, 0.94469, 0.90872, 0.95786, 0.90685, 0.82601, 0.90685, 0.82601, 0.90685, 0.82601, 0.90685, 1.03297, 0.90685, 0.82601, 0.77741, 1.05611, 0.6377, 1.07692, 1, 1, 0.90918, 0.75593, 1.03297, 1, 1, 0.76032, 0.90452, 0.98156, 1.11842, 0.77261, 1.11429, 0.89385, 0.94469, 1, 1, 0.89385, 0.94469, 0.95877, 0.86901, 0.94469, 0.85122, 0.9482, 0.85122, 0.9482, 0.85122, 0.9482, 0.8667, 0.90016, 0.75186, 1.04692, 1, 1, 0.75186, 1.04692, 0.68887, 0.78223, 0.68887, 0.78223, 0.68887, 0.78223, 0.68887, 0.78223, 1, 1, 0.79776, 0.92188, 0.79776, 1.23023, 0.88844, 0.94469, 0.88844, 0.94469, 0.88844, 0.94469, 0.88844, 0.94469, 0.88844, 0.94469, 0.88844, 0.94469, 0.94258, 0.98986, 0.7306, 0.90527, 0.7306, 0.76659, 0.79004, 0.76659, 0.79004, 0.76659, 0.79004, 1.09231, 0.54873, 0.8675, 0.86128, 0.76318, 0.8693, 0.85311, 0.86651, 1, 1, 0.79776, 1.20562, 1.18622, 1.18622, 1, 1.1437, 0.67742, 0.96334, 0.93695, 1.35191, 1.40909, 0.95161, 1.48387, 0.86686, 0.90861, 0.62267, 0.74359, 0.65649, 0.85498, 0.56963, 0.88254, 1.23516, 0.8675, 0.81552, 0.75443, 0.84503, 0.73206, 0.76659, 0.86275, 0.85122, 0.90685, 0.77892, 0.85746, 1.02638, 0.89385, 0.75657, 0.85122, 0.86275, 0.77452, 0.74171, 0.79776, 0.7306, 0.95165, 0.77818, 0.89772, 0.88831, 0.90685, 0.7306, 0.98142, 1.02191, 0.96576, 1.23516, 0.99018, 0.98142, 0.9236, 0.89258, 0.94035, 1.02191, 0.78848, 0.96576, 0.9561, 1.23516, 0.90918, 0.92578, 0.95424, 0.89746, 0.83969, 0.9482, 0.80113, 0.89442, 0.85208, 0.86155, 0.98022, 0.99018, 1.00452, 0.81209, 0.99247, 0.89181, 1.23516, 0.99018, 0.9482, 0.99018, 0.89181, 0.73206, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.88844, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.89464, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.96766, 1, 1, 1, 1, 1, 1, 0.94258, 0.98986, 0.94258, 0.98986, 0.94258, 0.98986, 0.7306, 0.90527, 1, 1, 0.89552, 0.90527, 1, 0.90186, 1.12308, 1.12308, 1.12308, 1.12308, 1.2566, 1.2566, 1.2566, 0.89552, 0.89552, 1.42259, 0.69043, 1.03809, 1, 1, 1.0176, 1.0176, 1.11523, 1.4956, 2.01462, 0.99331, 0.82616, 0.91133, 0.84286, 0.91133, 1, 1, 1, 0.70508, 1, 1.23108, 0.79801, 0.84426, 0.84426, 0.774, 0.90527, 1.81055, 0.90527, 1.81055, 1.28809, 1.55469, 0.94434, 1.07806, 1, 0.97094, 0.7589, 0.85284, 0.90747, 1.19658, 0.69825, 0.97622, 1.33512, 0.90747, 0.90747, 0.85356, 0.90747, 0.90747, 1.44947, 0.85284, 0.8941, 0.8941, 0.70572, 0.8, 0.70572, 0.70572, 0.70572, 0.70572, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.99862, 0.99862, 1, 1, 1, 1, 1, 1.0336, 0.91027, 1, 1, 1, 0.99862, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05859, 1.05859, 1, 1, 1, 1.07185, 0.99413, 0.96334, 1.08065, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.CalibriRegularFactors = CalibriRegularFactors;
const CalibriRegularMetrics = {
  lineHeight: 1.2207,
  lineGap: 0.2207
};
exports.CalibriRegularMetrics = CalibriRegularMetrics;

/***/ }),
/* 51 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.HelveticaRegularMetrics = exports.HelveticaRegularFactors = exports.HelveticaItalicMetrics = exports.HelveticaItalicFactors = exports.HelveticaBoldMetrics = exports.HelveticaBoldItalicMetrics = exports.HelveticaBoldItalicFactors = exports.HelveticaBoldFactors = void 0;
const HelveticaBoldFactors = [0.76116, 1, 1, 1.0006, 0.99998, 0.99974, 0.99973, 0.99973, 0.99982, 0.99977, 1.00087, 0.99998, 0.99998, 0.99959, 1.00003, 1.0006, 0.99998, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99998, 1, 1.00003, 1.00003, 1.00003, 1.00026, 0.9999, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00026, 1.00022, 0.99977, 1.0006, 0.99973, 0.99977, 1.00026, 0.99999, 0.99977, 1.00022, 1.00001, 1.00022, 0.99977, 1.00001, 1.00026, 0.99977, 1.00001, 1.00016, 1.00001, 1.00001, 1.00026, 0.99998, 1.0006, 0.99998, 1.00003, 0.99973, 0.99998, 0.99973, 1.00026, 0.99973, 1.00026, 0.99973, 0.99998, 1.00026, 1.00026, 1.0006, 1.0006, 0.99973, 1.0006, 0.99982, 1.00026, 1.00026, 1.00026, 1.00026, 0.99959, 0.99973, 0.99998, 1.00026, 0.99973, 1.00022, 0.99973, 0.99973, 1, 0.99959, 1.00077, 0.99959, 1.00003, 0.99998, 0.99973, 0.99973, 0.99973, 0.99973, 1.00077, 0.99973, 0.99998, 1.00025, 0.99968, 0.99973, 1.00003, 1.00025, 0.60299, 1.00024, 1.06409, 1, 1, 0.99998, 1, 0.99973, 1.0006, 0.99998, 1, 0.99936, 0.99973, 1.00002, 1.00002, 1.00002, 1.00026, 0.99977, 0.99977, 0.99977, 0.99977, 0.99977, 0.99977, 1, 0.99977, 1.00001, 1.00001, 1.00001, 1.00001, 1.0006, 1.0006, 1.0006, 1.0006, 0.99977, 0.99977, 1.00022, 1.00022, 1.00022, 1.00022, 1.00022, 1.00003, 1.00022, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00001, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99982, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.06409, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 0.99973, 1.00026, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 1.03374, 0.99977, 1.00026, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.00042, 0.99973, 0.99973, 1.0006, 0.99977, 0.99973, 0.99973, 1.00026, 1.0006, 1.00026, 1.0006, 1.00026, 1.03828, 1.00026, 0.99999, 1.00026, 1.0006, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.9993, 0.9998, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1, 1.00016, 0.99977, 0.99959, 0.99977, 0.99959, 0.99977, 0.99959, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00026, 0.99998, 1.00026, 0.8121, 1.00026, 0.99998, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 1.00016, 1.00022, 1.00001, 0.99973, 1.00001, 1.00026, 1, 1.00026, 1, 1.00026, 1, 1.0006, 0.99973, 0.99977, 0.99973, 1, 0.99982, 1.00022, 1.00026, 1.00001, 0.99973, 1.00026, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 1.00034, 0.99977, 1, 0.99997, 1.00026, 1.00078, 1.00036, 0.99973, 1.00013, 1.0006, 0.99977, 0.99977, 0.99988, 0.85148, 1.00001, 1.00026, 0.99977, 1.00022, 1.0006, 0.99977, 1.00001, 0.99999, 0.99977, 1.00069, 1.00022, 0.99977, 1.00001, 0.99984, 1.00026, 1.00001, 1.00024, 1.00001, 0.9999, 1, 1.0006, 1.00001, 1.00041, 0.99962, 1.00026, 1.0006, 0.99995, 1.00041, 0.99942, 0.99973, 0.99927, 1.00082, 0.99902, 1.00026, 1.00087, 1.0006, 1.00069, 0.99973, 0.99867, 0.99973, 0.9993, 1.00026, 1.00049, 1.00056, 1, 0.99988, 0.99935, 0.99995, 0.99954, 1.00055, 0.99945, 1.00032, 1.0006, 0.99995, 1.00026, 0.99995, 1.00032, 1.00001, 1.00008, 0.99971, 1.00019, 0.9994, 1.00001, 1.0006, 1.00044, 0.99973, 1.00023, 1.00047, 1, 0.99942, 0.99561, 0.99989, 1.00035, 0.99977, 1.00035, 0.99977, 1.00019, 0.99944, 1.00001, 1.00021, 0.99926, 1.00035, 1.00035, 0.99942, 1.00048, 0.99999, 0.99977, 1.00022, 1.00035, 1.00001, 0.99977, 1.00026, 0.99989, 1.00057, 1.00001, 0.99936, 1.00052, 1.00012, 0.99996, 1.00043, 1, 1.00035, 0.9994, 0.99976, 1.00035, 0.99973, 1.00052, 1.00041, 1.00119, 1.00037, 0.99973, 1.00002, 0.99986, 1.00041, 1.00041, 0.99902, 0.9996, 1.00034, 0.99999, 1.00026, 0.99999, 1.00026, 0.99973, 1.00052, 0.99973, 1, 0.99973, 1.00041, 1.00075, 0.9994, 1.0003, 0.99999, 1, 1.00041, 0.99955, 1, 0.99915, 0.99973, 0.99973, 1.00026, 1.00119, 0.99955, 0.99973, 1.0006, 0.99911, 1.0006, 1.00026, 0.99972, 1.00026, 0.99902, 1.00041, 0.99973, 0.99999, 1, 1, 1.00038, 1.0005, 1.00016, 1.00022, 1.00016, 1.00022, 1.00016, 1.00022, 1.00001, 0.99973, 1, 1, 0.99973, 1, 1, 0.99955, 1.0006, 1.0006, 1.0006, 1.0006, 1, 1, 1, 0.99973, 0.99973, 0.99972, 1, 1, 1.00106, 0.99999, 0.99998, 0.99998, 0.99999, 0.99998, 1.66475, 1, 0.99973, 0.99973, 1.00023, 0.99973, 0.99971, 1.00047, 1.00023, 1, 0.99991, 0.99984, 1.00002, 1.00002, 1.00002, 1.00002, 1, 1, 1, 1, 1, 1, 1, 0.99972, 1, 1.20985, 1.39713, 1.00003, 1.00031, 1.00015, 1, 0.99561, 1.00027, 1.00031, 1.00031, 0.99915, 1.00031, 1.00031, 0.99999, 1.00003, 0.99999, 0.99999, 1.41144, 1.6, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.40579, 1.40579, 1.36625, 0.99999, 1, 0.99861, 0.99861, 1, 1.00026, 1.00026, 1.00026, 1.00026, 0.99972, 0.99999, 0.99999, 0.99999, 0.99999, 1.40483, 1, 0.99977, 1.00054, 1, 1, 0.99953, 0.99962, 1.00042, 0.9995, 1, 1, 1, 1, 1, 1, 1, 1, 0.99998, 0.99998, 0.99998, 0.99998, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.HelveticaBoldFactors = HelveticaBoldFactors;
const HelveticaBoldMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.HelveticaBoldMetrics = HelveticaBoldMetrics;
const HelveticaBoldItalicFactors = [0.76116, 1, 1, 1.0006, 0.99998, 0.99974, 0.99973, 0.99973, 0.99982, 0.99977, 1.00087, 0.99998, 0.99998, 0.99959, 1.00003, 1.0006, 0.99998, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99998, 1, 1.00003, 1.00003, 1.00003, 1.00026, 0.9999, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00026, 1.00022, 0.99977, 1.0006, 0.99973, 0.99977, 1.00026, 0.99999, 0.99977, 1.00022, 1.00001, 1.00022, 0.99977, 1.00001, 1.00026, 0.99977, 1.00001, 1.00016, 1.00001, 1.00001, 1.00026, 0.99998, 1.0006, 0.99998, 1.00003, 0.99973, 0.99998, 0.99973, 1.00026, 0.99973, 1.00026, 0.99973, 0.99998, 1.00026, 1.00026, 1.0006, 1.0006, 0.99973, 1.0006, 0.99982, 1.00026, 1.00026, 1.00026, 1.00026, 0.99959, 0.99973, 0.99998, 1.00026, 0.99973, 1.00022, 0.99973, 0.99973, 1, 0.99959, 1.00077, 0.99959, 1.00003, 0.99998, 0.99973, 0.99973, 0.99973, 0.99973, 1.00077, 0.99973, 0.99998, 1.00025, 0.99968, 0.99973, 1.00003, 1.00025, 0.60299, 1.00024, 1.06409, 1, 1, 0.99998, 1, 0.99973, 1.0006, 0.99998, 1, 0.99936, 0.99973, 1.00002, 1.00002, 1.00002, 1.00026, 0.99977, 0.99977, 0.99977, 0.99977, 0.99977, 0.99977, 1, 0.99977, 1.00001, 1.00001, 1.00001, 1.00001, 1.0006, 1.0006, 1.0006, 1.0006, 0.99977, 0.99977, 1.00022, 1.00022, 1.00022, 1.00022, 1.00022, 1.00003, 1.00022, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00001, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99982, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 1.06409, 1.00026, 1.00026, 1.00026, 1.00026, 1.00026, 0.99973, 1.00026, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 1.0044, 0.99977, 1.00026, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 0.99971, 0.99973, 0.99973, 1.0006, 0.99977, 0.99973, 0.99973, 1.00026, 1.0006, 1.00026, 1.0006, 1.00026, 1.01011, 1.00026, 0.99999, 1.00026, 1.0006, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.9993, 0.9998, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1.00022, 1.00026, 1, 1.00016, 0.99977, 0.99959, 0.99977, 0.99959, 0.99977, 0.99959, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00026, 0.99998, 1.00026, 0.8121, 1.00026, 0.99998, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 0.99977, 1.00026, 1.00016, 1.00022, 1.00001, 0.99973, 1.00001, 1.00026, 1, 1.00026, 1, 1.00026, 1, 1.0006, 0.99973, 0.99977, 0.99973, 1, 0.99982, 1.00022, 1.00026, 1.00001, 0.99973, 1.00026, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99977, 1, 1, 1.00026, 0.99969, 0.99972, 0.99981, 0.9998, 1.0006, 0.99977, 0.99977, 1.00022, 0.91155, 1.00001, 1.00026, 0.99977, 1.00022, 1.0006, 0.99977, 1.00001, 0.99999, 0.99977, 0.99966, 1.00022, 1.00032, 1.00001, 0.99944, 1.00026, 1.00001, 0.99968, 1.00001, 1.00047, 1, 1.0006, 1.00001, 0.99981, 1.00101, 1.00026, 1.0006, 0.99948, 0.99981, 1.00064, 0.99973, 0.99942, 1.00101, 1.00061, 1.00026, 1.00069, 1.0006, 1.00014, 0.99973, 1.01322, 0.99973, 1.00065, 1.00026, 1.00012, 0.99923, 1, 1.00064, 1.00076, 0.99948, 1.00055, 1.00063, 1.00007, 0.99943, 1.0006, 0.99948, 1.00026, 0.99948, 0.99943, 1.00001, 1.00001, 1.00029, 1.00038, 1.00035, 1.00001, 1.0006, 1.0006, 0.99973, 0.99978, 1.00001, 1.00057, 0.99989, 0.99967, 0.99964, 0.99967, 0.99977, 0.99999, 0.99977, 1.00038, 0.99977, 1.00001, 0.99973, 1.00066, 0.99967, 0.99967, 1.00041, 0.99998, 0.99999, 0.99977, 1.00022, 0.99967, 1.00001, 0.99977, 1.00026, 0.99964, 1.00031, 1.00001, 0.99999, 0.99999, 1, 1.00023, 1, 1, 0.99999, 1.00035, 1.00001, 0.99999, 0.99973, 0.99977, 0.99999, 1.00058, 0.99973, 0.99973, 0.99955, 0.9995, 1.00026, 1.00026, 1.00032, 0.99989, 1.00034, 0.99999, 1.00026, 1.00026, 1.00026, 0.99973, 0.45998, 0.99973, 1.00026, 0.99973, 1.00001, 0.99999, 0.99982, 0.99994, 0.99996, 1, 1.00042, 1.00044, 1.00029, 1.00023, 0.99973, 0.99973, 1.00026, 0.99949, 1.00002, 0.99973, 1.0006, 1.0006, 1.0006, 0.99975, 1.00026, 1.00026, 1.00032, 0.98685, 0.99973, 1.00026, 1, 1, 0.99966, 1.00044, 1.00016, 1.00022, 1.00016, 1.00022, 1.00016, 1.00022, 1.00001, 0.99973, 1, 1, 0.99973, 1, 1, 0.99955, 1.0006, 1.0006, 1.0006, 1.0006, 1, 1, 1, 0.99973, 0.99973, 0.99972, 1, 1, 1.00106, 0.99999, 0.99998, 0.99998, 0.99999, 0.99998, 1.66475, 1, 0.99973, 0.99973, 1, 0.99973, 0.99971, 0.99978, 1, 1, 0.99991, 0.99984, 1.00002, 1.00002, 1.00002, 1.00002, 1.00098, 1, 1, 1, 1.00049, 1, 1, 0.99972, 1, 1.20985, 1.39713, 1.00003, 1.00031, 1.00015, 1, 0.99561, 1.00027, 1.00031, 1.00031, 0.99915, 1.00031, 1.00031, 0.99999, 1.00003, 0.99999, 0.99999, 1.41144, 1.6, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.40579, 1.40579, 1.36625, 0.99999, 1, 0.99861, 0.99861, 1, 1.00026, 1.00026, 1.00026, 1.00026, 0.99972, 0.99999, 0.99999, 0.99999, 0.99999, 1.40483, 1, 0.99977, 1.00054, 1, 1, 0.99953, 0.99962, 1.00042, 0.9995, 1, 1, 1, 1, 1, 1, 1, 1, 0.99998, 0.99998, 0.99998, 0.99998, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.HelveticaBoldItalicFactors = HelveticaBoldItalicFactors;
const HelveticaBoldItalicMetrics = {
  lineHeight: 1.35,
  lineGap: 0.2
};
exports.HelveticaBoldItalicMetrics = HelveticaBoldItalicMetrics;
const HelveticaItalicFactors = [0.76116, 1, 1, 1.0006, 1.0006, 1.00006, 0.99973, 0.99973, 0.99982, 1.00001, 1.00043, 0.99998, 0.99998, 0.99959, 1.00003, 1.0006, 0.99998, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1, 1.00003, 1.00003, 1.00003, 0.99973, 0.99987, 1.00001, 1.00001, 0.99977, 0.99977, 1.00001, 1.00026, 1.00022, 0.99977, 1.0006, 1, 1.00001, 0.99973, 0.99999, 0.99977, 1.00022, 1.00001, 1.00022, 0.99977, 1.00001, 1.00026, 0.99977, 1.00001, 1.00016, 1.00001, 1.00001, 1.00026, 1.0006, 1.0006, 1.0006, 0.99949, 0.99973, 0.99998, 0.99973, 0.99973, 1, 0.99973, 0.99973, 1.0006, 0.99973, 0.99973, 0.99924, 0.99924, 1, 0.99924, 0.99999, 0.99973, 0.99973, 0.99973, 0.99973, 0.99998, 1, 1.0006, 0.99973, 1, 0.99977, 1, 1, 1, 1.00005, 1.0009, 1.00005, 1.00003, 0.99998, 0.99973, 0.99973, 0.99973, 0.99973, 1.0009, 0.99973, 0.99998, 1.00025, 0.99968, 0.99973, 1.00003, 1.00025, 0.60299, 1.00024, 1.06409, 1, 1, 0.99998, 1, 0.9998, 1.0006, 0.99998, 1, 0.99936, 0.99973, 1.00002, 1.00002, 1.00002, 1.00026, 1.00001, 1.00001, 1.00001, 1.00001, 1.00001, 1.00001, 1, 0.99977, 1.00001, 1.00001, 1.00001, 1.00001, 1.0006, 1.0006, 1.0006, 1.0006, 0.99977, 0.99977, 1.00022, 1.00022, 1.00022, 1.00022, 1.00022, 1.00003, 1.00022, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00001, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99982, 1, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.06409, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 1, 0.99973, 1, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 0.99977, 1, 0.99977, 1, 0.99977, 1, 0.99977, 1, 0.99977, 1.0288, 0.99977, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 0.99924, 1.0006, 1.0006, 0.99946, 1.00034, 1, 0.99924, 1.00001, 1, 1, 0.99973, 0.99924, 0.99973, 0.99924, 0.99973, 1.06311, 0.99973, 1.00024, 0.99973, 0.99924, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 1.00041, 0.9998, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1, 1.00016, 0.99977, 0.99998, 0.99977, 0.99998, 0.99977, 0.99998, 1.00001, 1, 1.00001, 1, 1.00001, 1, 1.00001, 1, 1.00026, 1.0006, 1.00026, 0.89547, 1.00026, 1.0006, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 1.00016, 0.99977, 1.00001, 1, 1.00001, 1.00026, 1, 1.00026, 1, 1.00026, 1, 0.99924, 0.99973, 1.00001, 0.99973, 1, 0.99982, 1.00022, 1.00026, 1.00001, 1, 1.00026, 1.0006, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 1.00001, 1, 1.00054, 0.99977, 1.00084, 1.00007, 0.99973, 1.00013, 0.99924, 1.00001, 1.00001, 0.99945, 0.91221, 1.00001, 1.00026, 0.99977, 1.00022, 1.0006, 1.00001, 1.00001, 0.99999, 0.99977, 0.99933, 1.00022, 1.00054, 1.00001, 1.00065, 1.00026, 1.00001, 1.0001, 1.00001, 1.00052, 1, 1.0006, 1.00001, 0.99945, 0.99897, 0.99968, 0.99924, 1.00036, 0.99945, 0.99949, 1, 1.0006, 0.99897, 0.99918, 0.99968, 0.99911, 0.99924, 1, 0.99962, 1.01487, 1, 1.0005, 0.99973, 1.00012, 1.00043, 1, 0.99995, 0.99994, 1.00036, 0.99947, 1.00019, 1.00063, 1.00025, 0.99924, 1.00036, 0.99973, 1.00036, 1.00025, 1.00001, 1.00001, 1.00027, 1.0001, 1.00068, 1.00001, 1.0006, 1.0006, 1, 1.00008, 0.99957, 0.99972, 0.9994, 0.99954, 0.99975, 1.00051, 1.00001, 1.00019, 1.00001, 1.0001, 0.99986, 1.00001, 1.00001, 1.00038, 0.99954, 0.99954, 0.9994, 1.00066, 0.99999, 0.99977, 1.00022, 1.00054, 1.00001, 0.99977, 1.00026, 0.99975, 1.0001, 1.00001, 0.99993, 0.9995, 0.99955, 1.00016, 0.99978, 0.99974, 1.00019, 1.00022, 0.99955, 1.00053, 0.99973, 1.00089, 1.00005, 0.99967, 1.00048, 0.99973, 1.00002, 1.00034, 0.99973, 0.99973, 0.99964, 1.00006, 1.00066, 0.99947, 0.99973, 0.98894, 0.99973, 1, 0.44898, 1, 0.99946, 1, 1.00039, 1.00082, 0.99991, 0.99991, 0.99985, 1.00022, 1.00023, 1.00061, 1.00006, 0.99966, 0.99973, 0.99973, 0.99973, 1.00019, 1.0008, 1, 0.99924, 0.99924, 0.99924, 0.99983, 1.00044, 0.99973, 0.99964, 0.98332, 1, 0.99973, 1, 1, 0.99962, 0.99895, 1.00016, 0.99977, 1.00016, 0.99977, 1.00016, 0.99977, 1.00001, 1, 1, 1, 0.99973, 1, 1, 0.99955, 0.99924, 0.99924, 0.99924, 0.99924, 0.99998, 0.99998, 0.99998, 0.99973, 0.99973, 0.99972, 1, 1, 1.00267, 0.99999, 0.99998, 0.99998, 1, 0.99998, 1.66475, 1, 0.99973, 0.99973, 1.00023, 0.99973, 1.00423, 0.99925, 0.99999, 1, 0.99991, 0.99984, 1.00002, 1.00002, 1.00002, 1.00002, 1.00049, 1, 1.00245, 1, 1, 1, 1, 0.96329, 1, 1.20985, 1.39713, 1.00003, 0.8254, 1.00015, 1, 1.00035, 1.00027, 1.00031, 1.00031, 1.00003, 1.00031, 1.00031, 0.99999, 1.00003, 0.99999, 0.99999, 1.41144, 1.6, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.40579, 1.40579, 1.36625, 0.99999, 1, 0.99861, 0.99861, 1, 1.00026, 1.00026, 1.00026, 1.00026, 0.95317, 0.99999, 0.99999, 0.99999, 0.99999, 1.40483, 1, 0.99977, 1.00054, 1, 1, 0.99953, 0.99962, 1.00042, 0.9995, 1, 1, 1, 1, 1, 1, 1, 1, 0.99998, 0.99998, 0.99998, 0.99998, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.HelveticaItalicFactors = HelveticaItalicFactors;
const HelveticaItalicMetrics = {
  lineHeight: 1.35,
  lineGap: 0.2
};
exports.HelveticaItalicMetrics = HelveticaItalicMetrics;
const HelveticaRegularFactors = [0.76116, 1, 1, 1.0006, 1.0006, 1.00006, 0.99973, 0.99973, 0.99982, 1.00001, 1.00043, 0.99998, 0.99998, 0.99959, 1.00003, 1.0006, 0.99998, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1, 1.00003, 1.00003, 1.00003, 0.99973, 0.99987, 1.00001, 1.00001, 0.99977, 0.99977, 1.00001, 1.00026, 1.00022, 0.99977, 1.0006, 1, 1.00001, 0.99973, 0.99999, 0.99977, 1.00022, 1.00001, 1.00022, 0.99977, 1.00001, 1.00026, 0.99977, 1.00001, 1.00016, 1.00001, 1.00001, 1.00026, 1.0006, 1.0006, 1.0006, 0.99949, 0.99973, 0.99998, 0.99973, 0.99973, 1, 0.99973, 0.99973, 1.0006, 0.99973, 0.99973, 0.99924, 0.99924, 1, 0.99924, 0.99999, 0.99973, 0.99973, 0.99973, 0.99973, 0.99998, 1, 1.0006, 0.99973, 1, 0.99977, 1, 1, 1, 1.00005, 1.0009, 1.00005, 1.00003, 0.99998, 0.99973, 0.99973, 0.99973, 0.99973, 1.0009, 0.99973, 0.99998, 1.00025, 0.99968, 0.99973, 1.00003, 1.00025, 0.60299, 1.00024, 1.06409, 1, 1, 0.99998, 1, 0.9998, 1.0006, 0.99998, 1, 0.99936, 0.99973, 1.00002, 1.00002, 1.00002, 1.00026, 1.00001, 1.00001, 1.00001, 1.00001, 1.00001, 1.00001, 1, 0.99977, 1.00001, 1.00001, 1.00001, 1.00001, 1.0006, 1.0006, 1.0006, 1.0006, 0.99977, 0.99977, 1.00022, 1.00022, 1.00022, 1.00022, 1.00022, 1.00003, 1.00022, 0.99977, 0.99977, 0.99977, 0.99977, 1.00001, 1.00001, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99982, 1, 0.99973, 0.99973, 0.99973, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 0.99973, 1.06409, 1.00026, 0.99973, 0.99973, 0.99973, 0.99973, 1, 0.99973, 1, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 0.99977, 1, 0.99977, 1, 0.99977, 1, 0.99977, 1, 0.99977, 1.04596, 0.99977, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00001, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 1.0006, 0.99924, 1.0006, 1.0006, 1.00019, 1.00034, 1, 0.99924, 1.00001, 1, 1, 0.99973, 0.99924, 0.99973, 0.99924, 0.99973, 1.02572, 0.99973, 1.00005, 0.99973, 0.99924, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99999, 0.9998, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1.00022, 0.99973, 1, 1.00016, 0.99977, 0.99998, 0.99977, 0.99998, 0.99977, 0.99998, 1.00001, 1, 1.00001, 1, 1.00001, 1, 1.00001, 1, 1.00026, 1.0006, 1.00026, 0.84533, 1.00026, 1.0006, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 0.99977, 0.99973, 1.00016, 0.99977, 1.00001, 1, 1.00001, 1.00026, 1, 1.00026, 1, 1.00026, 1, 0.99924, 0.99973, 1.00001, 0.99973, 1, 0.99982, 1.00022, 1.00026, 1.00001, 1, 1.00026, 1.0006, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99998, 0.99928, 1, 0.99977, 1.00013, 1.00055, 0.99947, 0.99945, 0.99941, 0.99924, 1.00001, 1.00001, 1.0004, 0.91621, 1.00001, 1.00026, 0.99977, 1.00022, 1.0006, 1.00001, 1.00005, 0.99999, 0.99977, 1.00015, 1.00022, 0.99977, 1.00001, 0.99973, 1.00026, 1.00001, 1.00019, 1.00001, 0.99946, 1, 1.0006, 1.00001, 0.99978, 1.00045, 0.99973, 0.99924, 1.00023, 0.99978, 0.99966, 1, 1.00065, 1.00045, 1.00019, 0.99973, 0.99973, 0.99924, 1, 1, 0.96499, 1, 1.00055, 0.99973, 1.00008, 1.00027, 1, 0.9997, 0.99995, 1.00023, 0.99933, 1.00019, 1.00015, 1.00031, 0.99924, 1.00023, 0.99973, 1.00023, 1.00031, 1.00001, 0.99928, 1.00029, 1.00092, 1.00035, 1.00001, 1.0006, 1.0006, 1, 0.99988, 0.99975, 1, 1.00082, 0.99561, 0.9996, 1.00035, 1.00001, 0.99962, 1.00001, 1.00092, 0.99964, 1.00001, 0.99963, 0.99999, 1.00035, 1.00035, 1.00082, 0.99962, 0.99999, 0.99977, 1.00022, 1.00035, 1.00001, 0.99977, 1.00026, 0.9996, 0.99967, 1.00001, 1.00034, 1.00074, 1.00054, 1.00053, 1.00063, 0.99971, 0.99962, 1.00035, 0.99975, 0.99977, 0.99973, 1.00043, 0.99953, 1.0007, 0.99915, 0.99973, 1.00008, 0.99892, 1.00073, 1.00073, 1.00114, 0.99915, 1.00073, 0.99955, 0.99973, 1.00092, 0.99973, 1, 0.99998, 1, 1.0003, 1, 1.00043, 1.00001, 0.99969, 1.0003, 1, 1.00035, 1.00001, 0.9995, 1, 1.00092, 0.99973, 0.99973, 0.99973, 1.0007, 0.9995, 1, 0.99924, 1.0006, 0.99924, 0.99972, 1.00062, 0.99973, 1.00114, 1.00073, 1, 0.99955, 1, 1, 1.00047, 0.99968, 1.00016, 0.99977, 1.00016, 0.99977, 1.00016, 0.99977, 1.00001, 1, 1, 1, 0.99973, 1, 1, 0.99955, 0.99924, 0.99924, 0.99924, 0.99924, 0.99998, 0.99998, 0.99998, 0.99973, 0.99973, 0.99972, 1, 1, 1.00267, 0.99999, 0.99998, 0.99998, 1, 0.99998, 1.66475, 1, 0.99973, 0.99973, 1.00023, 0.99973, 0.99971, 0.99925, 1.00023, 1, 0.99991, 0.99984, 1.00002, 1.00002, 1.00002, 1.00002, 1, 1, 1, 1, 1, 1, 1, 0.96329, 1, 1.20985, 1.39713, 1.00003, 0.8254, 1.00015, 1, 1.00035, 1.00027, 1.00031, 1.00031, 0.99915, 1.00031, 1.00031, 0.99999, 1.00003, 0.99999, 0.99999, 1.41144, 1.6, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.41144, 1.40579, 1.40579, 1.36625, 0.99999, 1, 0.99861, 0.99861, 1, 1.00026, 1.00026, 1.00026, 1.00026, 0.95317, 0.99999, 0.99999, 0.99999, 0.99999, 1.40483, 1, 0.99977, 1.00054, 1, 1, 0.99953, 0.99962, 1.00042, 0.9995, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.HelveticaRegularFactors = HelveticaRegularFactors;
const HelveticaRegularMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.HelveticaRegularMetrics = HelveticaRegularMetrics;

/***/ }),
/* 52 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.LiberationSansRegularWidths = exports.LiberationSansRegularMapping = exports.LiberationSansItalicWidths = exports.LiberationSansItalicMapping = exports.LiberationSansBoldWidths = exports.LiberationSansBoldMapping = exports.LiberationSansBoldItalicWidths = exports.LiberationSansBoldItalicMapping = void 0;
const LiberationSansBoldWidths = [365, 0, 333, 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 737, 552, 400, 549, 333, 333, 333, 576, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, 611, 611, 611, 611, 611, 611, 611, 549, 611, 611, 611, 611, 611, 556, 611, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 719, 722, 611, 667, 556, 667, 556, 667, 556, 667, 556, 667, 556, 778, 611, 778, 611, 778, 611, 778, 611, 722, 611, 722, 611, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 785, 556, 556, 278, 722, 556, 556, 611, 278, 611, 278, 611, 385, 611, 479, 611, 278, 722, 611, 722, 611, 722, 611, 708, 723, 611, 778, 611, 778, 611, 778, 611, 1000, 944, 722, 389, 722, 389, 722, 389, 667, 556, 667, 556, 667, 556, 667, 556, 611, 333, 611, 479, 611, 333, 722, 611, 722, 611, 722, 611, 722, 611, 722, 611, 722, 611, 944, 778, 667, 556, 667, 611, 500, 611, 500, 611, 500, 278, 556, 722, 556, 1000, 889, 778, 611, 667, 556, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 465, 722, 333, 853, 906, 474, 825, 927, 838, 278, 722, 722, 601, 719, 667, 611, 722, 778, 278, 722, 667, 833, 722, 644, 778, 722, 667, 600, 611, 667, 821, 667, 809, 802, 278, 667, 615, 451, 611, 278, 582, 615, 610, 556, 606, 475, 460, 611, 541, 278, 558, 556, 612, 556, 445, 611, 766, 619, 520, 684, 446, 582, 715, 576, 753, 845, 278, 582, 611, 582, 845, 667, 669, 885, 567, 711, 667, 278, 276, 556, 1094, 1062, 875, 610, 722, 622, 719, 722, 719, 722, 567, 712, 667, 904, 626, 719, 719, 610, 702, 833, 722, 778, 719, 667, 722, 611, 622, 854, 667, 730, 703, 1005, 1019, 870, 979, 719, 711, 1031, 719, 556, 618, 615, 417, 635, 556, 709, 497, 615, 615, 500, 635, 740, 604, 611, 604, 611, 556, 490, 556, 875, 556, 615, 581, 833, 844, 729, 854, 615, 552, 854, 583, 556, 556, 611, 417, 552, 556, 278, 281, 278, 969, 906, 611, 500, 615, 556, 604, 778, 611, 487, 447, 944, 778, 944, 778, 944, 778, 667, 556, 333, 333, 556, 1000, 1000, 552, 278, 278, 278, 278, 500, 500, 500, 556, 556, 350, 1000, 1000, 240, 479, 333, 333, 604, 333, 167, 396, 556, 556, 1094, 556, 885, 489, 1115, 1000, 768, 600, 834, 834, 834, 834, 1000, 500, 1000, 500, 1000, 500, 500, 494, 612, 823, 713, 584, 549, 713, 979, 722, 274, 549, 549, 583, 549, 549, 604, 584, 604, 604, 708, 625, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 729, 604, 604, 354, 354, 1000, 990, 990, 990, 990, 494, 604, 604, 604, 604, 354, 1021, 1052, 917, 750, 750, 531, 656, 594, 510, 500, 750, 750, 611, 611, 333, 333, 333, 333, 333, 333, 333, 333, 222, 222, 333, 333, 333, 333, 333, 333, 333, 333];
exports.LiberationSansBoldWidths = LiberationSansBoldWidths;
const LiberationSansBoldMapping = [-1, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 402, 506, 507, 508, 509, 510, 511, 536, 537, 538, 539, 710, 711, 713, 728, 729, 730, 731, 732, 733, 900, 901, 902, 903, 904, 905, 906, 908, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1138, 1139, 1168, 1169, 7808, 7809, 7810, 7811, 7812, 7813, 7922, 7923, 8208, 8209, 8211, 8212, 8213, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222, 8224, 8225, 8226, 8230, 8240, 8242, 8243, 8249, 8250, 8252, 8254, 8260, 8319, 8355, 8356, 8359, 8364, 8453, 8467, 8470, 8482, 8486, 8494, 8539, 8540, 8541, 8542, 8592, 8593, 8594, 8595, 8596, 8597, 8616, 8706, 8710, 8719, 8721, 8722, 8730, 8734, 8735, 8745, 8747, 8776, 8800, 8801, 8804, 8805, 8962, 8976, 8992, 8993, 9472, 9474, 9484, 9488, 9492, 9496, 9500, 9508, 9516, 9524, 9532, 9552, 9553, 9554, 9555, 9556, 9557, 9558, 9559, 9560, 9561, 9562, 9563, 9564, 9565, 9566, 9567, 9568, 9569, 9570, 9571, 9572, 9573, 9574, 9575, 9576, 9577, 9578, 9579, 9580, 9600, 9604, 9608, 9612, 9616, 9617, 9618, 9619, 9632, 9633, 9642, 9643, 9644, 9650, 9658, 9660, 9668, 9674, 9675, 9679, 9688, 9689, 9702, 9786, 9787, 9788, 9792, 9794, 9824, 9827, 9829, 9830, 9834, 9835, 9836, 61441, 61442, 61445, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
exports.LiberationSansBoldMapping = LiberationSansBoldMapping;
const LiberationSansBoldItalicWidths = [365, 0, 333, 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 737, 552, 400, 549, 333, 333, 333, 576, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, 611, 611, 611, 611, 611, 611, 611, 549, 611, 611, 611, 611, 611, 556, 611, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 740, 722, 611, 667, 556, 667, 556, 667, 556, 667, 556, 667, 556, 778, 611, 778, 611, 778, 611, 778, 611, 722, 611, 722, 611, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 782, 556, 556, 278, 722, 556, 556, 611, 278, 611, 278, 611, 396, 611, 479, 611, 278, 722, 611, 722, 611, 722, 611, 708, 723, 611, 778, 611, 778, 611, 778, 611, 1000, 944, 722, 389, 722, 389, 722, 389, 667, 556, 667, 556, 667, 556, 667, 556, 611, 333, 611, 479, 611, 333, 722, 611, 722, 611, 722, 611, 722, 611, 722, 611, 722, 611, 944, 778, 667, 556, 667, 611, 500, 611, 500, 611, 500, 278, 556, 722, 556, 1000, 889, 778, 611, 667, 556, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 722, 333, 854, 906, 473, 844, 930, 847, 278, 722, 722, 610, 671, 667, 611, 722, 778, 278, 722, 667, 833, 722, 657, 778, 718, 667, 590, 611, 667, 822, 667, 829, 781, 278, 667, 620, 479, 611, 278, 591, 620, 621, 556, 610, 479, 492, 611, 558, 278, 566, 556, 603, 556, 450, 611, 712, 605, 532, 664, 409, 591, 704, 578, 773, 834, 278, 591, 611, 591, 834, 667, 667, 886, 614, 719, 667, 278, 278, 556, 1094, 1042, 854, 622, 719, 677, 719, 722, 708, 722, 614, 722, 667, 927, 643, 719, 719, 615, 687, 833, 722, 778, 719, 667, 722, 611, 677, 781, 667, 729, 708, 979, 989, 854, 1000, 708, 719, 1042, 729, 556, 619, 604, 534, 618, 556, 736, 510, 611, 611, 507, 622, 740, 604, 611, 611, 611, 556, 889, 556, 885, 556, 646, 583, 889, 935, 707, 854, 594, 552, 865, 589, 556, 556, 611, 469, 563, 556, 278, 278, 278, 969, 906, 611, 507, 619, 556, 611, 778, 611, 575, 467, 944, 778, 944, 778, 944, 778, 667, 556, 333, 333, 556, 1000, 1000, 552, 278, 278, 278, 278, 500, 500, 500, 556, 556, 350, 1000, 1000, 240, 479, 333, 333, 604, 333, 167, 396, 556, 556, 1104, 556, 885, 516, 1146, 1000, 768, 600, 834, 834, 834, 834, 999, 500, 1000, 500, 1000, 500, 500, 494, 612, 823, 713, 584, 549, 713, 979, 722, 274, 549, 549, 583, 549, 549, 604, 584, 604, 604, 708, 625, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 729, 604, 604, 354, 354, 1000, 990, 990, 990, 990, 494, 604, 604, 604, 604, 354, 1021, 1052, 917, 750, 750, 531, 656, 594, 510, 500, 750, 750, 611, 611, 333, 333, 333, 333, 333, 333, 333, 333, 222, 222, 333, 333, 333, 333, 333, 333, 333, 333];
exports.LiberationSansBoldItalicWidths = LiberationSansBoldItalicWidths;
const LiberationSansBoldItalicMapping = [-1, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 402, 506, 507, 508, 509, 510, 511, 536, 537, 538, 539, 710, 711, 713, 728, 729, 730, 731, 732, 733, 900, 901, 902, 903, 904, 905, 906, 908, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1138, 1139, 1168, 1169, 7808, 7809, 7810, 7811, 7812, 7813, 7922, 7923, 8208, 8209, 8211, 8212, 8213, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222, 8224, 8225, 8226, 8230, 8240, 8242, 8243, 8249, 8250, 8252, 8254, 8260, 8319, 8355, 8356, 8359, 8364, 8453, 8467, 8470, 8482, 8486, 8494, 8539, 8540, 8541, 8542, 8592, 8593, 8594, 8595, 8596, 8597, 8616, 8706, 8710, 8719, 8721, 8722, 8730, 8734, 8735, 8745, 8747, 8776, 8800, 8801, 8804, 8805, 8962, 8976, 8992, 8993, 9472, 9474, 9484, 9488, 9492, 9496, 9500, 9508, 9516, 9524, 9532, 9552, 9553, 9554, 9555, 9556, 9557, 9558, 9559, 9560, 9561, 9562, 9563, 9564, 9565, 9566, 9567, 9568, 9569, 9570, 9571, 9572, 9573, 9574, 9575, 9576, 9577, 9578, 9579, 9580, 9600, 9604, 9608, 9612, 9616, 9617, 9618, 9619, 9632, 9633, 9642, 9643, 9644, 9650, 9658, 9660, 9668, 9674, 9675, 9679, 9688, 9689, 9702, 9786, 9787, 9788, 9792, 9794, 9824, 9827, 9829, 9830, 9834, 9835, 9836, 61441, 61442, 61445, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
exports.LiberationSansBoldItalicMapping = LiberationSansBoldItalicMapping;
const LiberationSansItalicWidths = [365, 0, 333, 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 737, 552, 400, 549, 333, 333, 333, 576, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, 556, 556, 556, 556, 556, 556, 556, 549, 611, 556, 556, 556, 556, 500, 556, 500, 667, 556, 667, 556, 667, 556, 722, 500, 722, 500, 722, 500, 722, 500, 722, 625, 722, 556, 667, 556, 667, 556, 667, 556, 667, 556, 667, 556, 778, 556, 778, 556, 778, 556, 778, 556, 722, 556, 722, 556, 278, 278, 278, 278, 278, 278, 278, 222, 278, 278, 733, 444, 500, 222, 667, 500, 500, 556, 222, 556, 222, 556, 281, 556, 400, 556, 222, 722, 556, 722, 556, 722, 556, 615, 723, 556, 778, 556, 778, 556, 778, 556, 1000, 944, 722, 333, 722, 333, 722, 333, 667, 500, 667, 500, 667, 500, 667, 500, 611, 278, 611, 354, 611, 278, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 944, 722, 667, 500, 667, 611, 500, 611, 500, 611, 500, 222, 556, 667, 556, 1000, 889, 778, 611, 667, 500, 611, 278, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 667, 278, 789, 846, 389, 794, 865, 775, 222, 667, 667, 570, 671, 667, 611, 722, 778, 278, 667, 667, 833, 722, 648, 778, 725, 667, 600, 611, 667, 837, 667, 831, 761, 278, 667, 570, 439, 555, 222, 550, 570, 571, 500, 556, 439, 463, 555, 542, 222, 500, 492, 548, 500, 447, 556, 670, 573, 486, 603, 374, 550, 652, 546, 728, 779, 222, 550, 556, 550, 779, 667, 667, 843, 544, 708, 667, 278, 278, 500, 1066, 982, 844, 589, 715, 639, 724, 667, 651, 667, 544, 704, 667, 917, 614, 715, 715, 589, 686, 833, 722, 778, 725, 667, 722, 611, 639, 795, 667, 727, 673, 920, 923, 805, 886, 651, 694, 1022, 682, 556, 562, 522, 493, 553, 556, 688, 465, 556, 556, 472, 564, 686, 550, 556, 556, 556, 500, 833, 500, 835, 500, 572, 518, 830, 851, 621, 736, 526, 492, 752, 534, 556, 556, 556, 378, 496, 500, 222, 222, 222, 910, 828, 556, 472, 565, 500, 556, 778, 556, 492, 339, 944, 722, 944, 722, 944, 722, 667, 500, 333, 333, 556, 1000, 1000, 552, 222, 222, 222, 222, 333, 333, 333, 556, 556, 350, 1000, 1000, 188, 354, 333, 333, 500, 333, 167, 365, 556, 556, 1094, 556, 885, 323, 1083, 1000, 768, 600, 834, 834, 834, 834, 1000, 500, 998, 500, 1000, 500, 500, 494, 612, 823, 713, 584, 549, 713, 979, 719, 274, 549, 549, 584, 549, 549, 604, 584, 604, 604, 708, 625, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 729, 604, 604, 354, 354, 1000, 990, 990, 990, 990, 494, 604, 604, 604, 604, 354, 1021, 1052, 917, 750, 750, 531, 656, 594, 510, 500, 750, 750, 500, 500, 333, 333, 333, 333, 333, 333, 333, 333, 222, 222, 294, 294, 324, 324, 316, 328, 398, 285];
exports.LiberationSansItalicWidths = LiberationSansItalicWidths;
const LiberationSansItalicMapping = [-1, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 402, 506, 507, 508, 509, 510, 511, 536, 537, 538, 539, 710, 711, 713, 728, 729, 730, 731, 732, 733, 900, 901, 902, 903, 904, 905, 906, 908, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1138, 1139, 1168, 1169, 7808, 7809, 7810, 7811, 7812, 7813, 7922, 7923, 8208, 8209, 8211, 8212, 8213, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222, 8224, 8225, 8226, 8230, 8240, 8242, 8243, 8249, 8250, 8252, 8254, 8260, 8319, 8355, 8356, 8359, 8364, 8453, 8467, 8470, 8482, 8486, 8494, 8539, 8540, 8541, 8542, 8592, 8593, 8594, 8595, 8596, 8597, 8616, 8706, 8710, 8719, 8721, 8722, 8730, 8734, 8735, 8745, 8747, 8776, 8800, 8801, 8804, 8805, 8962, 8976, 8992, 8993, 9472, 9474, 9484, 9488, 9492, 9496, 9500, 9508, 9516, 9524, 9532, 9552, 9553, 9554, 9555, 9556, 9557, 9558, 9559, 9560, 9561, 9562, 9563, 9564, 9565, 9566, 9567, 9568, 9569, 9570, 9571, 9572, 9573, 9574, 9575, 9576, 9577, 9578, 9579, 9580, 9600, 9604, 9608, 9612, 9616, 9617, 9618, 9619, 9632, 9633, 9642, 9643, 9644, 9650, 9658, 9660, 9668, 9674, 9675, 9679, 9688, 9689, 9702, 9786, 9787, 9788, 9792, 9794, 9824, 9827, 9829, 9830, 9834, 9835, 9836, 61441, 61442, 61445, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
exports.LiberationSansItalicMapping = LiberationSansItalicMapping;
const LiberationSansRegularWidths = [365, 0, 333, 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 737, 552, 400, 549, 333, 333, 333, 576, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, 556, 556, 556, 556, 556, 556, 556, 549, 611, 556, 556, 556, 556, 500, 556, 500, 667, 556, 667, 556, 667, 556, 722, 500, 722, 500, 722, 500, 722, 500, 722, 615, 722, 556, 667, 556, 667, 556, 667, 556, 667, 556, 667, 556, 778, 556, 778, 556, 778, 556, 778, 556, 722, 556, 722, 556, 278, 278, 278, 278, 278, 278, 278, 222, 278, 278, 735, 444, 500, 222, 667, 500, 500, 556, 222, 556, 222, 556, 292, 556, 334, 556, 222, 722, 556, 722, 556, 722, 556, 604, 723, 556, 778, 556, 778, 556, 778, 556, 1000, 944, 722, 333, 722, 333, 722, 333, 667, 500, 667, 500, 667, 500, 667, 500, 611, 278, 611, 375, 611, 278, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 722, 556, 944, 722, 667, 500, 667, 611, 500, 611, 500, 611, 500, 222, 556, 667, 556, 1000, 889, 778, 611, 667, 500, 611, 278, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 667, 278, 784, 838, 384, 774, 855, 752, 222, 667, 667, 551, 668, 667, 611, 722, 778, 278, 667, 668, 833, 722, 650, 778, 722, 667, 618, 611, 667, 798, 667, 835, 748, 278, 667, 578, 446, 556, 222, 547, 578, 575, 500, 557, 446, 441, 556, 556, 222, 500, 500, 576, 500, 448, 556, 690, 569, 482, 617, 395, 547, 648, 525, 713, 781, 222, 547, 556, 547, 781, 667, 667, 865, 542, 719, 667, 278, 278, 500, 1057, 1010, 854, 583, 722, 635, 719, 667, 656, 667, 542, 677, 667, 923, 604, 719, 719, 583, 656, 833, 722, 778, 719, 667, 722, 611, 635, 760, 667, 740, 667, 917, 938, 792, 885, 656, 719, 1010, 722, 556, 573, 531, 365, 583, 556, 669, 458, 559, 559, 438, 583, 688, 552, 556, 542, 556, 500, 458, 500, 823, 500, 573, 521, 802, 823, 625, 719, 521, 510, 750, 542, 556, 556, 556, 365, 510, 500, 222, 278, 222, 906, 812, 556, 438, 559, 500, 552, 778, 556, 489, 411, 944, 722, 944, 722, 944, 722, 667, 500, 333, 333, 556, 1000, 1000, 552, 222, 222, 222, 222, 333, 333, 333, 556, 556, 350, 1000, 1000, 188, 354, 333, 333, 500, 333, 167, 365, 556, 556, 1094, 556, 885, 323, 1073, 1000, 768, 600, 834, 834, 834, 834, 1000, 500, 1000, 500, 1000, 500, 500, 494, 612, 823, 713, 584, 549, 713, 979, 719, 274, 549, 549, 583, 549, 549, 604, 584, 604, 604, 708, 625, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 729, 604, 604, 354, 354, 1000, 990, 990, 990, 990, 494, 604, 604, 604, 604, 354, 1021, 1052, 917, 750, 750, 531, 656, 594, 510, 500, 750, 750, 500, 500, 333, 333, 333, 333, 333, 333, 333, 333, 222, 222, 294, 294, 324, 324, 316, 328, 398, 285];
exports.LiberationSansRegularWidths = LiberationSansRegularWidths;
const LiberationSansRegularMapping = [-1, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 402, 506, 507, 508, 509, 510, 511, 536, 537, 538, 539, 710, 711, 713, 728, 729, 730, 731, 732, 733, 900, 901, 902, 903, 904, 905, 906, 908, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1138, 1139, 1168, 1169, 7808, 7809, 7810, 7811, 7812, 7813, 7922, 7923, 8208, 8209, 8211, 8212, 8213, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222, 8224, 8225, 8226, 8230, 8240, 8242, 8243, 8249, 8250, 8252, 8254, 8260, 8319, 8355, 8356, 8359, 8364, 8453, 8467, 8470, 8482, 8486, 8494, 8539, 8540, 8541, 8542, 8592, 8593, 8594, 8595, 8596, 8597, 8616, 8706, 8710, 8719, 8721, 8722, 8730, 8734, 8735, 8745, 8747, 8776, 8800, 8801, 8804, 8805, 8962, 8976, 8992, 8993, 9472, 9474, 9484, 9488, 9492, 9496, 9500, 9508, 9516, 9524, 9532, 9552, 9553, 9554, 9555, 9556, 9557, 9558, 9559, 9560, 9561, 9562, 9563, 9564, 9565, 9566, 9567, 9568, 9569, 9570, 9571, 9572, 9573, 9574, 9575, 9576, 9577, 9578, 9579, 9580, 9600, 9604, 9608, 9612, 9616, 9617, 9618, 9619, 9632, 9633, 9642, 9643, 9644, 9650, 9658, 9660, 9668, 9674, 9675, 9679, 9688, 9689, 9702, 9786, 9787, 9788, 9792, 9794, 9824, 9827, 9829, 9830, 9834, 9835, 9836, 61441, 61442, 61445, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
exports.LiberationSansRegularMapping = LiberationSansRegularMapping;

/***/ }),
/* 53 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MyriadProRegularMetrics = exports.MyriadProRegularFactors = exports.MyriadProItalicMetrics = exports.MyriadProItalicFactors = exports.MyriadProBoldMetrics = exports.MyriadProBoldItalicMetrics = exports.MyriadProBoldItalicFactors = exports.MyriadProBoldFactors = void 0;
const MyriadProBoldFactors = [1.36898, 1, 1, 0.72706, 0.80479, 0.83734, 0.98894, 0.99793, 0.9897, 0.93884, 0.86209, 0.94292, 0.94292, 1.16661, 1.02058, 0.93582, 0.96694, 0.93582, 1.19137, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.99793, 0.78076, 0.78076, 1.02058, 1.02058, 1.02058, 0.72851, 0.78966, 0.90838, 0.83637, 0.82391, 0.96376, 0.80061, 0.86275, 0.8768, 0.95407, 1.0258, 0.73901, 0.85022, 0.83655, 1.0156, 0.95546, 0.92179, 0.87107, 0.92179, 0.82114, 0.8096, 0.89713, 0.94438, 0.95353, 0.94083, 0.91905, 0.90406, 0.9446, 0.94292, 1.18777, 0.94292, 1.02058, 0.89903, 0.90088, 0.94938, 0.97898, 0.81093, 0.97571, 0.94938, 1.024, 0.9577, 0.95933, 0.98621, 1.0474, 0.97455, 0.98981, 0.9672, 0.95933, 0.9446, 0.97898, 0.97407, 0.97646, 0.78036, 1.10208, 0.95442, 0.95298, 0.97579, 0.9332, 0.94039, 0.938, 0.80687, 1.01149, 0.80687, 1.02058, 0.80479, 0.99793, 0.99793, 0.99793, 0.99793, 1.01149, 1.00872, 0.90088, 0.91882, 1.0213, 0.8361, 1.02058, 0.62295, 0.54324, 0.89022, 1.08595, 1, 1, 0.90088, 1, 0.97455, 0.93582, 0.90088, 1, 1.05686, 0.8361, 0.99642, 0.99642, 0.99642, 0.72851, 0.90838, 0.90838, 0.90838, 0.90838, 0.90838, 0.90838, 0.868, 0.82391, 0.80061, 0.80061, 0.80061, 0.80061, 1.0258, 1.0258, 1.0258, 1.0258, 0.97484, 0.95546, 0.92179, 0.92179, 0.92179, 0.92179, 0.92179, 1.02058, 0.92179, 0.94438, 0.94438, 0.94438, 0.94438, 0.90406, 0.86958, 0.98225, 0.94938, 0.94938, 0.94938, 0.94938, 0.94938, 0.94938, 0.9031, 0.81093, 0.94938, 0.94938, 0.94938, 0.94938, 0.98621, 0.98621, 0.98621, 0.98621, 0.93969, 0.95933, 0.9446, 0.9446, 0.9446, 0.9446, 0.9446, 1.08595, 0.9446, 0.95442, 0.95442, 0.95442, 0.95442, 0.94039, 0.97898, 0.94039, 0.90838, 0.94938, 0.90838, 0.94938, 0.90838, 0.94938, 0.82391, 0.81093, 0.82391, 0.81093, 0.82391, 0.81093, 0.82391, 0.81093, 0.96376, 0.84313, 0.97484, 0.97571, 0.80061, 0.94938, 0.80061, 0.94938, 0.80061, 0.94938, 0.80061, 0.94938, 0.80061, 0.94938, 0.8768, 0.9577, 0.8768, 0.9577, 0.8768, 0.9577, 1, 1, 0.95407, 0.95933, 0.97069, 0.95933, 1.0258, 0.98621, 1.0258, 0.98621, 1.0258, 0.98621, 1.0258, 0.98621, 1.0258, 0.98621, 0.887, 1.01591, 0.73901, 1.0474, 1, 1, 0.97455, 0.83655, 0.98981, 1, 1, 0.83655, 0.73977, 0.83655, 0.73903, 0.84638, 1.033, 0.95546, 0.95933, 1, 1, 0.95546, 0.95933, 0.8271, 0.95417, 0.95933, 0.92179, 0.9446, 0.92179, 0.9446, 0.92179, 0.9446, 0.936, 0.91964, 0.82114, 0.97646, 1, 1, 0.82114, 0.97646, 0.8096, 0.78036, 0.8096, 0.78036, 1, 1, 0.8096, 0.78036, 1, 1, 0.89713, 0.77452, 0.89713, 1.10208, 0.94438, 0.95442, 0.94438, 0.95442, 0.94438, 0.95442, 0.94438, 0.95442, 0.94438, 0.95442, 0.94438, 0.95442, 0.94083, 0.97579, 0.90406, 0.94039, 0.90406, 0.9446, 0.938, 0.9446, 0.938, 0.9446, 0.938, 1, 0.99793, 0.90838, 0.94938, 0.868, 0.9031, 0.92179, 0.9446, 1, 1, 0.89713, 1.10208, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90989, 0.9358, 0.91945, 0.83181, 0.75261, 0.87992, 0.82976, 0.96034, 0.83689, 0.97268, 1.0078, 0.90838, 0.83637, 0.8019, 0.90157, 0.80061, 0.9446, 0.95407, 0.92436, 1.0258, 0.85022, 0.97153, 1.0156, 0.95546, 0.89192, 0.92179, 0.92361, 0.87107, 0.96318, 0.89713, 0.93704, 0.95638, 0.91905, 0.91709, 0.92796, 1.0258, 0.93704, 0.94836, 1.0373, 0.95933, 1.0078, 0.95871, 0.94836, 0.96174, 0.92601, 0.9498, 0.98607, 0.95776, 0.95933, 1.05453, 1.0078, 0.98275, 0.9314, 0.95617, 0.91701, 1.05993, 0.9446, 0.78367, 0.9553, 1, 0.86832, 1.0128, 0.95871, 0.99394, 0.87548, 0.96361, 0.86774, 1.0078, 0.95871, 0.9446, 0.95871, 0.86774, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.94083, 0.97579, 0.94083, 0.97579, 0.94083, 0.97579, 0.90406, 0.94039, 0.96694, 1, 0.89903, 1, 1, 1, 0.93582, 0.93582, 0.93582, 1, 0.908, 0.908, 0.918, 0.94219, 0.94219, 0.96544, 1, 1.285, 1, 1, 0.81079, 0.81079, 1, 1, 0.74854, 1, 1, 1, 1, 0.99793, 1, 1, 1, 0.65, 1, 1.36145, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.17173, 1, 0.80535, 0.76169, 1.02058, 1.0732, 1.05486, 1, 1, 1.30692, 1.08595, 1.08595, 1, 1.08595, 1.08595, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.16161, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.MyriadProBoldFactors = MyriadProBoldFactors;
const MyriadProBoldMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.MyriadProBoldMetrics = MyriadProBoldMetrics;
const MyriadProBoldItalicFactors = [1.36898, 1, 1, 0.66227, 0.80779, 0.81625, 0.97276, 0.97276, 0.97733, 0.92222, 0.83266, 0.94292, 0.94292, 1.16148, 1.02058, 0.93582, 0.96694, 0.93582, 1.17337, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.97276, 0.78076, 0.78076, 1.02058, 1.02058, 1.02058, 0.71541, 0.76813, 0.85576, 0.80591, 0.80729, 0.94299, 0.77512, 0.83655, 0.86523, 0.92222, 0.98621, 0.71743, 0.81698, 0.79726, 0.98558, 0.92222, 0.90637, 0.83809, 0.90637, 0.80729, 0.76463, 0.86275, 0.90699, 0.91605, 0.9154, 0.85308, 0.85458, 0.90531, 0.94292, 1.21296, 0.94292, 1.02058, 0.89903, 1.18616, 0.99613, 0.91677, 0.78216, 0.91677, 0.90083, 0.98796, 0.9135, 0.92168, 0.95381, 0.98981, 0.95298, 0.95381, 0.93459, 0.92168, 0.91513, 0.92004, 0.91677, 0.95077, 0.748, 1.04502, 0.91677, 0.92061, 0.94236, 0.89544, 0.89364, 0.9, 0.80687, 0.8578, 0.80687, 1.02058, 0.80779, 0.97276, 0.97276, 0.97276, 0.97276, 0.8578, 0.99973, 1.18616, 0.91339, 1.08074, 0.82891, 1.02058, 0.55509, 0.71526, 0.89022, 1.08595, 1, 1, 1.18616, 1, 0.96736, 0.93582, 1.18616, 1, 1.04864, 0.82711, 0.99043, 0.99043, 0.99043, 0.71541, 0.85576, 0.85576, 0.85576, 0.85576, 0.85576, 0.85576, 0.845, 0.80729, 0.77512, 0.77512, 0.77512, 0.77512, 0.98621, 0.98621, 0.98621, 0.98621, 0.95961, 0.92222, 0.90637, 0.90637, 0.90637, 0.90637, 0.90637, 1.02058, 0.90251, 0.90699, 0.90699, 0.90699, 0.90699, 0.85458, 0.83659, 0.94951, 0.99613, 0.99613, 0.99613, 0.99613, 0.99613, 0.99613, 0.85811, 0.78216, 0.90083, 0.90083, 0.90083, 0.90083, 0.95381, 0.95381, 0.95381, 0.95381, 0.9135, 0.92168, 0.91513, 0.91513, 0.91513, 0.91513, 0.91513, 1.08595, 0.91677, 0.91677, 0.91677, 0.91677, 0.91677, 0.89364, 0.92332, 0.89364, 0.85576, 0.99613, 0.85576, 0.99613, 0.85576, 0.99613, 0.80729, 0.78216, 0.80729, 0.78216, 0.80729, 0.78216, 0.80729, 0.78216, 0.94299, 0.76783, 0.95961, 0.91677, 0.77512, 0.90083, 0.77512, 0.90083, 0.77512, 0.90083, 0.77512, 0.90083, 0.77512, 0.90083, 0.86523, 0.9135, 0.86523, 0.9135, 0.86523, 0.9135, 1, 1, 0.92222, 0.92168, 0.92222, 0.92168, 0.98621, 0.95381, 0.98621, 0.95381, 0.98621, 0.95381, 0.98621, 0.95381, 0.98621, 0.95381, 0.86036, 0.97096, 0.71743, 0.98981, 1, 1, 0.95298, 0.79726, 0.95381, 1, 1, 0.79726, 0.6894, 0.79726, 0.74321, 0.81691, 1.0006, 0.92222, 0.92168, 1, 1, 0.92222, 0.92168, 0.79464, 0.92098, 0.92168, 0.90637, 0.91513, 0.90637, 0.91513, 0.90637, 0.91513, 0.909, 0.87514, 0.80729, 0.95077, 1, 1, 0.80729, 0.95077, 0.76463, 0.748, 0.76463, 0.748, 1, 1, 0.76463, 0.748, 1, 1, 0.86275, 0.72651, 0.86275, 1.04502, 0.90699, 0.91677, 0.90699, 0.91677, 0.90699, 0.91677, 0.90699, 0.91677, 0.90699, 0.91677, 0.90699, 0.91677, 0.9154, 0.94236, 0.85458, 0.89364, 0.85458, 0.90531, 0.9, 0.90531, 0.9, 0.90531, 0.9, 1, 0.97276, 0.85576, 0.99613, 0.845, 0.85811, 0.90251, 0.91677, 1, 1, 0.86275, 1.04502, 1.18616, 1.18616, 1.18616, 1.18616, 1.18616, 1.18616, 1.18616, 1.18616, 1.18616, 1.00899, 1.30628, 0.85576, 0.80178, 0.66862, 0.7927, 0.69323, 0.88127, 0.72459, 0.89711, 0.95381, 0.85576, 0.80591, 0.7805, 0.94729, 0.77512, 0.90531, 0.92222, 0.90637, 0.98621, 0.81698, 0.92655, 0.98558, 0.92222, 0.85359, 0.90637, 0.90976, 0.83809, 0.94523, 0.86275, 0.83509, 0.93157, 0.85308, 0.83392, 0.92346, 0.98621, 0.83509, 0.92886, 0.91324, 0.92168, 0.95381, 0.90646, 0.92886, 0.90557, 0.86847, 0.90276, 0.91324, 0.86842, 0.92168, 0.99531, 0.95381, 0.9224, 0.85408, 0.92699, 0.86847, 1.0051, 0.91513, 0.80487, 0.93481, 1, 0.88159, 1.05214, 0.90646, 0.97355, 0.81539, 0.89398, 0.85923, 0.95381, 0.90646, 0.91513, 0.90646, 0.85923, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9154, 0.94236, 0.9154, 0.94236, 0.9154, 0.94236, 0.85458, 0.89364, 0.96694, 1, 0.89903, 1, 1, 1, 0.91782, 0.91782, 0.91782, 1, 0.896, 0.896, 0.896, 0.9332, 0.9332, 0.95973, 1, 1.26, 1, 1, 0.80479, 0.80178, 1, 1, 0.85633, 1, 1, 1, 1, 0.97276, 1, 1, 1, 0.698, 1, 1.36145, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.14542, 1, 0.79199, 0.78694, 1.02058, 1.03493, 1.05486, 1, 1, 1.23026, 1.08595, 1.08595, 1, 1.08595, 1.08595, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.20006, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.MyriadProBoldItalicFactors = MyriadProBoldItalicFactors;
const MyriadProBoldItalicMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.MyriadProBoldItalicMetrics = MyriadProBoldItalicMetrics;
const MyriadProItalicFactors = [1.36898, 1, 1, 0.65507, 0.84943, 0.85639, 0.88465, 0.88465, 0.86936, 0.88307, 0.86948, 0.85283, 0.85283, 1.06383, 1.02058, 0.75945, 0.9219, 0.75945, 1.17337, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.88465, 0.75945, 0.75945, 1.02058, 1.02058, 1.02058, 0.69046, 0.70926, 0.85158, 0.77812, 0.76852, 0.89591, 0.70466, 0.76125, 0.80094, 0.86822, 0.83864, 0.728, 0.77212, 0.79475, 0.93637, 0.87514, 0.8588, 0.76013, 0.8588, 0.72421, 0.69866, 0.77598, 0.85991, 0.80811, 0.87832, 0.78112, 0.77512, 0.8562, 1.0222, 1.18417, 1.0222, 1.27014, 0.89903, 1.15012, 0.93859, 0.94399, 0.846, 0.94399, 0.81453, 1.0186, 0.94219, 0.96017, 1.03075, 1.02175, 0.912, 1.03075, 0.96998, 0.96017, 0.93859, 0.94399, 0.94399, 0.95493, 0.746, 1.12658, 0.94578, 0.91, 0.979, 0.882, 0.882, 0.83, 0.85034, 0.83537, 0.85034, 1.02058, 0.70869, 0.88465, 0.88465, 0.88465, 0.88465, 0.83537, 0.90083, 1.15012, 0.9161, 0.94565, 0.73541, 1.02058, 0.53609, 0.69353, 0.79519, 1.08595, 1, 1, 1.15012, 1, 0.91974, 0.75945, 1.15012, 1, 0.9446, 0.73361, 0.9005, 0.9005, 0.9005, 0.62864, 0.85158, 0.85158, 0.85158, 0.85158, 0.85158, 0.85158, 0.773, 0.76852, 0.70466, 0.70466, 0.70466, 0.70466, 0.83864, 0.83864, 0.83864, 0.83864, 0.90561, 0.87514, 0.8588, 0.8588, 0.8588, 0.8588, 0.8588, 1.02058, 0.85751, 0.85991, 0.85991, 0.85991, 0.85991, 0.77512, 0.76013, 0.88075, 0.93859, 0.93859, 0.93859, 0.93859, 0.93859, 0.93859, 0.8075, 0.846, 0.81453, 0.81453, 0.81453, 0.81453, 0.82424, 0.82424, 0.82424, 0.82424, 0.9278, 0.96017, 0.93859, 0.93859, 0.93859, 0.93859, 0.93859, 1.08595, 0.8562, 0.94578, 0.94578, 0.94578, 0.94578, 0.882, 0.94578, 0.882, 0.85158, 0.93859, 0.85158, 0.93859, 0.85158, 0.93859, 0.76852, 0.846, 0.76852, 0.846, 0.76852, 0.846, 0.76852, 0.846, 0.89591, 0.8544, 0.90561, 0.94399, 0.70466, 0.81453, 0.70466, 0.81453, 0.70466, 0.81453, 0.70466, 0.81453, 0.70466, 0.81453, 0.80094, 0.94219, 0.80094, 0.94219, 0.80094, 0.94219, 1, 1, 0.86822, 0.96017, 0.86822, 0.96017, 0.83864, 0.82424, 0.83864, 0.82424, 0.83864, 0.82424, 0.83864, 1.03075, 0.83864, 0.82424, 0.81402, 1.02738, 0.728, 1.02175, 1, 1, 0.912, 0.79475, 1.03075, 1, 1, 0.79475, 0.83911, 0.79475, 0.66266, 0.80553, 1.06676, 0.87514, 0.96017, 1, 1, 0.87514, 0.96017, 0.86865, 0.87396, 0.96017, 0.8588, 0.93859, 0.8588, 0.93859, 0.8588, 0.93859, 0.867, 0.84759, 0.72421, 0.95493, 1, 1, 0.72421, 0.95493, 0.69866, 0.746, 0.69866, 0.746, 1, 1, 0.69866, 0.746, 1, 1, 0.77598, 0.88417, 0.77598, 1.12658, 0.85991, 0.94578, 0.85991, 0.94578, 0.85991, 0.94578, 0.85991, 0.94578, 0.85991, 0.94578, 0.85991, 0.94578, 0.87832, 0.979, 0.77512, 0.882, 0.77512, 0.8562, 0.83, 0.8562, 0.83, 0.8562, 0.83, 1, 0.88465, 0.85158, 0.93859, 0.773, 0.8075, 0.85751, 0.8562, 1, 1, 0.77598, 1.12658, 1.15012, 1.15012, 1.15012, 1.15012, 1.15012, 1.15313, 1.15012, 1.15012, 1.15012, 1.08106, 1.03901, 0.85158, 0.77025, 0.62264, 0.7646, 0.65351, 0.86026, 0.69461, 0.89947, 1.03075, 0.85158, 0.77812, 0.76449, 0.88836, 0.70466, 0.8562, 0.86822, 0.8588, 0.83864, 0.77212, 0.85308, 0.93637, 0.87514, 0.82352, 0.8588, 0.85701, 0.76013, 0.89058, 0.77598, 0.8156, 0.82565, 0.78112, 0.77899, 0.89386, 0.83864, 0.8156, 0.9486, 0.92388, 0.96186, 1.03075, 0.91123, 0.9486, 0.93298, 0.878, 0.93942, 0.92388, 0.84596, 0.96186, 0.95119, 1.03075, 0.922, 0.88787, 0.95829, 0.88, 0.93559, 0.93859, 0.78815, 0.93758, 1, 0.89217, 1.03737, 0.91123, 0.93969, 0.77487, 0.85769, 0.86799, 1.03075, 0.91123, 0.93859, 0.91123, 0.86799, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.87832, 0.979, 0.87832, 0.979, 0.87832, 0.979, 0.77512, 0.882, 0.9219, 1, 0.89903, 1, 1, 1, 0.87321, 0.87321, 0.87321, 1, 1.027, 1.027, 1.027, 0.86847, 0.86847, 0.79121, 1, 1.124, 1, 1, 0.73572, 0.73572, 1, 1, 0.85034, 1, 1, 1, 1, 0.88465, 1, 1, 1, 0.669, 1, 1.36145, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.04828, 1, 0.74948, 0.75187, 1.02058, 0.98391, 1.02119, 1, 1, 1.06233, 1.08595, 1.08595, 1, 1.08595, 1.08595, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05233, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.MyriadProItalicFactors = MyriadProItalicFactors;
const MyriadProItalicMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.MyriadProItalicMetrics = MyriadProItalicMetrics;
const MyriadProRegularFactors = [1.36898, 1, 1, 0.76305, 0.82784, 0.94935, 0.89364, 0.92241, 0.89073, 0.90706, 0.98472, 0.85283, 0.85283, 1.0664, 1.02058, 0.74505, 0.9219, 0.74505, 1.23456, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.92241, 0.74505, 0.74505, 1.02058, 1.02058, 1.02058, 0.73002, 0.72601, 0.91755, 0.8126, 0.80314, 0.92222, 0.73764, 0.79726, 0.83051, 0.90284, 0.86023, 0.74, 0.8126, 0.84869, 0.96518, 0.91115, 0.8858, 0.79761, 0.8858, 0.74498, 0.73914, 0.81363, 0.89591, 0.83659, 0.89633, 0.85608, 0.8111, 0.90531, 1.0222, 1.22736, 1.0222, 1.27014, 0.89903, 0.90088, 0.86667, 1.0231, 0.896, 1.01411, 0.90083, 1.05099, 1.00512, 0.99793, 1.05326, 1.09377, 0.938, 1.06226, 1.00119, 0.99793, 0.98714, 1.0231, 1.01231, 0.98196, 0.792, 1.19137, 0.99074, 0.962, 1.01915, 0.926, 0.942, 0.856, 0.85034, 0.92006, 0.85034, 1.02058, 0.69067, 0.92241, 0.92241, 0.92241, 0.92241, 0.92006, 0.9332, 0.90088, 0.91882, 0.93484, 0.75339, 1.02058, 0.56866, 0.54324, 0.79519, 1.08595, 1, 1, 0.90088, 1, 0.95325, 0.74505, 0.90088, 1, 0.97198, 0.75339, 0.91009, 0.91009, 0.91009, 0.66466, 0.91755, 0.91755, 0.91755, 0.91755, 0.91755, 0.91755, 0.788, 0.80314, 0.73764, 0.73764, 0.73764, 0.73764, 0.86023, 0.86023, 0.86023, 0.86023, 0.92915, 0.91115, 0.8858, 0.8858, 0.8858, 0.8858, 0.8858, 1.02058, 0.8858, 0.89591, 0.89591, 0.89591, 0.89591, 0.8111, 0.79611, 0.89713, 0.86667, 0.86667, 0.86667, 0.86667, 0.86667, 0.86667, 0.86936, 0.896, 0.90083, 0.90083, 0.90083, 0.90083, 0.84224, 0.84224, 0.84224, 0.84224, 0.97276, 0.99793, 0.98714, 0.98714, 0.98714, 0.98714, 0.98714, 1.08595, 0.89876, 0.99074, 0.99074, 0.99074, 0.99074, 0.942, 1.0231, 0.942, 0.91755, 0.86667, 0.91755, 0.86667, 0.91755, 0.86667, 0.80314, 0.896, 0.80314, 0.896, 0.80314, 0.896, 0.80314, 0.896, 0.92222, 0.93372, 0.92915, 1.01411, 0.73764, 0.90083, 0.73764, 0.90083, 0.73764, 0.90083, 0.73764, 0.90083, 0.73764, 0.90083, 0.83051, 1.00512, 0.83051, 1.00512, 0.83051, 1.00512, 1, 1, 0.90284, 0.99793, 0.90976, 0.99793, 0.86023, 0.84224, 0.86023, 0.84224, 0.86023, 0.84224, 0.86023, 1.05326, 0.86023, 0.84224, 0.82873, 1.07469, 0.74, 1.09377, 1, 1, 0.938, 0.84869, 1.06226, 1, 1, 0.84869, 0.83704, 0.84869, 0.81441, 0.85588, 1.08927, 0.91115, 0.99793, 1, 1, 0.91115, 0.99793, 0.91887, 0.90991, 0.99793, 0.8858, 0.98714, 0.8858, 0.98714, 0.8858, 0.98714, 0.894, 0.91434, 0.74498, 0.98196, 1, 1, 0.74498, 0.98196, 0.73914, 0.792, 0.73914, 0.792, 1, 1, 0.73914, 0.792, 1, 1, 0.81363, 0.904, 0.81363, 1.19137, 0.89591, 0.99074, 0.89591, 0.99074, 0.89591, 0.99074, 0.89591, 0.99074, 0.89591, 0.99074, 0.89591, 0.99074, 0.89633, 1.01915, 0.8111, 0.942, 0.8111, 0.90531, 0.856, 0.90531, 0.856, 0.90531, 0.856, 1, 0.92241, 0.91755, 0.86667, 0.788, 0.86936, 0.8858, 0.89876, 1, 1, 0.81363, 1.19137, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90088, 0.90388, 1.03901, 0.92138, 0.78105, 0.7154, 0.86169, 0.80513, 0.94007, 0.82528, 0.98612, 1.06226, 0.91755, 0.8126, 0.81884, 0.92819, 0.73764, 0.90531, 0.90284, 0.8858, 0.86023, 0.8126, 0.91172, 0.96518, 0.91115, 0.83089, 0.8858, 0.87791, 0.79761, 0.89297, 0.81363, 0.88157, 0.89992, 0.85608, 0.81992, 0.94307, 0.86023, 0.88157, 0.95308, 0.98699, 0.99793, 1.06226, 0.95817, 0.95308, 0.97358, 0.928, 0.98088, 0.98699, 0.92761, 0.99793, 0.96017, 1.06226, 0.986, 0.944, 0.95978, 0.938, 0.96705, 0.98714, 0.80442, 0.98972, 1, 0.89762, 1.04552, 0.95817, 0.99007, 0.87064, 0.91879, 0.88888, 1.06226, 0.95817, 0.98714, 0.95817, 0.88888, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.89633, 1.01915, 0.89633, 1.01915, 0.89633, 1.01915, 0.8111, 0.942, 0.9219, 1, 0.89903, 1, 1, 1, 0.93173, 0.93173, 0.93173, 1, 1.06304, 1.06304, 1.06904, 0.89903, 0.89903, 0.80549, 1, 1.156, 1, 1, 0.76575, 0.76575, 1, 1, 0.72458, 1, 1, 1, 1, 0.92241, 1, 1, 1, 0.619, 1, 1.36145, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.07257, 1, 0.74705, 0.71119, 1.02058, 1.024, 1.02119, 1, 1, 1.1536, 1.08595, 1.08595, 1, 1.08595, 1.08595, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.05638, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.MyriadProRegularFactors = MyriadProRegularFactors;
const MyriadProRegularMetrics = {
  lineHeight: 1.2,
  lineGap: 0.2
};
exports.MyriadProRegularMetrics = MyriadProRegularMetrics;

/***/ }),
/* 54 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.SegoeuiRegularMetrics = exports.SegoeuiRegularFactors = exports.SegoeuiItalicMetrics = exports.SegoeuiItalicFactors = exports.SegoeuiBoldMetrics = exports.SegoeuiBoldItalicMetrics = exports.SegoeuiBoldItalicFactors = exports.SegoeuiBoldFactors = void 0;
const SegoeuiBoldFactors = [1.76738, 1, 1, 0.99297, 0.9824, 1.04016, 1.06497, 1.03424, 0.97529, 1.17647, 1.23203, 1.1085, 1.1085, 1.16939, 1.2107, 0.9754, 1.21408, 0.9754, 1.59578, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 1.03424, 0.81378, 0.81378, 1.2107, 1.2107, 1.2107, 0.71703, 0.97847, 0.97363, 0.88776, 0.8641, 1.02096, 0.79795, 0.85132, 0.914, 1.06085, 1.1406, 0.8007, 0.89858, 0.83693, 1.14889, 1.09398, 0.97489, 0.92094, 0.97489, 0.90399, 0.84041, 0.95923, 1.00135, 1, 1.06467, 0.98243, 0.90996, 0.99361, 1.1085, 1.56942, 1.1085, 1.2107, 0.74627, 0.94282, 0.96752, 1.01519, 0.86304, 1.01359, 0.97278, 1.15103, 1.01359, 0.98561, 1.02285, 1.02285, 1.00527, 1.02285, 1.0302, 0.99041, 1.0008, 1.01519, 1.01359, 1.02258, 0.79104, 1.16862, 0.99041, 0.97454, 1.02511, 0.99298, 0.96752, 0.95801, 0.94856, 1.16579, 0.94856, 1.2107, 0.9824, 1.03424, 1.03424, 1, 1.03424, 1.16579, 0.8727, 1.3871, 1.18622, 1.10818, 1.04478, 1.2107, 1.18622, 0.75155, 0.94994, 1.28826, 1.21408, 1.21408, 0.91056, 1, 0.91572, 0.9754, 0.64663, 1.18328, 1.24866, 1.04478, 1.14169, 1.15749, 1.17389, 0.71703, 0.97363, 0.97363, 0.97363, 0.97363, 0.97363, 0.97363, 0.93506, 0.8641, 0.79795, 0.79795, 0.79795, 0.79795, 1.1406, 1.1406, 1.1406, 1.1406, 1.02096, 1.09398, 0.97426, 0.97426, 0.97426, 0.97426, 0.97426, 1.2107, 0.97489, 1.00135, 1.00135, 1.00135, 1.00135, 0.90996, 0.92094, 1.02798, 0.96752, 0.96752, 0.96752, 0.96752, 0.96752, 0.96752, 0.93136, 0.86304, 0.97278, 0.97278, 0.97278, 0.97278, 1.02285, 1.02285, 1.02285, 1.02285, 0.97122, 0.99041, 1, 1, 1, 1, 1, 1.28826, 1.0008, 0.99041, 0.99041, 0.99041, 0.99041, 0.96752, 1.01519, 0.96752, 0.97363, 0.96752, 0.97363, 0.96752, 0.97363, 0.96752, 0.8641, 0.86304, 0.8641, 0.86304, 0.8641, 0.86304, 0.8641, 0.86304, 1.02096, 1.03057, 1.02096, 1.03517, 0.79795, 0.97278, 0.79795, 0.97278, 0.79795, 0.97278, 0.79795, 0.97278, 0.79795, 0.97278, 0.914, 1.01359, 0.914, 1.01359, 0.914, 1.01359, 1, 1, 1.06085, 0.98561, 1.06085, 1.00879, 1.1406, 1.02285, 1.1406, 1.02285, 1.1406, 1.02285, 1.1406, 1.02285, 1.1406, 1.02285, 0.97138, 1.08692, 0.8007, 1.02285, 1, 1, 1.00527, 0.83693, 1.02285, 1, 1, 0.83693, 0.9455, 0.83693, 0.90418, 0.83693, 1.13005, 1.09398, 0.99041, 1, 1, 1.09398, 0.99041, 0.96692, 1.09251, 0.99041, 0.97489, 1.0008, 0.97489, 1.0008, 0.97489, 1.0008, 0.93994, 0.97931, 0.90399, 1.02258, 1, 1, 0.90399, 1.02258, 0.84041, 0.79104, 0.84041, 0.79104, 0.84041, 0.79104, 0.84041, 0.79104, 1, 1, 0.95923, 1.07034, 0.95923, 1.16862, 1.00135, 0.99041, 1.00135, 0.99041, 1.00135, 0.99041, 1.00135, 0.99041, 1.00135, 0.99041, 1.00135, 0.99041, 1.06467, 1.02511, 0.90996, 0.96752, 0.90996, 0.99361, 0.95801, 0.99361, 0.95801, 0.99361, 0.95801, 1.07733, 1.03424, 0.97363, 0.96752, 0.93506, 0.93136, 0.97489, 1.0008, 1, 1, 0.95923, 1.16862, 1.15103, 1.15103, 1.01173, 1.03959, 0.75953, 0.81378, 0.79912, 1.15103, 1.21994, 0.95161, 0.87815, 1.01149, 0.81525, 0.7676, 0.98167, 1.01134, 1.02546, 0.84097, 1.03089, 1.18102, 0.97363, 0.88776, 0.85134, 0.97826, 0.79795, 0.99361, 1.06085, 0.97489, 1.1406, 0.89858, 1.0388, 1.14889, 1.09398, 0.86039, 0.97489, 1.0595, 0.92094, 0.94793, 0.95923, 0.90996, 0.99346, 0.98243, 1.02112, 0.95493, 1.1406, 0.90996, 1.03574, 1.02597, 1.0008, 1.18102, 1.06628, 1.03574, 1.0192, 1.01932, 1.00886, 0.97531, 1.0106, 1.0008, 1.13189, 1.18102, 1.02277, 0.98683, 1.0016, 0.99561, 1.07237, 1.0008, 0.90434, 0.99921, 0.93803, 0.8965, 1.23085, 1.06628, 1.04983, 0.96268, 1.0499, 0.98439, 1.18102, 1.06628, 1.0008, 1.06628, 0.98439, 0.79795, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09466, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.97278, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.02065, 1, 1, 1, 1, 1, 1, 1.06467, 1.02511, 1.06467, 1.02511, 1.06467, 1.02511, 0.90996, 0.96752, 1, 1.21408, 0.89903, 1, 1, 0.75155, 1.04394, 1.04394, 1.04394, 1.04394, 0.98633, 0.98633, 0.98633, 0.73047, 0.73047, 1.20642, 0.91211, 1.25635, 1.222, 1.02956, 1.03372, 1.03372, 0.96039, 1.24633, 1, 1.12454, 0.93503, 1.03424, 1.19687, 1.03424, 1, 1, 1, 0.771, 1, 1, 1.15749, 1.15749, 1.15749, 1.10948, 0.86279, 0.94434, 0.86279, 0.94434, 0.86182, 1, 1, 1.16897, 1, 0.96085, 0.90137, 1.2107, 1.18416, 1.13973, 0.69825, 0.9716, 2.10339, 1.29004, 1.29004, 1.21172, 1.29004, 1.29004, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.42603, 1, 0.99862, 0.99862, 1, 0.87025, 0.87025, 0.87025, 0.87025, 1.18874, 1.42603, 1, 1.42603, 1.42603, 0.99862, 1, 1, 1, 1, 1, 1.2886, 1.04315, 1.15296, 1.34163, 1, 1, 1, 1.09193, 1.09193, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.SegoeuiBoldFactors = SegoeuiBoldFactors;
const SegoeuiBoldMetrics = {
  lineHeight: 1.33008,
  lineGap: 0
};
exports.SegoeuiBoldMetrics = SegoeuiBoldMetrics;
const SegoeuiBoldItalicFactors = [1.76738, 1, 1, 0.98946, 1.03959, 1.04016, 1.02809, 1.036, 0.97639, 1.10953, 1.23203, 1.11144, 1.11144, 1.16939, 1.21237, 0.9754, 1.21261, 0.9754, 1.59754, 1.036, 1.036, 1.036, 1.036, 1.036, 1.036, 1.036, 1.036, 1.036, 1.036, 0.81378, 0.81378, 1.21237, 1.21237, 1.21237, 0.73541, 0.97847, 0.97363, 0.89723, 0.87897, 1.0426, 0.79429, 0.85292, 0.91149, 1.05815, 1.1406, 0.79631, 0.90128, 0.83853, 1.04396, 1.10615, 0.97552, 0.94436, 0.97552, 0.88641, 0.80527, 0.96083, 1.00135, 1, 1.06777, 0.9817, 0.91142, 0.99361, 1.11144, 1.57293, 1.11144, 1.21237, 0.74627, 1.31818, 1.06585, 0.97042, 0.83055, 0.97042, 0.93503, 1.1261, 0.97042, 0.97922, 1.14236, 0.94552, 1.01054, 1.14236, 1.02471, 0.97922, 0.94165, 0.97042, 0.97042, 1.0276, 0.78929, 1.1261, 0.97922, 0.95874, 1.02197, 0.98507, 0.96752, 0.97168, 0.95107, 1.16579, 0.95107, 1.21237, 1.03959, 1.036, 1.036, 1, 1.036, 1.16579, 0.87357, 1.31818, 1.18754, 1.26781, 1.05356, 1.21237, 1.18622, 0.79487, 0.94994, 1.29004, 1.24047, 1.24047, 1.31818, 1, 0.91484, 0.9754, 1.31818, 1.1349, 1.24866, 1.05356, 1.13934, 1.15574, 1.17389, 0.73541, 0.97363, 0.97363, 0.97363, 0.97363, 0.97363, 0.97363, 0.94385, 0.87897, 0.79429, 0.79429, 0.79429, 0.79429, 1.1406, 1.1406, 1.1406, 1.1406, 1.0426, 1.10615, 0.97552, 0.97552, 0.97552, 0.97552, 0.97552, 1.21237, 0.97552, 1.00135, 1.00135, 1.00135, 1.00135, 0.91142, 0.94436, 0.98721, 1.06585, 1.06585, 1.06585, 1.06585, 1.06585, 1.06585, 0.96705, 0.83055, 0.93503, 0.93503, 0.93503, 0.93503, 1.14236, 1.14236, 1.14236, 1.14236, 0.93125, 0.97922, 0.94165, 0.94165, 0.94165, 0.94165, 0.94165, 1.29004, 0.94165, 0.97922, 0.97922, 0.97922, 0.97922, 0.96752, 0.97042, 0.96752, 0.97363, 1.06585, 0.97363, 1.06585, 0.97363, 1.06585, 0.87897, 0.83055, 0.87897, 0.83055, 0.87897, 0.83055, 0.87897, 0.83055, 1.0426, 1.0033, 1.0426, 0.97042, 0.79429, 0.93503, 0.79429, 0.93503, 0.79429, 0.93503, 0.79429, 0.93503, 0.79429, 0.93503, 0.91149, 0.97042, 0.91149, 0.97042, 0.91149, 0.97042, 1, 1, 1.05815, 0.97922, 1.05815, 0.97922, 1.1406, 1.14236, 1.1406, 1.14236, 1.1406, 1.14236, 1.1406, 1.14236, 1.1406, 1.14236, 0.97441, 1.04302, 0.79631, 1.01582, 1, 1, 1.01054, 0.83853, 1.14236, 1, 1, 0.83853, 1.09125, 0.83853, 0.90418, 0.83853, 1.19508, 1.10615, 0.97922, 1, 1, 1.10615, 0.97922, 1.01034, 1.10466, 0.97922, 0.97552, 0.94165, 0.97552, 0.94165, 0.97552, 0.94165, 0.91602, 0.91981, 0.88641, 1.0276, 1, 1, 0.88641, 1.0276, 0.80527, 0.78929, 0.80527, 0.78929, 0.80527, 0.78929, 0.80527, 0.78929, 1, 1, 0.96083, 1.05403, 0.95923, 1.16862, 1.00135, 0.97922, 1.00135, 0.97922, 1.00135, 0.97922, 1.00135, 0.97922, 1.00135, 0.97922, 1.00135, 0.97922, 1.06777, 1.02197, 0.91142, 0.96752, 0.91142, 0.99361, 0.97168, 0.99361, 0.97168, 0.99361, 0.97168, 1.23199, 1.036, 0.97363, 1.06585, 0.94385, 0.96705, 0.97552, 0.94165, 1, 1, 0.96083, 1.1261, 1.31818, 1.31818, 1.31818, 1.31818, 1.31818, 1.31818, 1.31818, 1.31818, 1.31818, 0.95161, 1.27126, 1.00811, 0.83284, 0.77702, 0.99137, 0.95253, 1.0347, 0.86142, 1.07205, 1.14236, 0.97363, 0.89723, 0.86869, 1.09818, 0.79429, 0.99361, 1.05815, 0.97552, 1.1406, 0.90128, 1.06662, 1.04396, 1.10615, 0.84918, 0.97552, 1.04694, 0.94436, 0.98015, 0.96083, 0.91142, 1.00356, 0.9817, 1.01945, 0.98999, 1.1406, 0.91142, 1.04961, 0.9898, 1.00639, 1.14236, 1.07514, 1.04961, 0.99607, 1.02897, 1.008, 0.9898, 0.95134, 1.00639, 1.11121, 1.14236, 1.00518, 0.97981, 1.02186, 1, 1.08578, 0.94165, 0.99314, 0.98387, 0.93028, 0.93377, 1.35125, 1.07514, 1.10687, 0.93491, 1.04232, 1.00351, 1.14236, 1.07514, 0.94165, 1.07514, 1.00351, 0.79429, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.09097, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.93503, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.96609, 1, 1, 1, 1, 1, 1, 1.06777, 1.02197, 1.06777, 1.02197, 1.06777, 1.02197, 0.91142, 0.96752, 1, 1.21261, 0.89903, 1, 1, 0.75155, 1.04745, 1.04745, 1.04745, 1.04394, 0.98633, 0.98633, 0.98633, 0.72959, 0.72959, 1.20502, 0.91406, 1.26514, 1.222, 1.02956, 1.03372, 1.03372, 0.96039, 1.24633, 1, 1.09125, 0.93327, 1.03336, 1.16541, 1.036, 1, 1, 1, 0.771, 1, 1, 1.15574, 1.15574, 1.15574, 1.15574, 0.86364, 0.94434, 0.86279, 0.94434, 0.86224, 1, 1, 1.16798, 1, 0.96085, 0.90068, 1.21237, 1.18416, 1.13904, 0.69825, 0.9716, 2.10339, 1.29004, 1.29004, 1.21339, 1.29004, 1.29004, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.42603, 1, 0.99862, 0.99862, 1, 0.87025, 0.87025, 0.87025, 0.87025, 1.18775, 1.42603, 1, 1.42603, 1.42603, 0.99862, 1, 1, 1, 1, 1, 1.2886, 1.04315, 1.15296, 1.34163, 1, 1, 1, 1.13269, 1.13269, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.SegoeuiBoldItalicFactors = SegoeuiBoldItalicFactors;
const SegoeuiBoldItalicMetrics = {
  lineHeight: 1.33008,
  lineGap: 0
};
exports.SegoeuiBoldItalicMetrics = SegoeuiBoldItalicMetrics;
const SegoeuiItalicFactors = [1.76738, 1, 1, 0.98946, 1.14763, 1.05365, 1.06234, 0.96927, 0.92586, 1.15373, 1.18414, 0.91349, 0.91349, 1.07403, 1.17308, 0.78383, 1.20088, 0.78383, 1.42531, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.78383, 0.78383, 1.17308, 1.17308, 1.17308, 0.77349, 0.94565, 0.94729, 0.85944, 0.88506, 0.9858, 0.74817, 0.80016, 0.88449, 0.98039, 0.95782, 0.69238, 0.89898, 0.83231, 0.98183, 1.03989, 0.96924, 0.86237, 0.96924, 0.80595, 0.74524, 0.86091, 0.95402, 0.94143, 0.98448, 0.8858, 0.83089, 0.93285, 1.0949, 1.39016, 1.0949, 1.45994, 0.74627, 1.04839, 0.97454, 0.97454, 0.87207, 0.97454, 0.87533, 1.06151, 0.97454, 1.00176, 1.16484, 1.08132, 0.98047, 1.16484, 1.02989, 1.01054, 0.96225, 0.97454, 0.97454, 1.06598, 0.79004, 1.16344, 1.00351, 0.94629, 0.9973, 0.91016, 0.96777, 0.9043, 0.91082, 0.92481, 0.91082, 1.17308, 0.95748, 0.96927, 0.96927, 1, 0.96927, 0.92481, 0.80597, 1.04839, 1.23393, 1.1781, 0.9245, 1.17308, 1.20808, 0.63218, 0.94261, 1.24822, 1.09971, 1.09971, 1.04839, 1, 0.85273, 0.78032, 1.04839, 1.09971, 1.22326, 0.9245, 1.09836, 1.13525, 1.15222, 0.70424, 0.94729, 0.94729, 0.94729, 0.94729, 0.94729, 0.94729, 0.85498, 0.88506, 0.74817, 0.74817, 0.74817, 0.74817, 0.95782, 0.95782, 0.95782, 0.95782, 0.9858, 1.03989, 0.96924, 0.96924, 0.96924, 0.96924, 0.96924, 1.17308, 0.96924, 0.95402, 0.95402, 0.95402, 0.95402, 0.83089, 0.86237, 0.88409, 0.97454, 0.97454, 0.97454, 0.97454, 0.97454, 0.97454, 0.92916, 0.87207, 0.87533, 0.87533, 0.87533, 0.87533, 0.93146, 0.93146, 0.93146, 0.93146, 0.93854, 1.01054, 0.96225, 0.96225, 0.96225, 0.96225, 0.96225, 1.24822, 0.8761, 1.00351, 1.00351, 1.00351, 1.00351, 0.96777, 0.97454, 0.96777, 0.94729, 0.97454, 0.94729, 0.97454, 0.94729, 0.97454, 0.88506, 0.87207, 0.88506, 0.87207, 0.88506, 0.87207, 0.88506, 0.87207, 0.9858, 0.95391, 0.9858, 0.97454, 0.74817, 0.87533, 0.74817, 0.87533, 0.74817, 0.87533, 0.74817, 0.87533, 0.74817, 0.87533, 0.88449, 0.97454, 0.88449, 0.97454, 0.88449, 0.97454, 1, 1, 0.98039, 1.00176, 0.98039, 1.00176, 0.95782, 0.93146, 0.95782, 0.93146, 0.95782, 0.93146, 0.95782, 1.16484, 0.95782, 0.93146, 0.84421, 1.12761, 0.69238, 1.08132, 1, 1, 0.98047, 0.83231, 1.16484, 1, 1, 0.84723, 1.04861, 0.84723, 0.78755, 0.83231, 1.23736, 1.03989, 1.01054, 1, 1, 1.03989, 1.01054, 0.9857, 1.03849, 1.01054, 0.96924, 0.96225, 0.96924, 0.96225, 0.96924, 0.96225, 0.92383, 0.90171, 0.80595, 1.06598, 1, 1, 0.80595, 1.06598, 0.74524, 0.79004, 0.74524, 0.79004, 0.74524, 0.79004, 0.74524, 0.79004, 1, 1, 0.86091, 1.02759, 0.85771, 1.16344, 0.95402, 1.00351, 0.95402, 1.00351, 0.95402, 1.00351, 0.95402, 1.00351, 0.95402, 1.00351, 0.95402, 1.00351, 0.98448, 0.9973, 0.83089, 0.96777, 0.83089, 0.93285, 0.9043, 0.93285, 0.9043, 0.93285, 0.9043, 1.31868, 0.96927, 0.94729, 0.97454, 0.85498, 0.92916, 0.96924, 0.8761, 1, 1, 0.86091, 1.16344, 1.04839, 1.04839, 1.04839, 1.04839, 1.04839, 1.04839, 1.04839, 1.04839, 1.04839, 0.81965, 0.81965, 0.94729, 0.78032, 0.71022, 0.90883, 0.84171, 0.99877, 0.77596, 1.05734, 1.2, 0.94729, 0.85944, 0.82791, 0.9607, 0.74817, 0.93285, 0.98039, 0.96924, 0.95782, 0.89898, 0.98316, 0.98183, 1.03989, 0.78614, 0.96924, 0.97642, 0.86237, 0.86075, 0.86091, 0.83089, 0.90082, 0.8858, 0.97296, 1.01284, 0.95782, 0.83089, 1.0976, 1.04, 1.03342, 1.2, 1.0675, 1.0976, 0.98205, 1.03809, 1.05097, 1.04, 0.95364, 1.03342, 1.05401, 1.2, 1.02148, 1.0119, 1.04724, 1.0127, 1.02732, 0.96225, 0.8965, 0.97783, 0.93574, 0.94818, 1.30679, 1.0675, 1.11826, 0.99821, 1.0557, 1.0326, 1.2, 1.0675, 0.96225, 1.0675, 1.0326, 0.74817, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.03754, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.87533, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.98705, 1, 1, 1, 1, 1, 1, 0.98448, 0.9973, 0.98448, 0.9973, 0.98448, 0.9973, 0.83089, 0.96777, 1, 1.20088, 0.89903, 1, 1, 0.75155, 0.94945, 0.94945, 0.94945, 0.94945, 1.12317, 1.12317, 1.12317, 0.67603, 0.67603, 1.15621, 0.73584, 1.21191, 1.22135, 1.06483, 0.94868, 0.94868, 0.95996, 1.24633, 1, 1.07497, 0.87709, 0.96927, 1.01473, 0.96927, 1, 1, 1, 0.77295, 1, 1, 1.09836, 1.09836, 1.09836, 1.01522, 0.86321, 0.94434, 0.8649, 0.94434, 0.86182, 1, 1, 1.083, 1, 0.91578, 0.86438, 1.17308, 1.18416, 1.14589, 0.69825, 0.97622, 1.96791, 1.24822, 1.24822, 1.17308, 1.24822, 1.24822, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.42603, 1, 0.99862, 0.99862, 1, 0.87025, 0.87025, 0.87025, 0.87025, 1.17984, 1.42603, 1, 1.42603, 1.42603, 0.99862, 1, 1, 1, 1, 1, 1.2886, 1.04315, 1.15296, 1.34163, 1, 1, 1, 1.10742, 1.10742, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.SegoeuiItalicFactors = SegoeuiItalicFactors;
const SegoeuiItalicMetrics = {
  lineHeight: 1.33008,
  lineGap: 0
};
exports.SegoeuiItalicMetrics = SegoeuiItalicMetrics;
const SegoeuiRegularFactors = [1.76738, 1, 1, 0.98594, 1.02285, 1.10454, 1.06234, 0.96927, 0.92037, 1.19985, 1.2046, 0.90616, 0.90616, 1.07152, 1.1714, 0.78032, 1.20088, 0.78032, 1.40246, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.96927, 0.78032, 0.78032, 1.1714, 1.1714, 1.1714, 0.80597, 0.94084, 0.96706, 0.85944, 0.85734, 0.97093, 0.75842, 0.79936, 0.88198, 0.9831, 0.95782, 0.71387, 0.86969, 0.84636, 1.07796, 1.03584, 0.96924, 0.83968, 0.96924, 0.82826, 0.79649, 0.85771, 0.95132, 0.93119, 0.98965, 0.88433, 0.8287, 0.93365, 1.08612, 1.3638, 1.08612, 1.45786, 0.74627, 0.80499, 0.91484, 1.05707, 0.92383, 1.05882, 0.9403, 1.12654, 1.05882, 1.01756, 1.09011, 1.09011, 0.99414, 1.09011, 1.034, 1.01756, 1.05356, 1.05707, 1.05882, 1.04399, 0.84863, 1.21968, 1.01756, 0.95801, 1.00068, 0.91797, 0.96777, 0.9043, 0.90351, 0.92105, 0.90351, 1.1714, 0.85337, 0.96927, 0.96927, 0.99912, 0.96927, 0.92105, 0.80597, 1.2434, 1.20808, 1.05937, 0.90957, 1.1714, 1.20808, 0.75155, 0.94261, 1.24644, 1.09971, 1.09971, 0.84751, 1, 0.85273, 0.78032, 0.61584, 1.05425, 1.17914, 0.90957, 1.08665, 1.11593, 1.14169, 0.73381, 0.96706, 0.96706, 0.96706, 0.96706, 0.96706, 0.96706, 0.86035, 0.85734, 0.75842, 0.75842, 0.75842, 0.75842, 0.95782, 0.95782, 0.95782, 0.95782, 0.97093, 1.03584, 0.96924, 0.96924, 0.96924, 0.96924, 0.96924, 1.1714, 0.96924, 0.95132, 0.95132, 0.95132, 0.95132, 0.8287, 0.83968, 0.89049, 0.91484, 0.91484, 0.91484, 0.91484, 0.91484, 0.91484, 0.93575, 0.92383, 0.9403, 0.9403, 0.9403, 0.9403, 0.8717, 0.8717, 0.8717, 0.8717, 1.00527, 1.01756, 1.05356, 1.05356, 1.05356, 1.05356, 1.05356, 1.24644, 0.95923, 1.01756, 1.01756, 1.01756, 1.01756, 0.96777, 1.05707, 0.96777, 0.96706, 0.91484, 0.96706, 0.91484, 0.96706, 0.91484, 0.85734, 0.92383, 0.85734, 0.92383, 0.85734, 0.92383, 0.85734, 0.92383, 0.97093, 1.0969, 0.97093, 1.05882, 0.75842, 0.9403, 0.75842, 0.9403, 0.75842, 0.9403, 0.75842, 0.9403, 0.75842, 0.9403, 0.88198, 1.05882, 0.88198, 1.05882, 0.88198, 1.05882, 1, 1, 0.9831, 1.01756, 0.9831, 1.01756, 0.95782, 0.8717, 0.95782, 0.8717, 0.95782, 0.8717, 0.95782, 1.09011, 0.95782, 0.8717, 0.84784, 1.11551, 0.71387, 1.09011, 1, 1, 0.99414, 0.84636, 1.09011, 1, 1, 0.84636, 1.0536, 0.84636, 0.94298, 0.84636, 1.23297, 1.03584, 1.01756, 1, 1, 1.03584, 1.01756, 1.00323, 1.03444, 1.01756, 0.96924, 1.05356, 0.96924, 1.05356, 0.96924, 1.05356, 0.93066, 0.98293, 0.82826, 1.04399, 1, 1, 0.82826, 1.04399, 0.79649, 0.84863, 0.79649, 0.84863, 0.79649, 0.84863, 0.79649, 0.84863, 1, 1, 0.85771, 1.17318, 0.85771, 1.21968, 0.95132, 1.01756, 0.95132, 1.01756, 0.95132, 1.01756, 0.95132, 1.01756, 0.95132, 1.01756, 0.95132, 1.01756, 0.98965, 1.00068, 0.8287, 0.96777, 0.8287, 0.93365, 0.9043, 0.93365, 0.9043, 0.93365, 0.9043, 1.08571, 0.96927, 0.96706, 0.91484, 0.86035, 0.93575, 0.96924, 0.95923, 1, 1, 0.85771, 1.21968, 1.11437, 1.11437, 0.93109, 0.91202, 0.60411, 0.84164, 0.55572, 1.01173, 0.97361, 0.81818, 0.81818, 0.96635, 0.78032, 0.72727, 0.92366, 0.98601, 1.03405, 0.77968, 1.09799, 1.2, 0.96706, 0.85944, 0.85638, 0.96491, 0.75842, 0.93365, 0.9831, 0.96924, 0.95782, 0.86969, 0.94152, 1.07796, 1.03584, 0.78437, 0.96924, 0.98715, 0.83968, 0.83491, 0.85771, 0.8287, 0.94492, 0.88433, 0.9287, 1.0098, 0.95782, 0.8287, 1.0625, 0.98248, 1.03424, 1.2, 1.01071, 1.0625, 0.95246, 1.03809, 1.04912, 0.98248, 1.00221, 1.03424, 1.05443, 1.2, 1.04785, 0.99609, 1.00169, 1.05176, 0.99346, 1.05356, 0.9087, 1.03004, 0.95542, 0.93117, 1.23362, 1.01071, 1.07831, 1.02512, 1.05205, 1.03502, 1.2, 1.01071, 1.05356, 1.01071, 1.03502, 0.75842, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.03719, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9403, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.04021, 1, 1, 1, 1, 1, 1, 0.98965, 1.00068, 0.98965, 1.00068, 0.98965, 1.00068, 0.8287, 0.96777, 1, 1.20088, 0.89903, 1, 1, 0.75155, 1.03077, 1.03077, 1.03077, 1.03077, 1.13196, 1.13196, 1.13196, 0.67428, 0.67428, 1.16039, 0.73291, 1.20996, 1.22135, 1.06483, 0.94868, 0.94868, 0.95996, 1.24633, 1, 1.07497, 0.87796, 0.96927, 1.01518, 0.96927, 1, 1, 1, 0.77295, 1, 1, 1.10539, 1.10539, 1.11358, 1.06967, 0.86279, 0.94434, 0.86279, 0.94434, 0.86182, 1, 1, 1.083, 1, 0.91578, 0.86507, 1.1714, 1.18416, 1.14589, 0.69825, 0.97622, 1.9697, 1.24822, 1.24822, 1.17238, 1.24822, 1.24822, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.42603, 1, 0.99862, 0.99862, 1, 0.87025, 0.87025, 0.87025, 0.87025, 1.18083, 1.42603, 1, 1.42603, 1.42603, 0.99862, 1, 1, 1, 1, 1, 1.2886, 1.04315, 1.15296, 1.34163, 1, 1, 1, 1.10938, 1.10938, 1, 1, 1, 1.05425, 1.09971, 1.09971, 1.09971, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
exports.SegoeuiRegularFactors = SegoeuiRegularFactors;
const SegoeuiRegularMetrics = {
  lineHeight: 1.33008,
  lineGap: 0
};
exports.SegoeuiRegularMetrics = SegoeuiRegularMetrics;

/***/ }),
/* 55 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PostScriptEvaluator = exports.PostScriptCompiler = exports.PDFFunctionFactory = void 0;
exports.isPDFFunction = isPDFFunction;
var _primitives = __w_pdfjs_require__(3);
var _util = __w_pdfjs_require__(2);
var _ps_parser = __w_pdfjs_require__(56);
var _base_stream = __w_pdfjs_require__(5);
var _image_utils = __w_pdfjs_require__(57);
class PDFFunctionFactory {
  constructor({
    xref,
    isEvalSupported = true
  }) {
    this.xref = xref;
    this.isEvalSupported = isEvalSupported !== false;
  }
  create(fn) {
    const cachedFunction = this.getCached(fn);
    if (cachedFunction) {
      return cachedFunction;
    }
    const parsedFunction = PDFFunction.parse({
      xref: this.xref,
      isEvalSupported: this.isEvalSupported,
      fn: fn instanceof _primitives.Ref ? this.xref.fetch(fn) : fn
    });
    this._cache(fn, parsedFunction);
    return parsedFunction;
  }
  createFromArray(fnObj) {
    const cachedFunction = this.getCached(fnObj);
    if (cachedFunction) {
      return cachedFunction;
    }
    const parsedFunction = PDFFunction.parseArray({
      xref: this.xref,
      isEvalSupported: this.isEvalSupported,
      fnObj: fnObj instanceof _primitives.Ref ? this.xref.fetch(fnObj) : fnObj
    });
    this._cache(fnObj, parsedFunction);
    return parsedFunction;
  }
  getCached(cacheKey) {
    let fnRef;
    if (cacheKey instanceof _primitives.Ref) {
      fnRef = cacheKey;
    } else if (cacheKey instanceof _primitives.Dict) {
      fnRef = cacheKey.objId;
    } else if (cacheKey instanceof _base_stream.BaseStream) {
      fnRef = cacheKey.dict && cacheKey.dict.objId;
    }
    if (fnRef) {
      const localFunction = this._localFunctionCache.getByRef(fnRef);
      if (localFunction) {
        return localFunction;
      }
    }
    return null;
  }
  _cache(cacheKey, parsedFunction) {
    if (!parsedFunction) {
      throw new Error('PDFFunctionFactory._cache - expected "parsedFunction" argument.');
    }
    let fnRef;
    if (cacheKey instanceof _primitives.Ref) {
      fnRef = cacheKey;
    } else if (cacheKey instanceof _primitives.Dict) {
      fnRef = cacheKey.objId;
    } else if (cacheKey instanceof _base_stream.BaseStream) {
      fnRef = cacheKey.dict && cacheKey.dict.objId;
    }
    if (fnRef) {
      this._localFunctionCache.set(null, fnRef, parsedFunction);
    }
  }
  get _localFunctionCache() {
    return (0, _util.shadow)(this, "_localFunctionCache", new _image_utils.LocalFunctionCache());
  }
}
exports.PDFFunctionFactory = PDFFunctionFactory;
function toNumberArray(arr) {
  if (!Array.isArray(arr)) {
    return null;
  }
  const length = arr.length;
  for (let i = 0; i < length; i++) {
    if (typeof arr[i] !== "number") {
      const result = new Array(length);
      for (let j = 0; j < length; j++) {
        result[j] = +arr[j];
      }
      return result;
    }
  }
  return arr;
}
class PDFFunction {
  static getSampleArray(size, outputSize, bps, stream) {
    let i, ii;
    let length = 1;
    for (i = 0, ii = size.length; i < ii; i++) {
      length *= size[i];
    }
    length *= outputSize;
    const array = new Array(length);
    let codeSize = 0;
    let codeBuf = 0;
    const sampleMul = 1.0 / (2.0 ** bps - 1);
    const strBytes = stream.getBytes((length * bps + 7) / 8);
    let strIdx = 0;
    for (i = 0; i < length; i++) {
      while (codeSize < bps) {
        codeBuf <<= 8;
        codeBuf |= strBytes[strIdx++];
        codeSize += 8;
      }
      codeSize -= bps;
      array[i] = (codeBuf >> codeSize) * sampleMul;
      codeBuf &= (1 << codeSize) - 1;
    }
    return array;
  }
  static parse({
    xref,
    isEvalSupported,
    fn
  }) {
    const dict = fn.dict || fn;
    const typeNum = dict.get("FunctionType");
    switch (typeNum) {
      case 0:
        return this.constructSampled({
          xref,
          isEvalSupported,
          fn,
          dict
        });
      case 1:
        break;
      case 2:
        return this.constructInterpolated({
          xref,
          isEvalSupported,
          dict
        });
      case 3:
        return this.constructStiched({
          xref,
          isEvalSupported,
          dict
        });
      case 4:
        return this.constructPostScript({
          xref,
          isEvalSupported,
          fn,
          dict
        });
    }
    throw new _util.FormatError("Unknown type of function");
  }
  static parseArray({
    xref,
    isEvalSupported,
    fnObj
  }) {
    if (!Array.isArray(fnObj)) {
      return this.parse({
        xref,
        isEvalSupported,
        fn: fnObj
      });
    }
    const fnArray = [];
    for (const fn of fnObj) {
      fnArray.push(this.parse({
        xref,
        isEvalSupported,
        fn: xref.fetchIfRef(fn)
      }));
    }
    return function (src, srcOffset, dest, destOffset) {
      for (let i = 0, ii = fnArray.length; i < ii; i++) {
        fnArray[i](src, srcOffset, dest, destOffset + i);
      }
    };
  }
  static constructSampled({
    xref,
    isEvalSupported,
    fn,
    dict
  }) {
    function toMultiArray(arr) {
      const inputLength = arr.length;
      const out = [];
      let index = 0;
      for (let i = 0; i < inputLength; i += 2) {
        out[index++] = [arr[i], arr[i + 1]];
      }
      return out;
    }
    function interpolate(x, xmin, xmax, ymin, ymax) {
      return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
    }
    let domain = toNumberArray(dict.getArray("Domain"));
    let range = toNumberArray(dict.getArray("Range"));
    if (!domain || !range) {
      throw new _util.FormatError("No domain or range");
    }
    const inputSize = domain.length / 2;
    const outputSize = range.length / 2;
    domain = toMultiArray(domain);
    range = toMultiArray(range);
    const size = toNumberArray(dict.getArray("Size"));
    const bps = dict.get("BitsPerSample");
    const order = dict.get("Order") || 1;
    if (order !== 1) {
      (0, _util.info)("No support for cubic spline interpolation: " + order);
    }
    let encode = toNumberArray(dict.getArray("Encode"));
    if (!encode) {
      encode = [];
      for (let i = 0; i < inputSize; ++i) {
        encode.push([0, size[i] - 1]);
      }
    } else {
      encode = toMultiArray(encode);
    }
    let decode = toNumberArray(dict.getArray("Decode"));
    if (!decode) {
      decode = range;
    } else {
      decode = toMultiArray(decode);
    }
    const samples = this.getSampleArray(size, outputSize, bps, fn);
    return function constructSampledFn(src, srcOffset, dest, destOffset) {
      const cubeVertices = 1 << inputSize;
      const cubeN = new Float64Array(cubeVertices);
      const cubeVertex = new Uint32Array(cubeVertices);
      let i, j;
      for (j = 0; j < cubeVertices; j++) {
        cubeN[j] = 1;
      }
      let k = outputSize,
        pos = 1;
      for (i = 0; i < inputSize; ++i) {
        const domain_2i = domain[i][0];
        const domain_2i_1 = domain[i][1];
        const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
        let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
        const size_i = size[i];
        e = Math.min(Math.max(e, 0), size_i - 1);
        const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
        const n0 = e0 + 1 - e;
        const n1 = e - e0;
        const offset0 = e0 * k;
        const offset1 = offset0 + k;
        for (j = 0; j < cubeVertices; j++) {
          if (j & pos) {
            cubeN[j] *= n1;
            cubeVertex[j] += offset1;
          } else {
            cubeN[j] *= n0;
            cubeVertex[j] += offset0;
          }
        }
        k *= size_i;
        pos <<= 1;
      }
      for (j = 0; j < outputSize; ++j) {
        let rj = 0;
        for (i = 0; i < cubeVertices; i++) {
          rj += samples[cubeVertex[i] + j] * cubeN[i];
        }
        rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
        dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
      }
    };
  }
  static constructInterpolated({
    xref,
    isEvalSupported,
    dict
  }) {
    const c0 = toNumberArray(dict.getArray("C0")) || [0];
    const c1 = toNumberArray(dict.getArray("C1")) || [1];
    const n = dict.get("N");
    const diff = [];
    for (let i = 0, ii = c0.length; i < ii; ++i) {
      diff.push(c1[i] - c0[i]);
    }
    const length = diff.length;
    return function constructInterpolatedFn(src, srcOffset, dest, destOffset) {
      const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
      for (let j = 0; j < length; ++j) {
        dest[destOffset + j] = c0[j] + x * diff[j];
      }
    };
  }
  static constructStiched({
    xref,
    isEvalSupported,
    dict
  }) {
    const domain = toNumberArray(dict.getArray("Domain"));
    if (!domain) {
      throw new _util.FormatError("No domain");
    }
    const inputSize = domain.length / 2;
    if (inputSize !== 1) {
      throw new _util.FormatError("Bad domain for stiched function");
    }
    const fns = [];
    for (const fn of dict.get("Functions")) {
      fns.push(this.parse({
        xref,
        isEvalSupported,
        fn: xref.fetchIfRef(fn)
      }));
    }
    const bounds = toNumberArray(dict.getArray("Bounds"));
    const encode = toNumberArray(dict.getArray("Encode"));
    const tmpBuf = new Float32Array(1);
    return function constructStichedFn(src, srcOffset, dest, destOffset) {
      const clip = function constructStichedFromIRClip(v, min, max) {
        if (v > max) {
          v = max;
        } else if (v < min) {
          v = min;
        }
        return v;
      };
      const v = clip(src[srcOffset], domain[0], domain[1]);
      const length = bounds.length;
      let i;
      for (i = 0; i < length; ++i) {
        if (v < bounds[i]) {
          break;
        }
      }
      let dmin = domain[0];
      if (i > 0) {
        dmin = bounds[i - 1];
      }
      let dmax = domain[1];
      if (i < bounds.length) {
        dmax = bounds[i];
      }
      const rmin = encode[2 * i];
      const rmax = encode[2 * i + 1];
      tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
      fns[i](tmpBuf, 0, dest, destOffset);
    };
  }
  static constructPostScript({
    xref,
    isEvalSupported,
    fn,
    dict
  }) {
    const domain = toNumberArray(dict.getArray("Domain"));
    const range = toNumberArray(dict.getArray("Range"));
    if (!domain) {
      throw new _util.FormatError("No domain.");
    }
    if (!range) {
      throw new _util.FormatError("No range.");
    }
    const lexer = new _ps_parser.PostScriptLexer(fn);
    const parser = new _ps_parser.PostScriptParser(lexer);
    const code = parser.parse();
    if (isEvalSupported && _util.FeatureTest.isEvalSupported) {
      const compiled = new PostScriptCompiler().compile(code, domain, range);
      if (compiled) {
        return new Function("src", "srcOffset", "dest", "destOffset", compiled);
      }
    }
    (0, _util.info)("Unable to compile PS function");
    const numOutputs = range.length >> 1;
    const numInputs = domain.length >> 1;
    const evaluator = new PostScriptEvaluator(code);
    const cache = Object.create(null);
    const MAX_CACHE_SIZE = 2048 * 4;
    let cache_available = MAX_CACHE_SIZE;
    const tmpBuf = new Float32Array(numInputs);
    return function constructPostScriptFn(src, srcOffset, dest, destOffset) {
      let i, value;
      let key = "";
      const input = tmpBuf;
      for (i = 0; i < numInputs; i++) {
        value = src[srcOffset + i];
        input[i] = value;
        key += value + "_";
      }
      const cachedValue = cache[key];
      if (cachedValue !== undefined) {
        dest.set(cachedValue, destOffset);
        return;
      }
      const output = new Float32Array(numOutputs);
      const stack = evaluator.execute(input);
      const stackIndex = stack.length - numOutputs;
      for (i = 0; i < numOutputs; i++) {
        value = stack[stackIndex + i];
        let bound = range[i * 2];
        if (value < bound) {
          value = bound;
        } else {
          bound = range[i * 2 + 1];
          if (value > bound) {
            value = bound;
          }
        }
        output[i] = value;
      }
      if (cache_available > 0) {
        cache_available--;
        cache[key] = output;
      }
      dest.set(output, destOffset);
    };
  }
}
function isPDFFunction(v) {
  let fnDict;
  if (typeof v !== "object") {
    return false;
  } else if (v instanceof _primitives.Dict) {
    fnDict = v;
  } else if (v instanceof _base_stream.BaseStream) {
    fnDict = v.dict;
  } else {
    return false;
  }
  return fnDict.has("FunctionType");
}
class PostScriptStack {
  static get MAX_STACK_SIZE() {
    return (0, _util.shadow)(this, "MAX_STACK_SIZE", 100);
  }
  constructor(initialStack) {
    this.stack = initialStack ? Array.from(initialStack) : [];
  }
  push(value) {
    if (this.stack.length >= PostScriptStack.MAX_STACK_SIZE) {
      throw new Error("PostScript function stack overflow.");
    }
    this.stack.push(value);
  }
  pop() {
    if (this.stack.length <= 0) {
      throw new Error("PostScript function stack underflow.");
    }
    return this.stack.pop();
  }
  copy(n) {
    if (this.stack.length + n >= PostScriptStack.MAX_STACK_SIZE) {
      throw new Error("PostScript function stack overflow.");
    }
    const stack = this.stack;
    for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
      stack.push(stack[i]);
    }
  }
  index(n) {
    this.push(this.stack[this.stack.length - n - 1]);
  }
  roll(n, p) {
    const stack = this.stack;
    const l = stack.length - n;
    const r = stack.length - 1;
    const c = l + (p - Math.floor(p / n) * n);
    for (let i = l, j = r; i < j; i++, j--) {
      const t = stack[i];
      stack[i] = stack[j];
      stack[j] = t;
    }
    for (let i = l, j = c - 1; i < j; i++, j--) {
      const t = stack[i];
      stack[i] = stack[j];
      stack[j] = t;
    }
    for (let i = c, j = r; i < j; i++, j--) {
      const t = stack[i];
      stack[i] = stack[j];
      stack[j] = t;
    }
  }
}
class PostScriptEvaluator {
  constructor(operators) {
    this.operators = operators;
  }
  execute(initialStack) {
    const stack = new PostScriptStack(initialStack);
    let counter = 0;
    const operators = this.operators;
    const length = operators.length;
    let operator, a, b;
    while (counter < length) {
      operator = operators[counter++];
      if (typeof operator === "number") {
        stack.push(operator);
        continue;
      }
      switch (operator) {
        case "jz":
          b = stack.pop();
          a = stack.pop();
          if (!a) {
            counter = b;
          }
          break;
        case "j":
          a = stack.pop();
          counter = a;
          break;
        case "abs":
          a = stack.pop();
          stack.push(Math.abs(a));
          break;
        case "add":
          b = stack.pop();
          a = stack.pop();
          stack.push(a + b);
          break;
        case "and":
          b = stack.pop();
          a = stack.pop();
          if (typeof a === "boolean" && typeof b === "boolean") {
            stack.push(a && b);
          } else {
            stack.push(a & b);
          }
          break;
        case "atan":
          a = stack.pop();
          stack.push(Math.atan(a));
          break;
        case "bitshift":
          b = stack.pop();
          a = stack.pop();
          if (a > 0) {
            stack.push(a << b);
          } else {
            stack.push(a >> b);
          }
          break;
        case "ceiling":
          a = stack.pop();
          stack.push(Math.ceil(a));
          break;
        case "copy":
          a = stack.pop();
          stack.copy(a);
          break;
        case "cos":
          a = stack.pop();
          stack.push(Math.cos(a));
          break;
        case "cvi":
          a = stack.pop() | 0;
          stack.push(a);
          break;
        case "cvr":
          break;
        case "div":
          b = stack.pop();
          a = stack.pop();
          stack.push(a / b);
          break;
        case "dup":
          stack.copy(1);
          break;
        case "eq":
          b = stack.pop();
          a = stack.pop();
          stack.push(a === b);
          break;
        case "exch":
          stack.roll(2, 1);
          break;
        case "exp":
          b = stack.pop();
          a = stack.pop();
          stack.push(a ** b);
          break;
        case "false":
          stack.push(false);
          break;
        case "floor":
          a = stack.pop();
          stack.push(Math.floor(a));
          break;
        case "ge":
          b = stack.pop();
          a = stack.pop();
          stack.push(a >= b);
          break;
        case "gt":
          b = stack.pop();
          a = stack.pop();
          stack.push(a > b);
          break;
        case "idiv":
          b = stack.pop();
          a = stack.pop();
          stack.push(a / b | 0);
          break;
        case "index":
          a = stack.pop();
          stack.index(a);
          break;
        case "le":
          b = stack.pop();
          a = stack.pop();
          stack.push(a <= b);
          break;
        case "ln":
          a = stack.pop();
          stack.push(Math.log(a));
          break;
        case "log":
          a = stack.pop();
          stack.push(Math.log(a) / Math.LN10);
          break;
        case "lt":
          b = stack.pop();
          a = stack.pop();
          stack.push(a < b);
          break;
        case "mod":
          b = stack.pop();
          a = stack.pop();
          stack.push(a % b);
          break;
        case "mul":
          b = stack.pop();
          a = stack.pop();
          stack.push(a * b);
          break;
        case "ne":
          b = stack.pop();
          a = stack.pop();
          stack.push(a !== b);
          break;
        case "neg":
          a = stack.pop();
          stack.push(-a);
          break;
        case "not":
          a = stack.pop();
          if (typeof a === "boolean") {
            stack.push(!a);
          } else {
            stack.push(~a);
          }
          break;
        case "or":
          b = stack.pop();
          a = stack.pop();
          if (typeof a === "boolean" && typeof b === "boolean") {
            stack.push(a || b);
          } else {
            stack.push(a | b);
          }
          break;
        case "pop":
          stack.pop();
          break;
        case "roll":
          b = stack.pop();
          a = stack.pop();
          stack.roll(a, b);
          break;
        case "round":
          a = stack.pop();
          stack.push(Math.round(a));
          break;
        case "sin":
          a = stack.pop();
          stack.push(Math.sin(a));
          break;
        case "sqrt":
          a = stack.pop();
          stack.push(Math.sqrt(a));
          break;
        case "sub":
          b = stack.pop();
          a = stack.pop();
          stack.push(a - b);
          break;
        case "true":
          stack.push(true);
          break;
        case "truncate":
          a = stack.pop();
          a = a < 0 ? Math.ceil(a) : Math.floor(a);
          stack.push(a);
          break;
        case "xor":
          b = stack.pop();
          a = stack.pop();
          if (typeof a === "boolean" && typeof b === "boolean") {
            stack.push(a !== b);
          } else {
            stack.push(a ^ b);
          }
          break;
        default:
          throw new _util.FormatError(`Unknown operator ${operator}`);
      }
    }
    return stack.stack;
  }
}
exports.PostScriptEvaluator = PostScriptEvaluator;
class AstNode {
  constructor(type) {
    this.type = type;
  }
  visit(visitor) {
    (0, _util.unreachable)("abstract method");
  }
}
class AstArgument extends AstNode {
  constructor(index, min, max) {
    super("args");
    this.index = index;
    this.min = min;
    this.max = max;
  }
  visit(visitor) {
    visitor.visitArgument(this);
  }
}
class AstLiteral extends AstNode {
  constructor(number) {
    super("literal");
    this.number = number;
    this.min = number;
    this.max = number;
  }
  visit(visitor) {
    visitor.visitLiteral(this);
  }
}
class AstBinaryOperation extends AstNode {
  constructor(op, arg1, arg2, min, max) {
    super("binary");
    this.op = op;
    this.arg1 = arg1;
    this.arg2 = arg2;
    this.min = min;
    this.max = max;
  }
  visit(visitor) {
    visitor.visitBinaryOperation(this);
  }
}
class AstMin extends AstNode {
  constructor(arg, max) {
    super("max");
    this.arg = arg;
    this.min = arg.min;
    this.max = max;
  }
  visit(visitor) {
    visitor.visitMin(this);
  }
}
class AstVariable extends AstNode {
  constructor(index, min, max) {
    super("var");
    this.index = index;
    this.min = min;
    this.max = max;
  }
  visit(visitor) {
    visitor.visitVariable(this);
  }
}
class AstVariableDefinition extends AstNode {
  constructor(variable, arg) {
    super("definition");
    this.variable = variable;
    this.arg = arg;
  }
  visit(visitor) {
    visitor.visitVariableDefinition(this);
  }
}
class ExpressionBuilderVisitor {
  constructor() {
    this.parts = [];
  }
  visitArgument(arg) {
    this.parts.push("Math.max(", arg.min, ", Math.min(", arg.max, ", src[srcOffset + ", arg.index, "]))");
  }
  visitVariable(variable) {
    this.parts.push("v", variable.index);
  }
  visitLiteral(literal) {
    this.parts.push(literal.number);
  }
  visitBinaryOperation(operation) {
    this.parts.push("(");
    operation.arg1.visit(this);
    this.parts.push(" ", operation.op, " ");
    operation.arg2.visit(this);
    this.parts.push(")");
  }
  visitVariableDefinition(definition) {
    this.parts.push("var ");
    definition.variable.visit(this);
    this.parts.push(" = ");
    definition.arg.visit(this);
    this.parts.push(";");
  }
  visitMin(max) {
    this.parts.push("Math.min(");
    max.arg.visit(this);
    this.parts.push(", ", max.max, ")");
  }
  toString() {
    return this.parts.join("");
  }
}
function buildAddOperation(num1, num2) {
  if (num2.type === "literal" && num2.number === 0) {
    return num1;
  }
  if (num1.type === "literal" && num1.number === 0) {
    return num2;
  }
  if (num2.type === "literal" && num1.type === "literal") {
    return new AstLiteral(num1.number + num2.number);
  }
  return new AstBinaryOperation("+", num1, num2, num1.min + num2.min, num1.max + num2.max);
}
function buildMulOperation(num1, num2) {
  if (num2.type === "literal") {
    if (num2.number === 0) {
      return new AstLiteral(0);
    } else if (num2.number === 1) {
      return num1;
    } else if (num1.type === "literal") {
      return new AstLiteral(num1.number * num2.number);
    }
  }
  if (num1.type === "literal") {
    if (num1.number === 0) {
      return new AstLiteral(0);
    } else if (num1.number === 1) {
      return num2;
    }
  }
  const min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  const max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  return new AstBinaryOperation("*", num1, num2, min, max);
}
function buildSubOperation(num1, num2) {
  if (num2.type === "literal") {
    if (num2.number === 0) {
      return num1;
    } else if (num1.type === "literal") {
      return new AstLiteral(num1.number - num2.number);
    }
  }
  if (num2.type === "binary" && num2.op === "-" && num1.type === "literal" && num1.number === 1 && num2.arg1.type === "literal" && num2.arg1.number === 1) {
    return num2.arg2;
  }
  return new AstBinaryOperation("-", num1, num2, num1.min - num2.max, num1.max - num2.min);
}
function buildMinOperation(num1, max) {
  if (num1.min >= max) {
    return new AstLiteral(max);
  } else if (num1.max <= max) {
    return num1;
  }
  return new AstMin(num1, max);
}
class PostScriptCompiler {
  compile(code, domain, range) {
    const stack = [];
    const instructions = [];
    const inputSize = domain.length >> 1,
      outputSize = range.length >> 1;
    let lastRegister = 0;
    let n, j;
    let num1, num2, ast1, ast2, tmpVar, item;
    for (let i = 0; i < inputSize; i++) {
      stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
    }
    for (let i = 0, ii = code.length; i < ii; i++) {
      item = code[i];
      if (typeof item === "number") {
        stack.push(new AstLiteral(item));
        continue;
      }
      switch (item) {
        case "add":
          if (stack.length < 2) {
            return null;
          }
          num2 = stack.pop();
          num1 = stack.pop();
          stack.push(buildAddOperation(num1, num2));
          break;
        case "cvr":
          if (stack.length < 1) {
            return null;
          }
          break;
        case "mul":
          if (stack.length < 2) {
            return null;
          }
          num2 = stack.pop();
          num1 = stack.pop();
          stack.push(buildMulOperation(num1, num2));
          break;
        case "sub":
          if (stack.length < 2) {
            return null;
          }
          num2 = stack.pop();
          num1 = stack.pop();
          stack.push(buildSubOperation(num1, num2));
          break;
        case "exch":
          if (stack.length < 2) {
            return null;
          }
          ast1 = stack.pop();
          ast2 = stack.pop();
          stack.push(ast1, ast2);
          break;
        case "pop":
          if (stack.length < 1) {
            return null;
          }
          stack.pop();
          break;
        case "index":
          if (stack.length < 1) {
            return null;
          }
          num1 = stack.pop();
          if (num1.type !== "literal") {
            return null;
          }
          n = num1.number;
          if (n < 0 || !Number.isInteger(n) || stack.length < n) {
            return null;
          }
          ast1 = stack[stack.length - n - 1];
          if (ast1.type === "literal" || ast1.type === "var") {
            stack.push(ast1);
            break;
          }
          tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
          stack[stack.length - n - 1] = tmpVar;
          stack.push(tmpVar);
          instructions.push(new AstVariableDefinition(tmpVar, ast1));
          break;
        case "dup":
          if (stack.length < 1) {
            return null;
          }
          if (typeof code[i + 1] === "number" && code[i + 2] === "gt" && code[i + 3] === i + 7 && code[i + 4] === "jz" && code[i + 5] === "pop" && code[i + 6] === code[i + 1]) {
            num1 = stack.pop();
            stack.push(buildMinOperation(num1, code[i + 1]));
            i += 6;
            break;
          }
          ast1 = stack.at(-1);
          if (ast1.type === "literal" || ast1.type === "var") {
            stack.push(ast1);
            break;
          }
          tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
          stack[stack.length - 1] = tmpVar;
          stack.push(tmpVar);
          instructions.push(new AstVariableDefinition(tmpVar, ast1));
          break;
        case "roll":
          if (stack.length < 2) {
            return null;
          }
          num2 = stack.pop();
          num1 = stack.pop();
          if (num2.type !== "literal" || num1.type !== "literal") {
            return null;
          }
          j = num2.number;
          n = num1.number;
          if (n <= 0 || !Number.isInteger(n) || !Number.isInteger(j) || stack.length < n) {
            return null;
          }
          j = (j % n + n) % n;
          if (j === 0) {
            break;
          }
          stack.push(...stack.splice(stack.length - n, n - j));
          break;
        default:
          return null;
      }
    }
    if (stack.length !== outputSize) {
      return null;
    }
    const result = [];
    for (const instruction of instructions) {
      const statementBuilder = new ExpressionBuilderVisitor();
      instruction.visit(statementBuilder);
      result.push(statementBuilder.toString());
    }
    for (let i = 0, ii = stack.length; i < ii; i++) {
      const expr = stack[i],
        statementBuilder = new ExpressionBuilderVisitor();
      expr.visit(statementBuilder);
      const min = range[i * 2],
        max = range[i * 2 + 1];
      const out = [statementBuilder.toString()];
      if (min > expr.min) {
        out.unshift("Math.max(", min, ", ");
        out.push(")");
      }
      if (max < expr.max) {
        out.unshift("Math.min(", max, ", ");
        out.push(")");
      }
      out.unshift("dest[destOffset + ", i, "] = ");
      out.push(";");
      result.push(out.join(""));
    }
    return result.join("\n");
  }
}
exports.PostScriptCompiler = PostScriptCompiler;

/***/ }),
/* 56 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PostScriptParser = exports.PostScriptLexer = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _core_utils = __w_pdfjs_require__(4);
class PostScriptParser {
  constructor(lexer) {
    this.lexer = lexer;
    this.operators = [];
    this.token = null;
    this.prev = null;
  }
  nextToken() {
    this.prev = this.token;
    this.token = this.lexer.getToken();
  }
  accept(type) {
    if (this.token.type === type) {
      this.nextToken();
      return true;
    }
    return false;
  }
  expect(type) {
    if (this.accept(type)) {
      return true;
    }
    throw new _util.FormatError(`Unexpected symbol: found ${this.token.type} expected ${type}.`);
  }
  parse() {
    this.nextToken();
    this.expect(PostScriptTokenTypes.LBRACE);
    this.parseBlock();
    this.expect(PostScriptTokenTypes.RBRACE);
    return this.operators;
  }
  parseBlock() {
    while (true) {
      if (this.accept(PostScriptTokenTypes.NUMBER)) {
        this.operators.push(this.prev.value);
      } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {
        this.operators.push(this.prev.value);
      } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
        this.parseCondition();
      } else {
        return;
      }
    }
  }
  parseCondition() {
    const conditionLocation = this.operators.length;
    this.operators.push(null, null);
    this.parseBlock();
    this.expect(PostScriptTokenTypes.RBRACE);
    if (this.accept(PostScriptTokenTypes.IF)) {
      this.operators[conditionLocation] = this.operators.length;
      this.operators[conditionLocation + 1] = "jz";
    } else if (this.accept(PostScriptTokenTypes.LBRACE)) {
      const jumpLocation = this.operators.length;
      this.operators.push(null, null);
      const endOfTrue = this.operators.length;
      this.parseBlock();
      this.expect(PostScriptTokenTypes.RBRACE);
      this.expect(PostScriptTokenTypes.IFELSE);
      this.operators[jumpLocation] = this.operators.length;
      this.operators[jumpLocation + 1] = "j";
      this.operators[conditionLocation] = endOfTrue;
      this.operators[conditionLocation + 1] = "jz";
    } else {
      throw new _util.FormatError("PS Function: error parsing conditional.");
    }
  }
}
exports.PostScriptParser = PostScriptParser;
const PostScriptTokenTypes = {
  LBRACE: 0,
  RBRACE: 1,
  NUMBER: 2,
  OPERATOR: 3,
  IF: 4,
  IFELSE: 5
};
class PostScriptToken {
  static get opCache() {
    return (0, _util.shadow)(this, "opCache", Object.create(null));
  }
  constructor(type, value) {
    this.type = type;
    this.value = value;
  }
  static getOperator(op) {
    const opValue = PostScriptToken.opCache[op];
    if (opValue) {
      return opValue;
    }
    return PostScriptToken.opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);
  }
  static get LBRACE() {
    return (0, _util.shadow)(this, "LBRACE", new PostScriptToken(PostScriptTokenTypes.LBRACE, "{"));
  }
  static get RBRACE() {
    return (0, _util.shadow)(this, "RBRACE", new PostScriptToken(PostScriptTokenTypes.RBRACE, "}"));
  }
  static get IF() {
    return (0, _util.shadow)(this, "IF", new PostScriptToken(PostScriptTokenTypes.IF, "IF"));
  }
  static get IFELSE() {
    return (0, _util.shadow)(this, "IFELSE", new PostScriptToken(PostScriptTokenTypes.IFELSE, "IFELSE"));
  }
}
class PostScriptLexer {
  constructor(stream) {
    this.stream = stream;
    this.nextChar();
    this.strBuf = [];
  }
  nextChar() {
    return this.currentChar = this.stream.getByte();
  }
  getToken() {
    let comment = false;
    let ch = this.currentChar;
    while (true) {
      if (ch < 0) {
        return _primitives.EOF;
      }
      if (comment) {
        if (ch === 0x0a || ch === 0x0d) {
          comment = false;
        }
      } else if (ch === 0x25) {
        comment = true;
      } else if (!(0, _core_utils.isWhiteSpace)(ch)) {
        break;
      }
      ch = this.nextChar();
    }
    switch (ch | 0) {
      case 0x30:
      case 0x31:
      case 0x32:
      case 0x33:
      case 0x34:
      case 0x35:
      case 0x36:
      case 0x37:
      case 0x38:
      case 0x39:
      case 0x2b:
      case 0x2d:
      case 0x2e:
        return new PostScriptToken(PostScriptTokenTypes.NUMBER, this.getNumber());
      case 0x7b:
        this.nextChar();
        return PostScriptToken.LBRACE;
      case 0x7d:
        this.nextChar();
        return PostScriptToken.RBRACE;
    }
    const strBuf = this.strBuf;
    strBuf.length = 0;
    strBuf[0] = String.fromCharCode(ch);
    while ((ch = this.nextChar()) >= 0 && (ch >= 0x41 && ch <= 0x5a || ch >= 0x61 && ch <= 0x7a)) {
      strBuf.push(String.fromCharCode(ch));
    }
    const str = strBuf.join("");
    switch (str.toLowerCase()) {
      case "if":
        return PostScriptToken.IF;
      case "ifelse":
        return PostScriptToken.IFELSE;
      default:
        return PostScriptToken.getOperator(str);
    }
  }
  getNumber() {
    let ch = this.currentChar;
    const strBuf = this.strBuf;
    strBuf.length = 0;
    strBuf[0] = String.fromCharCode(ch);
    while ((ch = this.nextChar()) >= 0) {
      if (ch >= 0x30 && ch <= 0x39 || ch === 0x2d || ch === 0x2e) {
        strBuf.push(String.fromCharCode(ch));
      } else {
        break;
      }
    }
    const value = parseFloat(strBuf.join(""));
    if (isNaN(value)) {
      throw new _util.FormatError(`Invalid floating point number: ${value}`);
    }
    return value;
  }
}
exports.PostScriptLexer = PostScriptLexer;

/***/ }),
/* 57 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.LocalTilingPatternCache = exports.LocalImageCache = exports.LocalGStateCache = exports.LocalFunctionCache = exports.LocalColorSpaceCache = exports.GlobalImageCache = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
class BaseLocalCache {
  constructor(options) {
    if (this.constructor === BaseLocalCache) {
      (0, _util.unreachable)("Cannot initialize BaseLocalCache.");
    }
    this._onlyRefs = (options && options.onlyRefs) === true;
    if (!this._onlyRefs) {
      this._nameRefMap = new Map();
      this._imageMap = new Map();
    }
    this._imageCache = new _primitives.RefSetCache();
  }
  getByName(name) {
    if (this._onlyRefs) {
      (0, _util.unreachable)("Should not call `getByName` method.");
    }
    const ref = this._nameRefMap.get(name);
    if (ref) {
      return this.getByRef(ref);
    }
    return this._imageMap.get(name) || null;
  }
  getByRef(ref) {
    return this._imageCache.get(ref) || null;
  }
  set(name, ref, data) {
    (0, _util.unreachable)("Abstract method `set` called.");
  }
}
class LocalImageCache extends BaseLocalCache {
  set(name, ref = null, data) {
    if (typeof name !== "string") {
      throw new Error('LocalImageCache.set - expected "name" argument.');
    }
    if (ref) {
      if (this._imageCache.has(ref)) {
        return;
      }
      this._nameRefMap.set(name, ref);
      this._imageCache.put(ref, data);
      return;
    }
    if (this._imageMap.has(name)) {
      return;
    }
    this._imageMap.set(name, data);
  }
}
exports.LocalImageCache = LocalImageCache;
class LocalColorSpaceCache extends BaseLocalCache {
  set(name = null, ref = null, data) {
    if (typeof name !== "string" && !ref) {
      throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');
    }
    if (ref) {
      if (this._imageCache.has(ref)) {
        return;
      }
      if (name !== null) {
        this._nameRefMap.set(name, ref);
      }
      this._imageCache.put(ref, data);
      return;
    }
    if (this._imageMap.has(name)) {
      return;
    }
    this._imageMap.set(name, data);
  }
}
exports.LocalColorSpaceCache = LocalColorSpaceCache;
class LocalFunctionCache extends BaseLocalCache {
  constructor(options) {
    super({
      onlyRefs: true
    });
  }
  set(name = null, ref, data) {
    if (!ref) {
      throw new Error('LocalFunctionCache.set - expected "ref" argument.');
    }
    if (this._imageCache.has(ref)) {
      return;
    }
    this._imageCache.put(ref, data);
  }
}
exports.LocalFunctionCache = LocalFunctionCache;
class LocalGStateCache extends BaseLocalCache {
  set(name, ref = null, data) {
    if (typeof name !== "string") {
      throw new Error('LocalGStateCache.set - expected "name" argument.');
    }
    if (ref) {
      if (this._imageCache.has(ref)) {
        return;
      }
      this._nameRefMap.set(name, ref);
      this._imageCache.put(ref, data);
      return;
    }
    if (this._imageMap.has(name)) {
      return;
    }
    this._imageMap.set(name, data);
  }
}
exports.LocalGStateCache = LocalGStateCache;
class LocalTilingPatternCache extends BaseLocalCache {
  constructor(options) {
    super({
      onlyRefs: true
    });
  }
  set(name = null, ref, data) {
    if (!ref) {
      throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');
    }
    if (this._imageCache.has(ref)) {
      return;
    }
    this._imageCache.put(ref, data);
  }
}
exports.LocalTilingPatternCache = LocalTilingPatternCache;
class GlobalImageCache {
  static get NUM_PAGES_THRESHOLD() {
    return (0, _util.shadow)(this, "NUM_PAGES_THRESHOLD", 2);
  }
  static get MIN_IMAGES_TO_CACHE() {
    return (0, _util.shadow)(this, "MIN_IMAGES_TO_CACHE", 10);
  }
  static get MAX_BYTE_SIZE() {
    return (0, _util.shadow)(this, "MAX_BYTE_SIZE", 40e6);
  }
  constructor() {
    this._refCache = new _primitives.RefSetCache();
    this._imageCache = new _primitives.RefSetCache();
  }
  get _byteSize() {
    let byteSize = 0;
    for (const imageData of this._imageCache) {
      byteSize += imageData.byteSize;
    }
    return byteSize;
  }
  get _cacheLimitReached() {
    if (this._imageCache.size < GlobalImageCache.MIN_IMAGES_TO_CACHE) {
      return false;
    }
    if (this._byteSize < GlobalImageCache.MAX_BYTE_SIZE) {
      return false;
    }
    return true;
  }
  shouldCache(ref, pageIndex) {
    const pageIndexSet = this._refCache.get(ref);
    const numPages = pageIndexSet ? pageIndexSet.size + (pageIndexSet.has(pageIndex) ? 0 : 1) : 1;
    if (numPages < GlobalImageCache.NUM_PAGES_THRESHOLD) {
      return false;
    }
    if (!this._imageCache.has(ref) && this._cacheLimitReached) {
      return false;
    }
    return true;
  }
  addPageIndex(ref, pageIndex) {
    let pageIndexSet = this._refCache.get(ref);
    if (!pageIndexSet) {
      pageIndexSet = new Set();
      this._refCache.put(ref, pageIndexSet);
    }
    pageIndexSet.add(pageIndex);
  }
  addByteSize(ref, byteSize) {
    const imageData = this._imageCache.get(ref);
    if (!imageData) {
      return;
    }
    if (imageData.byteSize) {
      return;
    }
    imageData.byteSize = byteSize;
  }
  getData(ref, pageIndex) {
    const pageIndexSet = this._refCache.get(ref);
    if (!pageIndexSet) {
      return null;
    }
    if (pageIndexSet.size < GlobalImageCache.NUM_PAGES_THRESHOLD) {
      return null;
    }
    const imageData = this._imageCache.get(ref);
    if (!imageData) {
      return null;
    }
    pageIndexSet.add(pageIndex);
    return imageData;
  }
  setData(ref, data) {
    if (!this._refCache.has(ref)) {
      throw new Error('GlobalImageCache.setData - expected "addPageIndex" to have been called.');
    }
    if (this._imageCache.has(ref)) {
      return;
    }
    if (this._cacheLimitReached) {
      (0, _util.warn)("GlobalImageCache.setData - cache limit reached.");
      return;
    }
    this._imageCache.put(ref, data);
  }
  clear(onlyData = false) {
    if (!onlyData) {
      this._refCache.clear();
    }
    this._imageCache.clear();
  }
}
exports.GlobalImageCache = GlobalImageCache;

/***/ }),
/* 58 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.bidi = bidi;
var _util = __w_pdfjs_require__(2);
const baseTypes = ["BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "S", "B", "S", "WS", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "B", "B", "B", "S", "WS", "ON", "ON", "ET", "ET", "ET", "ON", "ON", "ON", "ON", "ON", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "ON", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "ON", "ON", "ON", "BN", "BN", "BN", "BN", "BN", "BN", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "CS", "ON", "ET", "ET", "ET", "ET", "ON", "ON", "ON", "ON", "L", "ON", "ON", "BN", "ON", "ON", "ET", "ET", "EN", "EN", "ON", "L", "ON", "ON", "ON", "EN", "L", "ON", "ON", "ON", "ON", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "ON", "L", "L", "L", "L", "L", "L", "L", "L"];
const arabicTypes = ["AN", "AN", "AN", "AN", "AN", "AN", "ON", "ON", "AL", "ET", "ET", "AL", "CS", "AL", "ON", "ON", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "ET", "AN", "AN", "AL", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "ON", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "NSM", "NSM", "ON", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "AL", "AL", "AL", "AL", "AL", "AL"];
function isOdd(i) {
  return (i & 1) !== 0;
}
function isEven(i) {
  return (i & 1) === 0;
}
function findUnequal(arr, start, value) {
  let j, jj;
  for (j = start, jj = arr.length; j < jj; ++j) {
    if (arr[j] !== value) {
      return j;
    }
  }
  return j;
}
function setValues(arr, start, end, value) {
  for (let j = start; j < end; ++j) {
    arr[j] = value;
  }
}
function reverseValues(arr, start, end) {
  for (let i = start, j = end - 1; i < j; ++i, --j) {
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
}
function createBidiText(str, isLTR, vertical = false) {
  let dir = "ltr";
  if (vertical) {
    dir = "ttb";
  } else if (!isLTR) {
    dir = "rtl";
  }
  return {
    str,
    dir
  };
}
const chars = [];
const types = [];
function bidi(str, startLevel = -1, vertical = false) {
  let isLTR = true;
  const strLength = str.length;
  if (strLength === 0 || vertical) {
    return createBidiText(str, isLTR, vertical);
  }
  chars.length = strLength;
  types.length = strLength;
  let numBidi = 0;
  let i, ii;
  for (i = 0; i < strLength; ++i) {
    chars[i] = str.charAt(i);
    const charCode = str.charCodeAt(i);
    let charType = "L";
    if (charCode <= 0x00ff) {
      charType = baseTypes[charCode];
    } else if (0x0590 <= charCode && charCode <= 0x05f4) {
      charType = "R";
    } else if (0x0600 <= charCode && charCode <= 0x06ff) {
      charType = arabicTypes[charCode & 0xff];
      if (!charType) {
        (0, _util.warn)("Bidi: invalid Unicode character " + charCode.toString(16));
      }
    } else if (0x0700 <= charCode && charCode <= 0x08ac) {
      charType = "AL";
    }
    if (charType === "R" || charType === "AL" || charType === "AN") {
      numBidi++;
    }
    types[i] = charType;
  }
  if (numBidi === 0) {
    isLTR = true;
    return createBidiText(str, isLTR);
  }
  if (startLevel === -1) {
    if (numBidi / strLength < 0.3 && strLength > 4) {
      isLTR = true;
      startLevel = 0;
    } else {
      isLTR = false;
      startLevel = 1;
    }
  }
  const levels = [];
  for (i = 0; i < strLength; ++i) {
    levels[i] = startLevel;
  }
  const e = isOdd(startLevel) ? "R" : "L";
  const sor = e;
  const eor = sor;
  let lastType = sor;
  for (i = 0; i < strLength; ++i) {
    if (types[i] === "NSM") {
      types[i] = lastType;
    } else {
      lastType = types[i];
    }
  }
  lastType = sor;
  let t;
  for (i = 0; i < strLength; ++i) {
    t = types[i];
    if (t === "EN") {
      types[i] = lastType === "AL" ? "AN" : "EN";
    } else if (t === "R" || t === "L" || t === "AL") {
      lastType = t;
    }
  }
  for (i = 0; i < strLength; ++i) {
    t = types[i];
    if (t === "AL") {
      types[i] = "R";
    }
  }
  for (i = 1; i < strLength - 1; ++i) {
    if (types[i] === "ES" && types[i - 1] === "EN" && types[i + 1] === "EN") {
      types[i] = "EN";
    }
    if (types[i] === "CS" && (types[i - 1] === "EN" || types[i - 1] === "AN") && types[i + 1] === types[i - 1]) {
      types[i] = types[i - 1];
    }
  }
  for (i = 0; i < strLength; ++i) {
    if (types[i] === "EN") {
      for (let j = i - 1; j >= 0; --j) {
        if (types[j] !== "ET") {
          break;
        }
        types[j] = "EN";
      }
      for (let j = i + 1; j < strLength; ++j) {
        if (types[j] !== "ET") {
          break;
        }
        types[j] = "EN";
      }
    }
  }
  for (i = 0; i < strLength; ++i) {
    t = types[i];
    if (t === "WS" || t === "ES" || t === "ET" || t === "CS") {
      types[i] = "ON";
    }
  }
  lastType = sor;
  for (i = 0; i < strLength; ++i) {
    t = types[i];
    if (t === "EN") {
      types[i] = lastType === "L" ? "L" : "EN";
    } else if (t === "R" || t === "L") {
      lastType = t;
    }
  }
  for (i = 0; i < strLength; ++i) {
    if (types[i] === "ON") {
      const end = findUnequal(types, i + 1, "ON");
      let before = sor;
      if (i > 0) {
        before = types[i - 1];
      }
      let after = eor;
      if (end + 1 < strLength) {
        after = types[end + 1];
      }
      if (before !== "L") {
        before = "R";
      }
      if (after !== "L") {
        after = "R";
      }
      if (before === after) {
        setValues(types, i, end, before);
      }
      i = end - 1;
    }
  }
  for (i = 0; i < strLength; ++i) {
    if (types[i] === "ON") {
      types[i] = e;
    }
  }
  for (i = 0; i < strLength; ++i) {
    t = types[i];
    if (isEven(levels[i])) {
      if (t === "R") {
        levels[i] += 1;
      } else if (t === "AN" || t === "EN") {
        levels[i] += 2;
      }
    } else {
      if (t === "L" || t === "AN" || t === "EN") {
        levels[i] += 1;
      }
    }
  }
  let highestLevel = -1;
  let lowestOddLevel = 99;
  let level;
  for (i = 0, ii = levels.length; i < ii; ++i) {
    level = levels[i];
    if (highestLevel < level) {
      highestLevel = level;
    }
    if (lowestOddLevel > level && isOdd(level)) {
      lowestOddLevel = level;
    }
  }
  for (level = highestLevel; level >= lowestOddLevel; --level) {
    let start = -1;
    for (i = 0, ii = levels.length; i < ii; ++i) {
      if (levels[i] < level) {
        if (start >= 0) {
          reverseValues(chars, start, i);
          start = -1;
        }
      } else if (start < 0) {
        start = i;
      }
    }
    if (start >= 0) {
      reverseValues(chars, start, levels.length);
    }
  }
  for (i = 0, ii = chars.length; i < ii; ++i) {
    const ch = chars[i];
    if (ch === "<" || ch === ">") {
      chars[i] = "";
    }
  }
  return createBidiText(chars.join(""), isLTR);
}

/***/ }),
/* 59 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MurmurHash3_64 = void 0;
var _util = __w_pdfjs_require__(2);
const SEED = 0xc3d2e1f0;
const MASK_HIGH = 0xffff0000;
const MASK_LOW = 0xffff;
class MurmurHash3_64 {
  constructor(seed) {
    this.h1 = seed ? seed & 0xffffffff : SEED;
    this.h2 = seed ? seed & 0xffffffff : SEED;
  }
  update(input) {
    let data, length;
    if (typeof input === "string") {
      data = new Uint8Array(input.length * 2);
      length = 0;
      for (let i = 0, ii = input.length; i < ii; i++) {
        const code = input.charCodeAt(i);
        if (code <= 0xff) {
          data[length++] = code;
        } else {
          data[length++] = code >>> 8;
          data[length++] = code & 0xff;
        }
      }
    } else if ((0, _util.isArrayBuffer)(input)) {
      data = input.slice();
      length = data.byteLength;
    } else {
      throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
    }
    const blockCounts = length >> 2;
    const tailLength = length - blockCounts * 4;
    const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
    let k1 = 0,
      k2 = 0;
    let h1 = this.h1,
      h2 = this.h2;
    const C1 = 0xcc9e2d51,
      C2 = 0x1b873593;
    const C1_LOW = C1 & MASK_LOW,
      C2_LOW = C2 & MASK_LOW;
    for (let i = 0; i < blockCounts; i++) {
      if (i & 1) {
        k1 = dataUint32[i];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        h1 ^= k1;
        h1 = h1 << 13 | h1 >>> 19;
        h1 = h1 * 5 + 0xe6546b64;
      } else {
        k2 = dataUint32[i];
        k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
        k2 = k2 << 15 | k2 >>> 17;
        k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
        h2 ^= k2;
        h2 = h2 << 13 | h2 >>> 19;
        h2 = h2 * 5 + 0xe6546b64;
      }
    }
    k1 = 0;
    switch (tailLength) {
      case 3:
        k1 ^= data[blockCounts * 4 + 2] << 16;
      case 2:
        k1 ^= data[blockCounts * 4 + 1] << 8;
      case 1:
        k1 ^= data[blockCounts * 4];
        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
        if (blockCounts & 1) {
          h1 ^= k1;
        } else {
          h2 ^= k1;
        }
    }
    this.h1 = h1;
    this.h2 = h2;
  }
  hexdigest() {
    let h1 = this.h1,
      h2 = this.h2;
    h1 ^= h2 >>> 1;
    h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
    h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
    h1 ^= h2 >>> 1;
    h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
    h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
    h1 ^= h2 >>> 1;
    return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
  }
}
exports.MurmurHash3_64 = MurmurHash3_64;

/***/ }),
/* 60 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.OperatorList = void 0;
var _util = __w_pdfjs_require__(2);
function addState(parentState, pattern, checkFn, iterateFn, processFn) {
  let state = parentState;
  for (let i = 0, ii = pattern.length - 1; i < ii; i++) {
    const item = pattern[i];
    state = state[item] || (state[item] = []);
  }
  state[pattern.at(-1)] = {
    checkFn,
    iterateFn,
    processFn
  };
}
const InitialState = [];
addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInlineImageXObject, _util.OPS.restore], null, function iterateInlineImageGroup(context, i) {
  const fnArray = context.fnArray;
  const iFirstSave = context.iCurr - 3;
  const pos = (i - iFirstSave) % 4;
  switch (pos) {
    case 0:
      return fnArray[i] === _util.OPS.save;
    case 1:
      return fnArray[i] === _util.OPS.transform;
    case 2:
      return fnArray[i] === _util.OPS.paintInlineImageXObject;
    case 3:
      return fnArray[i] === _util.OPS.restore;
  }
  throw new Error(`iterateInlineImageGroup - invalid pos: ${pos}`);
}, function foundInlineImageGroup(context, i) {
  const MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  const MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  const MAX_WIDTH = 1000;
  const IMAGE_PADDING = 1;
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const curr = context.iCurr;
  const iFirstSave = curr - 3;
  const iFirstTransform = curr - 2;
  const iFirstPIIXO = curr - 1;
  const count = Math.min(Math.floor((i - iFirstSave) / 4), MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
    return i - (i - iFirstSave) % 4;
  }
  let maxX = 0;
  const map = [];
  let maxLineHeight = 0;
  let currentX = IMAGE_PADDING,
    currentY = IMAGE_PADDING;
  for (let q = 0; q < count; q++) {
    const transform = argsArray[iFirstTransform + (q << 2)];
    const img = argsArray[iFirstPIIXO + (q << 2)][0];
    if (currentX + img.width > MAX_WIDTH) {
      maxX = Math.max(maxX, currentX);
      currentY += maxLineHeight + 2 * IMAGE_PADDING;
      currentX = 0;
      maxLineHeight = 0;
    }
    map.push({
      transform,
      x: currentX,
      y: currentY,
      w: img.width,
      h: img.height
    });
    currentX += img.width + 2 * IMAGE_PADDING;
    maxLineHeight = Math.max(maxLineHeight, img.height);
  }
  const imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  const imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  const imgData = new Uint8Array(imgWidth * imgHeight * 4);
  const imgRowSize = imgWidth << 2;
  for (let q = 0; q < count; q++) {
    const data = argsArray[iFirstPIIXO + (q << 2)][0].data;
    const rowSize = map[q].w << 2;
    let dataOffset = 0;
    let offset = map[q].x + map[q].y * imgWidth << 2;
    imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
    for (let k = 0, kk = map[q].h; k < kk; k++) {
      imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
      dataOffset += rowSize;
      offset += imgRowSize;
    }
    imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
    while (offset >= 0) {
      data[offset - 4] = data[offset];
      data[offset - 3] = data[offset + 1];
      data[offset - 2] = data[offset + 2];
      data[offset - 1] = data[offset + 3];
      data[offset + rowSize] = data[offset + rowSize - 4];
      data[offset + rowSize + 1] = data[offset + rowSize - 3];
      data[offset + rowSize + 2] = data[offset + rowSize - 2];
      data[offset + rowSize + 3] = data[offset + rowSize - 1];
      offset -= imgRowSize;
    }
  }
  fnArray.splice(iFirstSave, count * 4, _util.OPS.paintInlineImageXObjectGroup);
  argsArray.splice(iFirstSave, count * 4, [{
    width: imgWidth,
    height: imgHeight,
    kind: _util.ImageKind.RGBA_32BPP,
    data: imgData
  }, map]);
  return iFirstSave + 1;
});
addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageMaskXObject, _util.OPS.restore], null, function iterateImageMaskGroup(context, i) {
  const fnArray = context.fnArray;
  const iFirstSave = context.iCurr - 3;
  const pos = (i - iFirstSave) % 4;
  switch (pos) {
    case 0:
      return fnArray[i] === _util.OPS.save;
    case 1:
      return fnArray[i] === _util.OPS.transform;
    case 2:
      return fnArray[i] === _util.OPS.paintImageMaskXObject;
    case 3:
      return fnArray[i] === _util.OPS.restore;
  }
  throw new Error(`iterateImageMaskGroup - invalid pos: ${pos}`);
}, function foundImageMaskGroup(context, i) {
  const MIN_IMAGES_IN_MASKS_BLOCK = 10;
  const MAX_IMAGES_IN_MASKS_BLOCK = 100;
  const MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const curr = context.iCurr;
  const iFirstSave = curr - 3;
  const iFirstTransform = curr - 2;
  const iFirstPIMXO = curr - 1;
  let count = Math.floor((i - iFirstSave) / 4);
  if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
    return i - (i - iFirstSave) % 4;
  }
  let isSameImage = false;
  let iTransform, transformArgs;
  const firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  const firstTransformArg0 = argsArray[iFirstTransform][0],
    firstTransformArg1 = argsArray[iFirstTransform][1],
    firstTransformArg2 = argsArray[iFirstTransform][2],
    firstTransformArg3 = argsArray[iFirstTransform][3];
  if (firstTransformArg1 === firstTransformArg2) {
    isSameImage = true;
    iTransform = iFirstTransform + 4;
    let iPIMXO = iFirstPIMXO + 4;
    for (let q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
      transformArgs = argsArray[iTransform];
      if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== firstTransformArg1 || transformArgs[2] !== firstTransformArg2 || transformArgs[3] !== firstTransformArg3) {
        if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
          isSameImage = false;
        } else {
          count = q;
        }
        break;
      }
    }
  }
  if (isSameImage) {
    count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
    const positions = new Float32Array(count * 2);
    iTransform = iFirstTransform;
    for (let q = 0; q < count; q++, iTransform += 4) {
      transformArgs = argsArray[iTransform];
      positions[q << 1] = transformArgs[4];
      positions[(q << 1) + 1] = transformArgs[5];
    }
    fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectRepeat);
    argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg1, firstTransformArg2, firstTransformArg3, positions]);
  } else {
    count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
    const images = [];
    for (let q = 0; q < count; q++) {
      transformArgs = argsArray[iFirstTransform + (q << 2)];
      const maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
      images.push({
        data: maskParams.data,
        width: maskParams.width,
        height: maskParams.height,
        interpolate: maskParams.interpolate,
        count: maskParams.count,
        transform: transformArgs
      });
    }
    fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectGroup);
    argsArray.splice(iFirstSave, count * 4, [images]);
  }
  return iFirstSave + 1;
});
addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageXObject, _util.OPS.restore], function (context) {
  const argsArray = context.argsArray;
  const iFirstTransform = context.iCurr - 2;
  return argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0;
}, function iterateImageGroup(context, i) {
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const iFirstSave = context.iCurr - 3;
  const pos = (i - iFirstSave) % 4;
  switch (pos) {
    case 0:
      return fnArray[i] === _util.OPS.save;
    case 1:
      if (fnArray[i] !== _util.OPS.transform) {
        return false;
      }
      const iFirstTransform = context.iCurr - 2;
      const firstTransformArg0 = argsArray[iFirstTransform][0];
      const firstTransformArg3 = argsArray[iFirstTransform][3];
      if (argsArray[i][0] !== firstTransformArg0 || argsArray[i][1] !== 0 || argsArray[i][2] !== 0 || argsArray[i][3] !== firstTransformArg3) {
        return false;
      }
      return true;
    case 2:
      if (fnArray[i] !== _util.OPS.paintImageXObject) {
        return false;
      }
      const iFirstPIXO = context.iCurr - 1;
      const firstPIXOArg0 = argsArray[iFirstPIXO][0];
      if (argsArray[i][0] !== firstPIXOArg0) {
        return false;
      }
      return true;
    case 3:
      return fnArray[i] === _util.OPS.restore;
  }
  throw new Error(`iterateImageGroup - invalid pos: ${pos}`);
}, function (context, i) {
  const MIN_IMAGES_IN_BLOCK = 3;
  const MAX_IMAGES_IN_BLOCK = 1000;
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const curr = context.iCurr;
  const iFirstSave = curr - 3;
  const iFirstTransform = curr - 2;
  const iFirstPIXO = curr - 1;
  const firstPIXOArg0 = argsArray[iFirstPIXO][0];
  const firstTransformArg0 = argsArray[iFirstTransform][0];
  const firstTransformArg3 = argsArray[iFirstTransform][3];
  const count = Math.min(Math.floor((i - iFirstSave) / 4), MAX_IMAGES_IN_BLOCK);
  if (count < MIN_IMAGES_IN_BLOCK) {
    return i - (i - iFirstSave) % 4;
  }
  const positions = new Float32Array(count * 2);
  let iTransform = iFirstTransform;
  for (let q = 0; q < count; q++, iTransform += 4) {
    const transformArgs = argsArray[iTransform];
    positions[q << 1] = transformArgs[4];
    positions[(q << 1) + 1] = transformArgs[5];
  }
  const args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3, positions];
  fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageXObjectRepeat);
  argsArray.splice(iFirstSave, count * 4, args);
  return iFirstSave + 1;
});
addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], null, function iterateShowTextGroup(context, i) {
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const iFirstSave = context.iCurr - 4;
  const pos = (i - iFirstSave) % 5;
  switch (pos) {
    case 0:
      return fnArray[i] === _util.OPS.beginText;
    case 1:
      return fnArray[i] === _util.OPS.setFont;
    case 2:
      return fnArray[i] === _util.OPS.setTextMatrix;
    case 3:
      if (fnArray[i] !== _util.OPS.showText) {
        return false;
      }
      const iFirstSetFont = context.iCurr - 3;
      const firstSetFontArg0 = argsArray[iFirstSetFont][0];
      const firstSetFontArg1 = argsArray[iFirstSetFont][1];
      if (argsArray[i][0] !== firstSetFontArg0 || argsArray[i][1] !== firstSetFontArg1) {
        return false;
      }
      return true;
    case 4:
      return fnArray[i] === _util.OPS.endText;
  }
  throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`);
}, function (context, i) {
  const MIN_CHARS_IN_BLOCK = 3;
  const MAX_CHARS_IN_BLOCK = 1000;
  const fnArray = context.fnArray,
    argsArray = context.argsArray;
  const curr = context.iCurr;
  const iFirstBeginText = curr - 4;
  const iFirstSetFont = curr - 3;
  const iFirstSetTextMatrix = curr - 2;
  const iFirstShowText = curr - 1;
  const iFirstEndText = curr;
  const firstSetFontArg0 = argsArray[iFirstSetFont][0];
  const firstSetFontArg1 = argsArray[iFirstSetFont][1];
  let count = Math.min(Math.floor((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
  if (count < MIN_CHARS_IN_BLOCK) {
    return i - (i - iFirstBeginText) % 5;
  }
  let iFirst = iFirstBeginText;
  if (iFirstBeginText >= 4 && fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] && fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] && fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] && fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] && argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 && argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
    count++;
    iFirst -= 5;
  }
  let iEndText = iFirst + 4;
  for (let q = 1; q < count; q++) {
    fnArray.splice(iEndText, 3);
    argsArray.splice(iEndText, 3);
    iEndText += 2;
  }
  return iEndText + 1;
});
class NullOptimizer {
  constructor(queue) {
    this.queue = queue;
  }
  _optimize() {}
  push(fn, args) {
    this.queue.fnArray.push(fn);
    this.queue.argsArray.push(args);
    this._optimize();
  }
  flush() {}
  reset() {}
}
class QueueOptimizer extends NullOptimizer {
  constructor(queue) {
    super(queue);
    this.state = null;
    this.context = {
      iCurr: 0,
      fnArray: queue.fnArray,
      argsArray: queue.argsArray
    };
    this.match = null;
    this.lastProcessed = 0;
  }
  _optimize() {
    const fnArray = this.queue.fnArray;
    let i = this.lastProcessed,
      ii = fnArray.length;
    let state = this.state;
    let match = this.match;
    if (!state && !match && i + 1 === ii && !InitialState[fnArray[i]]) {
      this.lastProcessed = ii;
      return;
    }
    const context = this.context;
    while (i < ii) {
      if (match) {
        const iterate = (0, match.iterateFn)(context, i);
        if (iterate) {
          i++;
          continue;
        }
        i = (0, match.processFn)(context, i + 1);
        ii = fnArray.length;
        match = null;
        state = null;
        if (i >= ii) {
          break;
        }
      }
      state = (state || InitialState)[fnArray[i]];
      if (!state || Array.isArray(state)) {
        i++;
        continue;
      }
      context.iCurr = i;
      i++;
      if (state.checkFn && !(0, state.checkFn)(context)) {
        state = null;
        continue;
      }
      match = state;
      state = null;
    }
    this.state = state;
    this.match = match;
    this.lastProcessed = i;
  }
  flush() {
    while (this.match) {
      const length = this.queue.fnArray.length;
      this.lastProcessed = (0, this.match.processFn)(this.context, length);
      this.match = null;
      this.state = null;
      this._optimize();
    }
  }
  reset() {
    this.state = null;
    this.match = null;
    this.lastProcessed = 0;
  }
}
class OperatorList {
  static get CHUNK_SIZE() {
    return (0, _util.shadow)(this, "CHUNK_SIZE", 1000);
  }
  static get CHUNK_SIZE_ABOUT() {
    return (0, _util.shadow)(this, "CHUNK_SIZE_ABOUT", this.CHUNK_SIZE - 5);
  }
  constructor(intent = 0, streamSink) {
    this._streamSink = streamSink;
    this.fnArray = [];
    this.argsArray = [];
    if (streamSink && !(intent & _util.RenderingIntentFlag.OPLIST)) {
      this.optimizer = new QueueOptimizer(this);
    } else {
      this.optimizer = new NullOptimizer(this);
    }
    this.dependencies = new Set();
    this._totalLength = 0;
    this.weight = 0;
    this._resolved = streamSink ? null : Promise.resolve();
  }
  get length() {
    return this.argsArray.length;
  }
  get ready() {
    return this._resolved || this._streamSink.ready;
  }
  get totalLength() {
    return this._totalLength + this.length;
  }
  addOp(fn, args) {
    this.optimizer.push(fn, args);
    this.weight++;
    if (this._streamSink) {
      if (this.weight >= OperatorList.CHUNK_SIZE) {
        this.flush();
      } else if (this.weight >= OperatorList.CHUNK_SIZE_ABOUT && (fn === _util.OPS.restore || fn === _util.OPS.endText)) {
        this.flush();
      }
    }
  }
  addImageOps(fn, args, optionalContent) {
    if (optionalContent !== undefined) {
      this.addOp(_util.OPS.beginMarkedContentProps, ["OC", optionalContent]);
    }
    this.addOp(fn, args);
    if (optionalContent !== undefined) {
      this.addOp(_util.OPS.endMarkedContent, []);
    }
  }
  addDependency(dependency) {
    if (this.dependencies.has(dependency)) {
      return;
    }
    this.dependencies.add(dependency);
    this.addOp(_util.OPS.dependency, [dependency]);
  }
  addDependencies(dependencies) {
    for (const dependency of dependencies) {
      this.addDependency(dependency);
    }
  }
  addOpList(opList) {
    if (!(opList instanceof OperatorList)) {
      (0, _util.warn)('addOpList - ignoring invalid "opList" parameter.');
      return;
    }
    for (const dependency of opList.dependencies) {
      this.dependencies.add(dependency);
    }
    for (let i = 0, ii = opList.length; i < ii; i++) {
      this.addOp(opList.fnArray[i], opList.argsArray[i]);
    }
  }
  getIR() {
    return {
      fnArray: this.fnArray,
      argsArray: this.argsArray,
      length: this.length
    };
  }
  get _transfers() {
    const transfers = [];
    const {
      fnArray,
      argsArray,
      length
    } = this;
    for (let i = 0; i < length; i++) {
      switch (fnArray[i]) {
        case _util.OPS.paintInlineImageXObject:
        case _util.OPS.paintInlineImageXObjectGroup:
        case _util.OPS.paintImageMaskXObject:
          const arg = argsArray[i][0];
          if (!arg.cached && arg.data && arg.data.buffer instanceof ArrayBuffer) {
            transfers.push(arg.data.buffer);
          }
          break;
      }
    }
    return transfers;
  }
  flush(lastChunk = false, separateAnnots = null) {
    this.optimizer.flush();
    const length = this.length;
    this._totalLength += length;
    this._streamSink.enqueue({
      fnArray: this.fnArray,
      argsArray: this.argsArray,
      lastChunk,
      separateAnnots,
      length
    }, 1, this._transfers);
    this.dependencies.clear();
    this.fnArray.length = 0;
    this.argsArray.length = 0;
    this.weight = 0;
    this.optimizer.reset();
  }
}
exports.OperatorList = OperatorList;

/***/ }),
/* 61 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFImage = void 0;
var _util = __w_pdfjs_require__(2);
var _image_utils = __w_pdfjs_require__(62);
var _base_stream = __w_pdfjs_require__(5);
var _colorspace = __w_pdfjs_require__(12);
var _decode_stream = __w_pdfjs_require__(17);
var _jpeg_stream = __w_pdfjs_require__(25);
var _jpx = __w_pdfjs_require__(28);
var _primitives = __w_pdfjs_require__(3);
function decodeAndClamp(value, addend, coefficient, max) {
  value = addend + value * coefficient;
  if (value < 0) {
    value = 0;
  } else if (value > max) {
    value = max;
  }
  return value;
}
function resizeImageMask(src, bpc, w1, h1, w2, h2) {
  const length = w2 * h2;
  let dest;
  if (bpc <= 8) {
    dest = new Uint8Array(length);
  } else if (bpc <= 16) {
    dest = new Uint16Array(length);
  } else {
    dest = new Uint32Array(length);
  }
  const xRatio = w1 / w2;
  const yRatio = h1 / h2;
  let i,
    j,
    py,
    newIndex = 0,
    oldIndex;
  const xScaled = new Uint16Array(w2);
  const w1Scanline = w1;
  for (i = 0; i < w2; i++) {
    xScaled[i] = Math.floor(i * xRatio);
  }
  for (i = 0; i < h2; i++) {
    py = Math.floor(i * yRatio) * w1Scanline;
    for (j = 0; j < w2; j++) {
      oldIndex = py + xScaled[j];
      dest[newIndex++] = src[oldIndex];
    }
  }
  return dest;
}
class PDFImage {
  constructor({
    xref,
    res,
    image,
    isInline = false,
    smask = null,
    mask = null,
    isMask = false,
    pdfFunctionFactory,
    localColorSpaceCache
  }) {
    this.image = image;
    const dict = image.dict;
    const filter = dict.get("F", "Filter");
    let filterName;
    if (filter instanceof _primitives.Name) {
      filterName = filter.name;
    } else if (Array.isArray(filter)) {
      const filterZero = xref.fetchIfRef(filter[0]);
      if (filterZero instanceof _primitives.Name) {
        filterName = filterZero.name;
      }
    }
    switch (filterName) {
      case "JPXDecode":
        const jpxImage = new _jpx.JpxImage();
        jpxImage.parseImageProperties(image.stream);
        image.stream.reset();
        image.width = jpxImage.width;
        image.height = jpxImage.height;
        image.bitsPerComponent = jpxImage.bitsPerComponent;
        image.numComps = jpxImage.componentsCount;
        break;
      case "JBIG2Decode":
        image.bitsPerComponent = 1;
        image.numComps = 1;
        break;
    }
    let width = dict.get("W", "Width");
    let height = dict.get("H", "Height");
    if (Number.isInteger(image.width) && image.width > 0 && Number.isInteger(image.height) && image.height > 0 && (image.width !== width || image.height !== height)) {
      (0, _util.warn)("PDFImage - using the Width/Height of the image data, " + "rather than the image dictionary.");
      width = image.width;
      height = image.height;
    }
    if (width < 1 || height < 1) {
      throw new _util.FormatError(`Invalid image width: ${width} or height: ${height}`);
    }
    this.width = width;
    this.height = height;
    this.interpolate = dict.get("I", "Interpolate");
    this.imageMask = dict.get("IM", "ImageMask") || false;
    this.matte = dict.get("Matte") || false;
    let bitsPerComponent = image.bitsPerComponent;
    if (!bitsPerComponent) {
      bitsPerComponent = dict.get("BPC", "BitsPerComponent");
      if (!bitsPerComponent) {
        if (this.imageMask) {
          bitsPerComponent = 1;
        } else {
          throw new _util.FormatError(`Bits per component missing in image: ${this.imageMask}`);
        }
      }
    }
    this.bpc = bitsPerComponent;
    if (!this.imageMask) {
      let colorSpace = dict.getRaw("CS") || dict.getRaw("ColorSpace");
      if (!colorSpace) {
        (0, _util.info)("JPX images (which do not require color spaces)");
        switch (image.numComps) {
          case 1:
            colorSpace = _primitives.Name.get("DeviceGray");
            break;
          case 3:
            colorSpace = _primitives.Name.get("DeviceRGB");
            break;
          case 4:
            colorSpace = _primitives.Name.get("DeviceCMYK");
            break;
          default:
            throw new Error(`JPX images with ${image.numComps} color components not supported.`);
        }
      }
      this.colorSpace = _colorspace.ColorSpace.parse({
        cs: colorSpace,
        xref,
        resources: isInline ? res : null,
        pdfFunctionFactory,
        localColorSpaceCache
      });
      this.numComps = this.colorSpace.numComps;
    }
    this.decode = dict.getArray("D", "Decode");
    this.needsDecode = false;
    if (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode, bitsPerComponent) || isMask && !_colorspace.ColorSpace.isDefaultDecode(this.decode, 1))) {
      this.needsDecode = true;
      const max = (1 << bitsPerComponent) - 1;
      this.decodeCoefficients = [];
      this.decodeAddends = [];
      const isIndexed = this.colorSpace && this.colorSpace.name === "Indexed";
      for (let i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
        const dmin = this.decode[i];
        const dmax = this.decode[i + 1];
        this.decodeCoefficients[j] = isIndexed ? (dmax - dmin) / max : dmax - dmin;
        this.decodeAddends[j] = isIndexed ? dmin : max * dmin;
      }
    }
    if (smask) {
      this.smask = new PDFImage({
        xref,
        res,
        image: smask,
        isInline,
        pdfFunctionFactory,
        localColorSpaceCache
      });
    } else if (mask) {
      if (mask instanceof _base_stream.BaseStream) {
        const maskDict = mask.dict,
          imageMask = maskDict.get("IM", "ImageMask");
        if (!imageMask) {
          (0, _util.warn)("Ignoring /Mask in image without /ImageMask.");
        } else {
          this.mask = new PDFImage({
            xref,
            res,
            image: mask,
            isInline,
            isMask: true,
            pdfFunctionFactory,
            localColorSpaceCache
          });
        }
      } else {
        this.mask = mask;
      }
    }
  }
  static async buildImage({
    xref,
    res,
    image,
    isInline = false,
    pdfFunctionFactory,
    localColorSpaceCache
  }) {
    const imageData = image;
    let smaskData = null;
    let maskData = null;
    const smask = image.dict.get("SMask");
    const mask = image.dict.get("Mask");
    if (smask) {
      if (smask instanceof _base_stream.BaseStream) {
        smaskData = smask;
      } else {
        (0, _util.warn)("Unsupported /SMask format.");
      }
    } else if (mask) {
      if (mask instanceof _base_stream.BaseStream || Array.isArray(mask)) {
        maskData = mask;
      } else {
        (0, _util.warn)("Unsupported /Mask format.");
      }
    }
    return new PDFImage({
      xref,
      res,
      image: imageData,
      isInline,
      smask: smaskData,
      mask: maskData,
      pdfFunctionFactory,
      localColorSpaceCache
    });
  }
  static createRawMask({
    imgArray,
    width,
    height,
    imageIsFromDecodeStream,
    inverseDecode,
    interpolate
  }) {
    const computedLength = (width + 7 >> 3) * height;
    const actualLength = imgArray.byteLength;
    const haveFullData = computedLength === actualLength;
    let data, i;
    if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
      data = imgArray;
    } else if (!inverseDecode) {
      data = new Uint8Array(imgArray);
    } else {
      data = new Uint8Array(computedLength);
      data.set(imgArray);
      data.fill(0xff, actualLength);
    }
    if (inverseDecode) {
      for (i = 0; i < actualLength; i++) {
        data[i] ^= 0xff;
      }
    }
    return {
      data,
      width,
      height,
      interpolate
    };
  }
  static createMask({
    imgArray,
    width,
    height,
    imageIsFromDecodeStream,
    inverseDecode,
    interpolate,
    isOffscreenCanvasSupported = true
  }) {
    const isSingleOpaquePixel = width === 1 && height === 1 && inverseDecode === (imgArray.length === 0 || !!(imgArray[0] & 128));
    if (isSingleOpaquePixel) {
      return {
        isSingleOpaquePixel
      };
    }
    if (isOffscreenCanvasSupported && _util.FeatureTest.isOffscreenCanvasSupported) {
      const canvas = new OffscreenCanvas(width, height);
      const ctx = canvas.getContext("2d");
      const imgData = ctx.createImageData(width, height);
      (0, _image_utils.applyMaskImageData)({
        src: imgArray,
        dest: imgData.data,
        width,
        height,
        inverseDecode
      });
      ctx.putImageData(imgData, 0, 0);
      const bitmap = canvas.transferToImageBitmap();
      return {
        data: null,
        width,
        height,
        interpolate,
        bitmap
      };
    }
    return this.createRawMask({
      imgArray,
      width,
      height,
      inverseDecode,
      imageIsFromDecodeStream,
      interpolate
    });
  }
  get drawWidth() {
    return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
  }
  get drawHeight() {
    return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
  }
  decodeBuffer(buffer) {
    const bpc = this.bpc;
    const numComps = this.numComps;
    const decodeAddends = this.decodeAddends;
    const decodeCoefficients = this.decodeCoefficients;
    const max = (1 << bpc) - 1;
    let i, ii;
    if (bpc === 1) {
      for (i = 0, ii = buffer.length; i < ii; i++) {
        buffer[i] = +!buffer[i];
      }
      return;
    }
    let index = 0;
    for (i = 0, ii = this.width * this.height; i < ii; i++) {
      for (let j = 0; j < numComps; j++) {
        buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
        index++;
      }
    }
  }
  getComponents(buffer) {
    const bpc = this.bpc;
    if (bpc === 8) {
      return buffer;
    }
    const width = this.width;
    const height = this.height;
    const numComps = this.numComps;
    const length = width * height * numComps;
    let bufferPos = 0;
    let output;
    if (bpc <= 8) {
      output = new Uint8Array(length);
    } else if (bpc <= 16) {
      output = new Uint16Array(length);
    } else {
      output = new Uint32Array(length);
    }
    const rowComps = width * numComps;
    const max = (1 << bpc) - 1;
    let i = 0,
      ii,
      buf;
    if (bpc === 1) {
      let mask, loop1End, loop2End;
      for (let j = 0; j < height; j++) {
        loop1End = i + (rowComps & ~7);
        loop2End = i + rowComps;
        while (i < loop1End) {
          buf = buffer[bufferPos++];
          output[i] = buf >> 7 & 1;
          output[i + 1] = buf >> 6 & 1;
          output[i + 2] = buf >> 5 & 1;
          output[i + 3] = buf >> 4 & 1;
          output[i + 4] = buf >> 3 & 1;
          output[i + 5] = buf >> 2 & 1;
          output[i + 6] = buf >> 1 & 1;
          output[i + 7] = buf & 1;
          i += 8;
        }
        if (i < loop2End) {
          buf = buffer[bufferPos++];
          mask = 128;
          while (i < loop2End) {
            output[i++] = +!!(buf & mask);
            mask >>= 1;
          }
        }
      }
    } else {
      let bits = 0;
      buf = 0;
      for (i = 0, ii = length; i < ii; ++i) {
        if (i % rowComps === 0) {
          buf = 0;
          bits = 0;
        }
        while (bits < bpc) {
          buf = buf << 8 | buffer[bufferPos++];
          bits += 8;
        }
        const remainingBits = bits - bpc;
        let value = buf >> remainingBits;
        if (value < 0) {
          value = 0;
        } else if (value > max) {
          value = max;
        }
        output[i] = value;
        buf &= (1 << remainingBits) - 1;
        bits = remainingBits;
      }
    }
    return output;
  }
  fillOpacity(rgbaBuf, width, height, actualHeight, image) {
    const smask = this.smask;
    const mask = this.mask;
    let alphaBuf, sw, sh, i, ii, j;
    if (smask) {
      sw = smask.width;
      sh = smask.height;
      alphaBuf = new Uint8ClampedArray(sw * sh);
      smask.fillGrayBuffer(alphaBuf);
      if (sw !== width || sh !== height) {
        alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
      }
    } else if (mask) {
      if (mask instanceof PDFImage) {
        sw = mask.width;
        sh = mask.height;
        alphaBuf = new Uint8ClampedArray(sw * sh);
        mask.numComps = 1;
        mask.fillGrayBuffer(alphaBuf);
        for (i = 0, ii = sw * sh; i < ii; ++i) {
          alphaBuf[i] = 255 - alphaBuf[i];
        }
        if (sw !== width || sh !== height) {
          alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
        }
      } else if (Array.isArray(mask)) {
        alphaBuf = new Uint8ClampedArray(width * height);
        const numComps = this.numComps;
        for (i = 0, ii = width * height; i < ii; ++i) {
          let opacity = 0;
          const imageOffset = i * numComps;
          for (j = 0; j < numComps; ++j) {
            const color = image[imageOffset + j];
            const maskOffset = j * 2;
            if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
              opacity = 255;
              break;
            }
          }
          alphaBuf[i] = opacity;
        }
      } else {
        throw new _util.FormatError("Unknown mask format.");
      }
    }
    if (alphaBuf) {
      for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
        rgbaBuf[j] = alphaBuf[i];
      }
    } else {
      for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
        rgbaBuf[j] = 255;
      }
    }
  }
  undoPreblend(buffer, width, height) {
    const matte = this.smask && this.smask.matte;
    if (!matte) {
      return;
    }
    const matteRgb = this.colorSpace.getRgb(matte, 0);
    const matteR = matteRgb[0];
    const matteG = matteRgb[1];
    const matteB = matteRgb[2];
    const length = width * height * 4;
    for (let i = 0; i < length; i += 4) {
      const alpha = buffer[i + 3];
      if (alpha === 0) {
        buffer[i] = 255;
        buffer[i + 1] = 255;
        buffer[i + 2] = 255;
        continue;
      }
      const k = 255 / alpha;
      buffer[i] = (buffer[i] - matteR) * k + matteR;
      buffer[i + 1] = (buffer[i + 1] - matteG) * k + matteG;
      buffer[i + 2] = (buffer[i + 2] - matteB) * k + matteB;
    }
  }
  createImageData(forceRGBA = false) {
    const drawWidth = this.drawWidth;
    const drawHeight = this.drawHeight;
    const imgData = {
      width: drawWidth,
      height: drawHeight,
      interpolate: this.interpolate,
      kind: 0,
      data: null
    };
    const numComps = this.numComps;
    const originalWidth = this.width;
    const originalHeight = this.height;
    const bpc = this.bpc;
    const rowBytes = originalWidth * numComps * bpc + 7 >> 3;
    if (!forceRGBA) {
      let kind;
      if (this.colorSpace.name === "DeviceGray" && bpc === 1) {
        kind = _util.ImageKind.GRAYSCALE_1BPP;
      } else if (this.colorSpace.name === "DeviceRGB" && bpc === 8 && !this.needsDecode) {
        kind = _util.ImageKind.RGB_24BPP;
      }
      if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
        imgData.kind = kind;
        imgData.data = this.getImageBytes(originalHeight * rowBytes, {});
        if (this.needsDecode) {
          (0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP, "PDFImage.createImageData: The image must be grayscale.");
          const buffer = imgData.data;
          for (let i = 0, ii = buffer.length; i < ii; i++) {
            buffer[i] ^= 0xff;
          }
        }
        return imgData;
      }
      if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask) {
        let imageLength = originalHeight * rowBytes;
        switch (this.colorSpace.name) {
          case "DeviceGray":
            imageLength *= 3;
          case "DeviceRGB":
          case "DeviceCMYK":
            imgData.kind = _util.ImageKind.RGB_24BPP;
            imgData.data = this.getImageBytes(imageLength, {
              drawWidth,
              drawHeight,
              forceRGB: true
            });
            return imgData;
        }
      }
    }
    const imgArray = this.getImageBytes(originalHeight * rowBytes, {
      internal: true
    });
    const actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
    const comps = this.getComponents(imgArray);
    let alpha01, maybeUndoPreblend;
    if (!forceRGBA && !this.smask && !this.mask) {
      imgData.kind = _util.ImageKind.RGB_24BPP;
      imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 3);
      alpha01 = 0;
      maybeUndoPreblend = false;
    } else {
      imgData.kind = _util.ImageKind.RGBA_32BPP;
      imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 4);
      alpha01 = 1;
      maybeUndoPreblend = true;
      this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
    }
    if (this.needsDecode) {
      this.decodeBuffer(comps);
    }
    this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
    if (maybeUndoPreblend) {
      this.undoPreblend(imgData.data, drawWidth, actualHeight);
    }
    return imgData;
  }
  fillGrayBuffer(buffer) {
    const numComps = this.numComps;
    if (numComps !== 1) {
      throw new _util.FormatError(`Reading gray scale from a color image: ${numComps}`);
    }
    const width = this.width;
    const height = this.height;
    const bpc = this.bpc;
    const rowBytes = width * numComps * bpc + 7 >> 3;
    const imgArray = this.getImageBytes(height * rowBytes, {
      internal: true
    });
    const comps = this.getComponents(imgArray);
    let i, length;
    if (bpc === 1) {
      length = width * height;
      if (this.needsDecode) {
        for (i = 0; i < length; ++i) {
          buffer[i] = comps[i] - 1 & 255;
        }
      } else {
        for (i = 0; i < length; ++i) {
          buffer[i] = -comps[i] & 255;
        }
      }
      return;
    }
    if (this.needsDecode) {
      this.decodeBuffer(comps);
    }
    length = width * height;
    const scale = 255 / ((1 << bpc) - 1);
    for (i = 0; i < length; ++i) {
      buffer[i] = scale * comps[i];
    }
  }
  getImageBytes(length, {
    drawWidth,
    drawHeight,
    forceRGB = false,
    internal = false
  }) {
    this.image.reset();
    this.image.drawWidth = drawWidth || this.width;
    this.image.drawHeight = drawHeight || this.height;
    this.image.forceRGB = !!forceRGB;
    const imageBytes = this.image.getBytes(length);
    if (internal || this.image instanceof _decode_stream.DecodeStream) {
      return imageBytes;
    }
    (0, _util.assert)(imageBytes instanceof Uint8Array, 'PDFImage.getImageBytes: Unsupported "imageBytes" type.');
    return new Uint8Array(imageBytes);
  }
}
exports.PDFImage = PDFImage;

/***/ }),
/* 62 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.applyMaskImageData = applyMaskImageData;
var _util = __w_pdfjs_require__(2);
function applyMaskImageData({
  src,
  srcPos = 0,
  dest,
  destPos = 0,
  width,
  height,
  inverseDecode = false
}) {
  const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
  const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
  const widthInSource = width >> 3;
  const widthRemainder = width & 7;
  const srcLength = src.length;
  dest = new Uint32Array(dest.buffer);
  for (let i = 0; i < height; i++) {
    for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
      const elem = srcPos < srcLength ? src[srcPos] : 255;
      dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
      dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
    }
    if (widthRemainder === 0) {
      continue;
    }
    const elem = srcPos < srcLength ? src[srcPos++] : 255;
    for (let j = 0; j < widthRemainder; j++) {
      dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
    }
  }
  return {
    srcPos,
    destPos
  };
}

/***/ }),
/* 63 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.incrementalUpdate = incrementalUpdate;
exports.writeDict = writeDict;
exports.writeObject = writeObject;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _core_utils = __w_pdfjs_require__(4);
var _xml_parser = __w_pdfjs_require__(64);
var _base_stream = __w_pdfjs_require__(5);
var _crypto = __w_pdfjs_require__(65);
function writeObject(ref, obj, buffer, transform) {
  buffer.push(`${ref.num} ${ref.gen} obj\n`);
  if (obj instanceof _primitives.Dict) {
    writeDict(obj, buffer, transform);
  } else if (obj instanceof _base_stream.BaseStream) {
    writeStream(obj, buffer, transform);
  }
  buffer.push("\nendobj\n");
}
function writeDict(dict, buffer, transform) {
  buffer.push("<<");
  for (const key of dict.getKeys()) {
    buffer.push(` /${(0, _core_utils.escapePDFName)(key)} `);
    writeValue(dict.getRaw(key), buffer, transform);
  }
  buffer.push(">>");
}
function writeStream(stream, buffer, transform) {
  writeDict(stream.dict, buffer, transform);
  buffer.push(" stream\n");
  let string = stream.getString();
  if (transform !== null) {
    string = transform.encryptString(string);
  }
  buffer.push(string, "\nendstream");
}
function writeArray(array, buffer, transform) {
  buffer.push("[");
  let first = true;
  for (const val of array) {
    if (!first) {
      buffer.push(" ");
    } else {
      first = false;
    }
    writeValue(val, buffer, transform);
  }
  buffer.push("]");
}
function writeValue(value, buffer, transform) {
  if (value instanceof _primitives.Name) {
    buffer.push(`/${(0, _core_utils.escapePDFName)(value.name)}`);
  } else if (value instanceof _primitives.Ref) {
    buffer.push(`${value.num} ${value.gen} R`);
  } else if (Array.isArray(value)) {
    writeArray(value, buffer, transform);
  } else if (typeof value === "string") {
    if (transform !== null) {
      value = transform.encryptString(value);
    }
    buffer.push(`(${(0, _core_utils.escapeString)(value)})`);
  } else if (typeof value === "number") {
    buffer.push((0, _core_utils.numberToString)(value));
  } else if (typeof value === "boolean") {
    buffer.push(value.toString());
  } else if (value instanceof _primitives.Dict) {
    writeDict(value, buffer, transform);
  } else if (value instanceof _base_stream.BaseStream) {
    writeStream(value, buffer, transform);
  } else if (value === null) {
    buffer.push("null");
  } else {
    (0, _util.warn)(`Unhandled value in writer: ${typeof value}, please file a bug.`);
  }
}
function writeInt(number, size, offset, buffer) {
  for (let i = size + offset - 1; i > offset - 1; i--) {
    buffer[i] = number & 0xff;
    number >>= 8;
  }
  return offset + size;
}
function writeString(string, offset, buffer) {
  for (let i = 0, len = string.length; i < len; i++) {
    buffer[offset + i] = string.charCodeAt(i) & 0xff;
  }
}
function computeMD5(filesize, xrefInfo) {
  const time = Math.floor(Date.now() / 1000);
  const filename = xrefInfo.filename || "";
  const md5Buffer = [time.toString(), filename, filesize.toString()];
  let md5BufferLen = md5Buffer.reduce((a, str) => a + str.length, 0);
  for (const value of Object.values(xrefInfo.info)) {
    md5Buffer.push(value);
    md5BufferLen += value.length;
  }
  const array = new Uint8Array(md5BufferLen);
  let offset = 0;
  for (const str of md5Buffer) {
    writeString(str, offset, array);
    offset += str.length;
  }
  return (0, _util.bytesToString)((0, _crypto.calculateMD5)(array));
}
function writeXFADataForAcroform(str, newRefs) {
  const xml = new _xml_parser.SimpleXMLParser({
    hasAttributes: true
  }).parseFromString(str);
  for (const {
    xfa
  } of newRefs) {
    if (!xfa) {
      continue;
    }
    const {
      path,
      value
    } = xfa;
    if (!path) {
      continue;
    }
    const node = xml.documentElement.searchNode((0, _core_utils.parseXFAPath)(path), 0);
    if (node) {
      if (Array.isArray(value)) {
        node.childNodes = value.map(val => new _xml_parser.SimpleDOMNode("value", val));
      } else {
        node.childNodes = [new _xml_parser.SimpleDOMNode("#text", value)];
      }
    } else {
      (0, _util.warn)(`Node not found for path: ${path}`);
    }
  }
  const buffer = [];
  xml.documentElement.dump(buffer);
  return buffer.join("");
}
function updateAcroform({
  xref,
  acroForm,
  acroFormRef,
  hasXfa,
  hasXfaDatasetsEntry,
  xfaDatasetsRef,
  needAppearances,
  newRefs
}) {
  if (hasXfa && !hasXfaDatasetsEntry && !xfaDatasetsRef) {
    (0, _util.warn)("XFA - Cannot save it");
  }
  if (!needAppearances && (!hasXfa || !xfaDatasetsRef)) {
    return;
  }
  const dict = new _primitives.Dict(xref);
  for (const key of acroForm.getKeys()) {
    dict.set(key, acroForm.getRaw(key));
  }
  if (hasXfa && !hasXfaDatasetsEntry) {
    const newXfa = acroForm.get("XFA").slice();
    newXfa.splice(2, 0, "datasets");
    newXfa.splice(3, 0, xfaDatasetsRef);
    dict.set("XFA", newXfa);
  }
  if (needAppearances) {
    dict.set("NeedAppearances", true);
  }
  const encrypt = xref.encrypt;
  let transform = null;
  if (encrypt) {
    transform = encrypt.createCipherTransform(acroFormRef.num, acroFormRef.gen);
  }
  const buffer = [];
  writeObject(acroFormRef, dict, buffer, transform);
  newRefs.push({
    ref: acroFormRef,
    data: buffer.join("")
  });
}
function updateXFA({
  xfaData,
  xfaDatasetsRef,
  newRefs,
  xref
}) {
  if (xfaData === null) {
    const datasets = xref.fetchIfRef(xfaDatasetsRef);
    xfaData = writeXFADataForAcroform(datasets.getString(), newRefs);
  }
  const encrypt = xref.encrypt;
  if (encrypt) {
    const transform = encrypt.createCipherTransform(xfaDatasetsRef.num, xfaDatasetsRef.gen);
    xfaData = transform.encryptString(xfaData);
  }
  const data = `${xfaDatasetsRef.num} ${xfaDatasetsRef.gen} obj\n` + `<< /Type /EmbeddedFile /Length ${xfaData.length}>>\nstream\n` + xfaData + "\nendstream\nendobj\n";
  newRefs.push({
    ref: xfaDatasetsRef,
    data
  });
}
function incrementalUpdate({
  originalData,
  xrefInfo,
  newRefs,
  xref = null,
  hasXfa = false,
  xfaDatasetsRef = null,
  hasXfaDatasetsEntry = false,
  needAppearances,
  acroFormRef = null,
  acroForm = null,
  xfaData = null
}) {
  updateAcroform({
    xref,
    acroForm,
    acroFormRef,
    hasXfa,
    hasXfaDatasetsEntry,
    xfaDatasetsRef,
    needAppearances,
    newRefs
  });
  if (hasXfa) {
    updateXFA({
      xfaData,
      xfaDatasetsRef,
      newRefs,
      xref
    });
  }
  const newXref = new _primitives.Dict(null);
  const refForXrefTable = xrefInfo.newRef;
  let buffer, baseOffset;
  const lastByte = originalData.at(-1);
  if (lastByte === 0x0a || lastByte === 0x0d) {
    buffer = [];
    baseOffset = originalData.length;
  } else {
    buffer = ["\n"];
    baseOffset = originalData.length + 1;
  }
  newXref.set("Size", refForXrefTable.num + 1);
  newXref.set("Prev", xrefInfo.startXRef);
  newXref.set("Type", _primitives.Name.get("XRef"));
  if (xrefInfo.rootRef !== null) {
    newXref.set("Root", xrefInfo.rootRef);
  }
  if (xrefInfo.infoRef !== null) {
    newXref.set("Info", xrefInfo.infoRef);
  }
  if (xrefInfo.encryptRef !== null) {
    newXref.set("Encrypt", xrefInfo.encryptRef);
  }
  newRefs.push({
    ref: refForXrefTable,
    data: ""
  });
  newRefs = newRefs.sort((a, b) => {
    return a.ref.num - b.ref.num;
  });
  const xrefTableData = [[0, 1, 0xffff]];
  const indexes = [0, 1];
  let maxOffset = 0;
  for (const {
    ref,
    data
  } of newRefs) {
    maxOffset = Math.max(maxOffset, baseOffset);
    xrefTableData.push([1, baseOffset, Math.min(ref.gen, 0xffff)]);
    baseOffset += data.length;
    indexes.push(ref.num, 1);
    buffer.push(data);
  }
  newXref.set("Index", indexes);
  if (Array.isArray(xrefInfo.fileIds) && xrefInfo.fileIds.length > 0) {
    const md5 = computeMD5(baseOffset, xrefInfo);
    newXref.set("ID", [xrefInfo.fileIds[0], md5]);
  }
  const offsetSize = Math.ceil(Math.log2(maxOffset) / 8);
  const sizes = [1, offsetSize, 2];
  const structSize = sizes[0] + sizes[1] + sizes[2];
  const tableLength = structSize * xrefTableData.length;
  newXref.set("W", sizes);
  newXref.set("Length", tableLength);
  buffer.push(`${refForXrefTable.num} ${refForXrefTable.gen} obj\n`);
  writeDict(newXref, buffer, null);
  buffer.push(" stream\n");
  const bufferLen = buffer.reduce((a, str) => a + str.length, 0);
  const footer = `\nendstream\nendobj\nstartxref\n${baseOffset}\n%%EOF\n`;
  const array = new Uint8Array(originalData.length + bufferLen + tableLength + footer.length);
  array.set(originalData);
  let offset = originalData.length;
  for (const str of buffer) {
    writeString(str, offset, array);
    offset += str.length;
  }
  for (const [type, objOffset, gen] of xrefTableData) {
    offset = writeInt(type, sizes[0], offset, array);
    offset = writeInt(objOffset, sizes[1], offset, array);
    offset = writeInt(gen, sizes[2], offset, array);
  }
  writeString(footer, offset, array);
  return array;
}

/***/ }),
/* 64 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XMLParserErrorCode = exports.XMLParserBase = exports.SimpleXMLParser = exports.SimpleDOMNode = void 0;
var _core_utils = __w_pdfjs_require__(4);
const XMLParserErrorCode = {
  NoError: 0,
  EndOfDocument: -1,
  UnterminatedCdat: -2,
  UnterminatedXmlDeclaration: -3,
  UnterminatedDoctypeDeclaration: -4,
  UnterminatedComment: -5,
  MalformedElement: -6,
  OutOfMemory: -7,
  UnterminatedAttributeValue: -8,
  UnterminatedElement: -9,
  ElementNeverBegun: -10
};
exports.XMLParserErrorCode = XMLParserErrorCode;
function isWhitespace(s, index) {
  const ch = s[index];
  return ch === " " || ch === "\n" || ch === "\r" || ch === "\t";
}
function isWhitespaceString(s) {
  for (let i = 0, ii = s.length; i < ii; i++) {
    if (!isWhitespace(s, i)) {
      return false;
    }
  }
  return true;
}
class XMLParserBase {
  _resolveEntities(s) {
    return s.replace(/&([^;]+);/g, (all, entity) => {
      if (entity.substring(0, 2) === "#x") {
        return String.fromCodePoint(parseInt(entity.substring(2), 16));
      } else if (entity.substring(0, 1) === "#") {
        return String.fromCodePoint(parseInt(entity.substring(1), 10));
      }
      switch (entity) {
        case "lt":
          return "<";
        case "gt":
          return ">";
        case "amp":
          return "&";
        case "quot":
          return '"';
        case "apos":
          return "'";
      }
      return this.onResolveEntity(entity);
    });
  }
  _parseContent(s, start) {
    const attributes = [];
    let pos = start;
    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }
    while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== ">" && s[pos] !== "/") {
      ++pos;
    }
    const name = s.substring(start, pos);
    skipWs();
    while (pos < s.length && s[pos] !== ">" && s[pos] !== "/" && s[pos] !== "?") {
      skipWs();
      let attrName = "",
        attrValue = "";
      while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== "=") {
        attrName += s[pos];
        ++pos;
      }
      skipWs();
      if (s[pos] !== "=") {
        return null;
      }
      ++pos;
      skipWs();
      const attrEndChar = s[pos];
      if (attrEndChar !== '"' && attrEndChar !== "'") {
        return null;
      }
      const attrEndIndex = s.indexOf(attrEndChar, ++pos);
      if (attrEndIndex < 0) {
        return null;
      }
      attrValue = s.substring(pos, attrEndIndex);
      attributes.push({
        name: attrName,
        value: this._resolveEntities(attrValue)
      });
      pos = attrEndIndex + 1;
      skipWs();
    }
    return {
      name,
      attributes,
      parsed: pos - start
    };
  }
  _parseProcessingInstruction(s, start) {
    let pos = start;
    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }
    while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== ">" && s[pos] !== "?" && s[pos] !== "/") {
      ++pos;
    }
    const name = s.substring(start, pos);
    skipWs();
    const attrStart = pos;
    while (pos < s.length && (s[pos] !== "?" || s[pos + 1] !== ">")) {
      ++pos;
    }
    const value = s.substring(attrStart, pos);
    return {
      name,
      value,
      parsed: pos - start
    };
  }
  parseXml(s) {
    let i = 0;
    while (i < s.length) {
      const ch = s[i];
      let j = i;
      if (ch === "<") {
        ++j;
        const ch2 = s[j];
        let q;
        switch (ch2) {
          case "/":
            ++j;
            q = s.indexOf(">", j);
            if (q < 0) {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onEndElement(s.substring(j, q));
            j = q + 1;
            break;
          case "?":
            ++j;
            const pi = this._parseProcessingInstruction(s, j);
            if (s.substring(j + pi.parsed, j + pi.parsed + 2) !== "?>") {
              this.onError(XMLParserErrorCode.UnterminatedXmlDeclaration);
              return;
            }
            this.onPi(pi.name, pi.value);
            j += pi.parsed + 2;
            break;
          case "!":
            if (s.substring(j + 1, j + 3) === "--") {
              q = s.indexOf("-->", j + 3);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedComment);
                return;
              }
              this.onComment(s.substring(j + 3, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === "[CDATA[") {
              q = s.indexOf("]]>", j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedCdat);
                return;
              }
              this.onCdata(s.substring(j + 8, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === "DOCTYPE") {
              const q2 = s.indexOf("[", j + 8);
              let complexDoctype = false;
              q = s.indexOf(">", j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                return;
              }
              if (q2 > 0 && q > q2) {
                q = s.indexOf("]>", j + 8);
                if (q < 0) {
                  this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                  return;
                }
                complexDoctype = true;
              }
              const doctypeContent = s.substring(j + 8, q + (complexDoctype ? 1 : 0));
              this.onDoctype(doctypeContent);
              j = q + (complexDoctype ? 2 : 1);
            } else {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            break;
          default:
            const content = this._parseContent(s, j);
            if (content === null) {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            let isClosed = false;
            if (s.substring(j + content.parsed, j + content.parsed + 2) === "/>") {
              isClosed = true;
            } else if (s.substring(j + content.parsed, j + content.parsed + 1) !== ">") {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onBeginElement(content.name, content.attributes, isClosed);
            j += content.parsed + (isClosed ? 2 : 1);
            break;
        }
      } else {
        while (j < s.length && s[j] !== "<") {
          j++;
        }
        const text = s.substring(i, j);
        this.onText(this._resolveEntities(text));
      }
      i = j;
    }
  }
  onResolveEntity(name) {
    return `&${name};`;
  }
  onPi(name, value) {}
  onComment(text) {}
  onCdata(text) {}
  onDoctype(doctypeContent) {}
  onText(text) {}
  onBeginElement(name, attributes, isEmpty) {}
  onEndElement(name) {}
  onError(code) {}
}
exports.XMLParserBase = XMLParserBase;
class SimpleDOMNode {
  constructor(nodeName, nodeValue) {
    this.nodeName = nodeName;
    this.nodeValue = nodeValue;
    Object.defineProperty(this, "parentNode", {
      value: null,
      writable: true
    });
  }
  get firstChild() {
    return this.childNodes && this.childNodes[0];
  }
  get nextSibling() {
    const childNodes = this.parentNode.childNodes;
    if (!childNodes) {
      return undefined;
    }
    const index = childNodes.indexOf(this);
    if (index === -1) {
      return undefined;
    }
    return childNodes[index + 1];
  }
  get textContent() {
    if (!this.childNodes) {
      return this.nodeValue || "";
    }
    return this.childNodes.map(function (child) {
      return child.textContent;
    }).join("");
  }
  get children() {
    return this.childNodes || [];
  }
  hasChildNodes() {
    return this.childNodes && this.childNodes.length > 0;
  }
  searchNode(paths, pos) {
    if (pos >= paths.length) {
      return this;
    }
    const component = paths[pos];
    const stack = [];
    let node = this;
    while (true) {
      if (component.name === node.nodeName) {
        if (component.pos === 0) {
          const res = node.searchNode(paths, pos + 1);
          if (res !== null) {
            return res;
          }
        } else if (stack.length === 0) {
          return null;
        } else {
          const [parent] = stack.pop();
          let siblingPos = 0;
          for (const child of parent.childNodes) {
            if (component.name === child.nodeName) {
              if (siblingPos === component.pos) {
                return child.searchNode(paths, pos + 1);
              }
              siblingPos++;
            }
          }
          return node.searchNode(paths, pos + 1);
        }
      }
      if (node.childNodes && node.childNodes.length !== 0) {
        stack.push([node, 0]);
        node = node.childNodes[0];
      } else if (stack.length === 0) {
        return null;
      } else {
        while (stack.length !== 0) {
          const [parent, currentPos] = stack.pop();
          const newPos = currentPos + 1;
          if (newPos < parent.childNodes.length) {
            stack.push([parent, newPos]);
            node = parent.childNodes[newPos];
            break;
          }
        }
        if (stack.length === 0) {
          return null;
        }
      }
    }
  }
  dump(buffer) {
    if (this.nodeName === "#text") {
      buffer.push((0, _core_utils.encodeToXmlString)(this.nodeValue));
      return;
    }
    buffer.push(`<${this.nodeName}`);
    if (this.attributes) {
      for (const attribute of this.attributes) {
        buffer.push(` ${attribute.name}="${(0, _core_utils.encodeToXmlString)(attribute.value)}"`);
      }
    }
    if (this.hasChildNodes()) {
      buffer.push(">");
      for (const child of this.childNodes) {
        child.dump(buffer);
      }
      buffer.push(`</${this.nodeName}>`);
    } else if (this.nodeValue) {
      buffer.push(`>${(0, _core_utils.encodeToXmlString)(this.nodeValue)}</${this.nodeName}>`);
    } else {
      buffer.push("/>");
    }
  }
}
exports.SimpleDOMNode = SimpleDOMNode;
class SimpleXMLParser extends XMLParserBase {
  constructor({
    hasAttributes = false,
    lowerCaseName = false
  }) {
    super();
    this._currentFragment = null;
    this._stack = null;
    this._errorCode = XMLParserErrorCode.NoError;
    this._hasAttributes = hasAttributes;
    this._lowerCaseName = lowerCaseName;
  }
  parseFromString(data) {
    this._currentFragment = [];
    this._stack = [];
    this._errorCode = XMLParserErrorCode.NoError;
    this.parseXml(data);
    if (this._errorCode !== XMLParserErrorCode.NoError) {
      return undefined;
    }
    const [documentElement] = this._currentFragment;
    if (!documentElement) {
      return undefined;
    }
    return {
      documentElement
    };
  }
  onText(text) {
    if (isWhitespaceString(text)) {
      return;
    }
    const node = new SimpleDOMNode("#text", text);
    this._currentFragment.push(node);
  }
  onCdata(text) {
    const node = new SimpleDOMNode("#text", text);
    this._currentFragment.push(node);
  }
  onBeginElement(name, attributes, isEmpty) {
    if (this._lowerCaseName) {
      name = name.toLowerCase();
    }
    const node = new SimpleDOMNode(name);
    node.childNodes = [];
    if (this._hasAttributes) {
      node.attributes = attributes;
    }
    this._currentFragment.push(node);
    if (isEmpty) {
      return;
    }
    this._stack.push(this._currentFragment);
    this._currentFragment = node.childNodes;
  }
  onEndElement(name) {
    this._currentFragment = this._stack.pop() || [];
    const lastElement = this._currentFragment.at(-1);
    if (!lastElement) {
      return null;
    }
    for (const childNode of lastElement.childNodes) {
      childNode.parentNode = lastElement;
    }
    return lastElement;
  }
  onError(code) {
    this._errorCode = code;
  }
}
exports.SimpleXMLParser = SimpleXMLParser;

/***/ }),
/* 65 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.calculateSHA256 = exports.calculateMD5 = exports.PDF20 = exports.PDF17 = exports.CipherTransformFactory = exports.ARCFourCipher = exports.AES256Cipher = exports.AES128Cipher = void 0;
exports.calculateSHA384 = calculateSHA384;
exports.calculateSHA512 = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _decrypt_stream = __w_pdfjs_require__(66);
class ARCFourCipher {
  constructor(key) {
    this.a = 0;
    this.b = 0;
    const s = new Uint8Array(256);
    const keyLength = key.length;
    for (let i = 0; i < 256; ++i) {
      s[i] = i;
    }
    for (let i = 0, j = 0; i < 256; ++i) {
      const tmp = s[i];
      j = j + tmp + key[i % keyLength] & 0xff;
      s[i] = s[j];
      s[j] = tmp;
    }
    this.s = s;
  }
  encryptBlock(data) {
    let a = this.a,
      b = this.b;
    const s = this.s;
    const n = data.length;
    const output = new Uint8Array(n);
    for (let i = 0; i < n; ++i) {
      a = a + 1 & 0xff;
      const tmp = s[a];
      b = b + tmp & 0xff;
      const tmp2 = s[b];
      s[a] = tmp2;
      s[b] = tmp;
      output[i] = data[i] ^ s[tmp + tmp2 & 0xff];
    }
    this.a = a;
    this.b = b;
    return output;
  }
  decryptBlock(data) {
    return this.encryptBlock(data);
  }
  encrypt(data) {
    return this.encryptBlock(data);
  }
}
exports.ARCFourCipher = ARCFourCipher;
const calculateMD5 = function calculateMD5Closure() {
  const r = new Uint8Array([7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
  const k = new Int32Array([-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551]);
  function hash(data, offset, length) {
    let h0 = 1732584193,
      h1 = -271733879,
      h2 = -1732584194,
      h3 = 271733878;
    const paddedLength = length + 72 & ~63;
    const padded = new Uint8Array(paddedLength);
    let i, j;
    for (i = 0; i < length; ++i) {
      padded[i] = data[offset++];
    }
    padded[i++] = 0x80;
    const n = paddedLength - 8;
    while (i < n) {
      padded[i++] = 0;
    }
    padded[i++] = length << 3 & 0xff;
    padded[i++] = length >> 5 & 0xff;
    padded[i++] = length >> 13 & 0xff;
    padded[i++] = length >> 21 & 0xff;
    padded[i++] = length >>> 29 & 0xff;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    const w = new Int32Array(16);
    for (i = 0; i < paddedLength;) {
      for (j = 0; j < 16; ++j, i += 4) {
        w[j] = padded[i] | padded[i + 1] << 8 | padded[i + 2] << 16 | padded[i + 3] << 24;
      }
      let a = h0,
        b = h1,
        c = h2,
        d = h3,
        f,
        g;
      for (j = 0; j < 64; ++j) {
        if (j < 16) {
          f = b & c | ~b & d;
          g = j;
        } else if (j < 32) {
          f = d & b | ~d & c;
          g = 5 * j + 1 & 15;
        } else if (j < 48) {
          f = b ^ c ^ d;
          g = 3 * j + 5 & 15;
        } else {
          f = c ^ (b | ~d);
          g = 7 * j & 15;
        }
        const tmp = d,
          rotateArg = a + f + k[j] + w[g] | 0,
          rotate = r[j];
        d = c;
        c = b;
        b = b + (rotateArg << rotate | rotateArg >>> 32 - rotate) | 0;
        a = tmp;
      }
      h0 = h0 + a | 0;
      h1 = h1 + b | 0;
      h2 = h2 + c | 0;
      h3 = h3 + d | 0;
    }
    return new Uint8Array([h0 & 0xFF, h0 >> 8 & 0xFF, h0 >> 16 & 0xFF, h0 >>> 24 & 0xFF, h1 & 0xFF, h1 >> 8 & 0xFF, h1 >> 16 & 0xFF, h1 >>> 24 & 0xFF, h2 & 0xFF, h2 >> 8 & 0xFF, h2 >> 16 & 0xFF, h2 >>> 24 & 0xFF, h3 & 0xFF, h3 >> 8 & 0xFF, h3 >> 16 & 0xFF, h3 >>> 24 & 0xFF]);
  }
  return hash;
}();
exports.calculateMD5 = calculateMD5;
class Word64 {
  constructor(highInteger, lowInteger) {
    this.high = highInteger | 0;
    this.low = lowInteger | 0;
  }
  and(word) {
    this.high &= word.high;
    this.low &= word.low;
  }
  xor(word) {
    this.high ^= word.high;
    this.low ^= word.low;
  }
  or(word) {
    this.high |= word.high;
    this.low |= word.low;
  }
  shiftRight(places) {
    if (places >= 32) {
      this.low = this.high >>> places - 32 | 0;
      this.high = 0;
    } else {
      this.low = this.low >>> places | this.high << 32 - places;
      this.high = this.high >>> places | 0;
    }
  }
  shiftLeft(places) {
    if (places >= 32) {
      this.high = this.low << places - 32;
      this.low = 0;
    } else {
      this.high = this.high << places | this.low >>> 32 - places;
      this.low <<= places;
    }
  }
  rotateRight(places) {
    let low, high;
    if (places & 32) {
      high = this.low;
      low = this.high;
    } else {
      low = this.low;
      high = this.high;
    }
    places &= 31;
    this.low = low >>> places | high << 32 - places;
    this.high = high >>> places | low << 32 - places;
  }
  not() {
    this.high = ~this.high;
    this.low = ~this.low;
  }
  add(word) {
    const lowAdd = (this.low >>> 0) + (word.low >>> 0);
    let highAdd = (this.high >>> 0) + (word.high >>> 0);
    if (lowAdd > 0xffffffff) {
      highAdd += 1;
    }
    this.low = lowAdd | 0;
    this.high = highAdd | 0;
  }
  copyTo(bytes, offset) {
    bytes[offset] = this.high >>> 24 & 0xff;
    bytes[offset + 1] = this.high >> 16 & 0xff;
    bytes[offset + 2] = this.high >> 8 & 0xff;
    bytes[offset + 3] = this.high & 0xff;
    bytes[offset + 4] = this.low >>> 24 & 0xff;
    bytes[offset + 5] = this.low >> 16 & 0xff;
    bytes[offset + 6] = this.low >> 8 & 0xff;
    bytes[offset + 7] = this.low & 0xff;
  }
  assign(word) {
    this.high = word.high;
    this.low = word.low;
  }
}
const calculateSHA256 = function calculateSHA256Closure() {
  function rotr(x, n) {
    return x >>> n | x << 32 - n;
  }
  function ch(x, y, z) {
    return x & y ^ ~x & z;
  }
  function maj(x, y, z) {
    return x & y ^ x & z ^ y & z;
  }
  function sigma(x) {
    return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
  }
  function sigmaPrime(x) {
    return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
  }
  function littleSigma(x) {
    return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
  }
  function littleSigmaPrime(x) {
    return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
  }
  const k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  function hash(data, offset, length) {
    let h0 = 0x6a09e667,
      h1 = 0xbb67ae85,
      h2 = 0x3c6ef372,
      h3 = 0xa54ff53a,
      h4 = 0x510e527f,
      h5 = 0x9b05688c,
      h6 = 0x1f83d9ab,
      h7 = 0x5be0cd19;
    const paddedLength = Math.ceil((length + 9) / 64) * 64;
    const padded = new Uint8Array(paddedLength);
    let i, j;
    for (i = 0; i < length; ++i) {
      padded[i] = data[offset++];
    }
    padded[i++] = 0x80;
    const n = paddedLength - 8;
    while (i < n) {
      padded[i++] = 0;
    }
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = length >>> 29 & 0xff;
    padded[i++] = length >> 21 & 0xff;
    padded[i++] = length >> 13 & 0xff;
    padded[i++] = length >> 5 & 0xff;
    padded[i++] = length << 3 & 0xff;
    const w = new Uint32Array(64);
    for (i = 0; i < paddedLength;) {
      for (j = 0; j < 16; ++j) {
        w[j] = padded[i] << 24 | padded[i + 1] << 16 | padded[i + 2] << 8 | padded[i + 3];
        i += 4;
      }
      for (j = 16; j < 64; ++j) {
        w[j] = littleSigmaPrime(w[j - 2]) + w[j - 7] + littleSigma(w[j - 15]) + w[j - 16] | 0;
      }
      let a = h0,
        b = h1,
        c = h2,
        d = h3,
        e = h4,
        f = h5,
        g = h6,
        h = h7,
        t1,
        t2;
      for (j = 0; j < 64; ++j) {
        t1 = h + sigmaPrime(e) + ch(e, f, g) + k[j] + w[j];
        t2 = sigma(a) + maj(a, b, c);
        h = g;
        g = f;
        f = e;
        e = d + t1 | 0;
        d = c;
        c = b;
        b = a;
        a = t1 + t2 | 0;
      }
      h0 = h0 + a | 0;
      h1 = h1 + b | 0;
      h2 = h2 + c | 0;
      h3 = h3 + d | 0;
      h4 = h4 + e | 0;
      h5 = h5 + f | 0;
      h6 = h6 + g | 0;
      h7 = h7 + h | 0;
    }
    return new Uint8Array([h0 >> 24 & 0xFF, h0 >> 16 & 0xFF, h0 >> 8 & 0xFF, h0 & 0xFF, h1 >> 24 & 0xFF, h1 >> 16 & 0xFF, h1 >> 8 & 0xFF, h1 & 0xFF, h2 >> 24 & 0xFF, h2 >> 16 & 0xFF, h2 >> 8 & 0xFF, h2 & 0xFF, h3 >> 24 & 0xFF, h3 >> 16 & 0xFF, h3 >> 8 & 0xFF, h3 & 0xFF, h4 >> 24 & 0xFF, h4 >> 16 & 0xFF, h4 >> 8 & 0xFF, h4 & 0xFF, h5 >> 24 & 0xFF, h5 >> 16 & 0xFF, h5 >> 8 & 0xFF, h5 & 0xFF, h6 >> 24 & 0xFF, h6 >> 16 & 0xFF, h6 >> 8 & 0xFF, h6 & 0xFF, h7 >> 24 & 0xFF, h7 >> 16 & 0xFF, h7 >> 8 & 0xFF, h7 & 0xFF]);
  }
  return hash;
}();
exports.calculateSHA256 = calculateSHA256;
const calculateSHA512 = function calculateSHA512Closure() {
  function ch(result, x, y, z, tmp) {
    result.assign(x);
    result.and(y);
    tmp.assign(x);
    tmp.not();
    tmp.and(z);
    result.xor(tmp);
  }
  function maj(result, x, y, z, tmp) {
    result.assign(x);
    result.and(y);
    tmp.assign(x);
    tmp.and(z);
    result.xor(tmp);
    tmp.assign(y);
    tmp.and(z);
    result.xor(tmp);
  }
  function sigma(result, x, tmp) {
    result.assign(x);
    result.rotateRight(28);
    tmp.assign(x);
    tmp.rotateRight(34);
    result.xor(tmp);
    tmp.assign(x);
    tmp.rotateRight(39);
    result.xor(tmp);
  }
  function sigmaPrime(result, x, tmp) {
    result.assign(x);
    result.rotateRight(14);
    tmp.assign(x);
    tmp.rotateRight(18);
    result.xor(tmp);
    tmp.assign(x);
    tmp.rotateRight(41);
    result.xor(tmp);
  }
  function littleSigma(result, x, tmp) {
    result.assign(x);
    result.rotateRight(1);
    tmp.assign(x);
    tmp.rotateRight(8);
    result.xor(tmp);
    tmp.assign(x);
    tmp.shiftRight(7);
    result.xor(tmp);
  }
  function littleSigmaPrime(result, x, tmp) {
    result.assign(x);
    result.rotateRight(19);
    tmp.assign(x);
    tmp.rotateRight(61);
    result.xor(tmp);
    tmp.assign(x);
    tmp.shiftRight(6);
    result.xor(tmp);
  }
  const k = [new Word64(0x428a2f98, 0xd728ae22), new Word64(0x71374491, 0x23ef65cd), new Word64(0xb5c0fbcf, 0xec4d3b2f), new Word64(0xe9b5dba5, 0x8189dbbc), new Word64(0x3956c25b, 0xf348b538), new Word64(0x59f111f1, 0xb605d019), new Word64(0x923f82a4, 0xaf194f9b), new Word64(0xab1c5ed5, 0xda6d8118), new Word64(0xd807aa98, 0xa3030242), new Word64(0x12835b01, 0x45706fbe), new Word64(0x243185be, 0x4ee4b28c), new Word64(0x550c7dc3, 0xd5ffb4e2), new Word64(0x72be5d74, 0xf27b896f), new Word64(0x80deb1fe, 0x3b1696b1), new Word64(0x9bdc06a7, 0x25c71235), new Word64(0xc19bf174, 0xcf692694), new Word64(0xe49b69c1, 0x9ef14ad2), new Word64(0xefbe4786, 0x384f25e3), new Word64(0x0fc19dc6, 0x8b8cd5b5), new Word64(0x240ca1cc, 0x77ac9c65), new Word64(0x2de92c6f, 0x592b0275), new Word64(0x4a7484aa, 0x6ea6e483), new Word64(0x5cb0a9dc, 0xbd41fbd4), new Word64(0x76f988da, 0x831153b5), new Word64(0x983e5152, 0xee66dfab), new Word64(0xa831c66d, 0x2db43210), new Word64(0xb00327c8, 0x98fb213f), new Word64(0xbf597fc7, 0xbeef0ee4), new Word64(0xc6e00bf3, 0x3da88fc2), new Word64(0xd5a79147, 0x930aa725), new Word64(0x06ca6351, 0xe003826f), new Word64(0x14292967, 0x0a0e6e70), new Word64(0x27b70a85, 0x46d22ffc), new Word64(0x2e1b2138, 0x5c26c926), new Word64(0x4d2c6dfc, 0x5ac42aed), new Word64(0x53380d13, 0x9d95b3df), new Word64(0x650a7354, 0x8baf63de), new Word64(0x766a0abb, 0x3c77b2a8), new Word64(0x81c2c92e, 0x47edaee6), new Word64(0x92722c85, 0x1482353b), new Word64(0xa2bfe8a1, 0x4cf10364), new Word64(0xa81a664b, 0xbc423001), new Word64(0xc24b8b70, 0xd0f89791), new Word64(0xc76c51a3, 0x0654be30), new Word64(0xd192e819, 0xd6ef5218), new Word64(0xd6990624, 0x5565a910), new Word64(0xf40e3585, 0x5771202a), new Word64(0x106aa070, 0x32bbd1b8), new Word64(0x19a4c116, 0xb8d2d0c8), new Word64(0x1e376c08, 0x5141ab53), new Word64(0x2748774c, 0xdf8eeb99), new Word64(0x34b0bcb5, 0xe19b48a8), new Word64(0x391c0cb3, 0xc5c95a63), new Word64(0x4ed8aa4a, 0xe3418acb), new Word64(0x5b9cca4f, 0x7763e373), new Word64(0x682e6ff3, 0xd6b2b8a3), new Word64(0x748f82ee, 0x5defb2fc), new Word64(0x78a5636f, 0x43172f60), new Word64(0x84c87814, 0xa1f0ab72), new Word64(0x8cc70208, 0x1a6439ec), new Word64(0x90befffa, 0x23631e28), new Word64(0xa4506ceb, 0xde82bde9), new Word64(0xbef9a3f7, 0xb2c67915), new Word64(0xc67178f2, 0xe372532b), new Word64(0xca273ece, 0xea26619c), new Word64(0xd186b8c7, 0x21c0c207), new Word64(0xeada7dd6, 0xcde0eb1e), new Word64(0xf57d4f7f, 0xee6ed178), new Word64(0x06f067aa, 0x72176fba), new Word64(0x0a637dc5, 0xa2c898a6), new Word64(0x113f9804, 0xbef90dae), new Word64(0x1b710b35, 0x131c471b), new Word64(0x28db77f5, 0x23047d84), new Word64(0x32caab7b, 0x40c72493), new Word64(0x3c9ebe0a, 0x15c9bebc), new Word64(0x431d67c4, 0x9c100d4c), new Word64(0x4cc5d4be, 0xcb3e42b6), new Word64(0x597f299c, 0xfc657e2a), new Word64(0x5fcb6fab, 0x3ad6faec), new Word64(0x6c44198c, 0x4a475817)];
  function hash(data, offset, length, mode384 = false) {
    let h0, h1, h2, h3, h4, h5, h6, h7;
    if (!mode384) {
      h0 = new Word64(0x6a09e667, 0xf3bcc908);
      h1 = new Word64(0xbb67ae85, 0x84caa73b);
      h2 = new Word64(0x3c6ef372, 0xfe94f82b);
      h3 = new Word64(0xa54ff53a, 0x5f1d36f1);
      h4 = new Word64(0x510e527f, 0xade682d1);
      h5 = new Word64(0x9b05688c, 0x2b3e6c1f);
      h6 = new Word64(0x1f83d9ab, 0xfb41bd6b);
      h7 = new Word64(0x5be0cd19, 0x137e2179);
    } else {
      h0 = new Word64(0xcbbb9d5d, 0xc1059ed8);
      h1 = new Word64(0x629a292a, 0x367cd507);
      h2 = new Word64(0x9159015a, 0x3070dd17);
      h3 = new Word64(0x152fecd8, 0xf70e5939);
      h4 = new Word64(0x67332667, 0xffc00b31);
      h5 = new Word64(0x8eb44a87, 0x68581511);
      h6 = new Word64(0xdb0c2e0d, 0x64f98fa7);
      h7 = new Word64(0x47b5481d, 0xbefa4fa4);
    }
    const paddedLength = Math.ceil((length + 17) / 128) * 128;
    const padded = new Uint8Array(paddedLength);
    let i, j;
    for (i = 0; i < length; ++i) {
      padded[i] = data[offset++];
    }
    padded[i++] = 0x80;
    const n = paddedLength - 16;
    while (i < n) {
      padded[i++] = 0;
    }
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = 0;
    padded[i++] = length >>> 29 & 0xff;
    padded[i++] = length >> 21 & 0xff;
    padded[i++] = length >> 13 & 0xff;
    padded[i++] = length >> 5 & 0xff;
    padded[i++] = length << 3 & 0xff;
    const w = new Array(80);
    for (i = 0; i < 80; i++) {
      w[i] = new Word64(0, 0);
    }
    let a = new Word64(0, 0),
      b = new Word64(0, 0),
      c = new Word64(0, 0);
    let d = new Word64(0, 0),
      e = new Word64(0, 0),
      f = new Word64(0, 0);
    let g = new Word64(0, 0),
      h = new Word64(0, 0);
    const t1 = new Word64(0, 0),
      t2 = new Word64(0, 0);
    const tmp1 = new Word64(0, 0),
      tmp2 = new Word64(0, 0);
    let tmp3;
    for (i = 0; i < paddedLength;) {
      for (j = 0; j < 16; ++j) {
        w[j].high = padded[i] << 24 | padded[i + 1] << 16 | padded[i + 2] << 8 | padded[i + 3];
        w[j].low = padded[i + 4] << 24 | padded[i + 5] << 16 | padded[i + 6] << 8 | padded[i + 7];
        i += 8;
      }
      for (j = 16; j < 80; ++j) {
        tmp3 = w[j];
        littleSigmaPrime(tmp3, w[j - 2], tmp2);
        tmp3.add(w[j - 7]);
        littleSigma(tmp1, w[j - 15], tmp2);
        tmp3.add(tmp1);
        tmp3.add(w[j - 16]);
      }
      a.assign(h0);
      b.assign(h1);
      c.assign(h2);
      d.assign(h3);
      e.assign(h4);
      f.assign(h5);
      g.assign(h6);
      h.assign(h7);
      for (j = 0; j < 80; ++j) {
        t1.assign(h);
        sigmaPrime(tmp1, e, tmp2);
        t1.add(tmp1);
        ch(tmp1, e, f, g, tmp2);
        t1.add(tmp1);
        t1.add(k[j]);
        t1.add(w[j]);
        sigma(t2, a, tmp2);
        maj(tmp1, a, b, c, tmp2);
        t2.add(tmp1);
        tmp3 = h;
        h = g;
        g = f;
        f = e;
        d.add(t1);
        e = d;
        d = c;
        c = b;
        b = a;
        tmp3.assign(t1);
        tmp3.add(t2);
        a = tmp3;
      }
      h0.add(a);
      h1.add(b);
      h2.add(c);
      h3.add(d);
      h4.add(e);
      h5.add(f);
      h6.add(g);
      h7.add(h);
    }
    let result;
    if (!mode384) {
      result = new Uint8Array(64);
      h0.copyTo(result, 0);
      h1.copyTo(result, 8);
      h2.copyTo(result, 16);
      h3.copyTo(result, 24);
      h4.copyTo(result, 32);
      h5.copyTo(result, 40);
      h6.copyTo(result, 48);
      h7.copyTo(result, 56);
    } else {
      result = new Uint8Array(48);
      h0.copyTo(result, 0);
      h1.copyTo(result, 8);
      h2.copyTo(result, 16);
      h3.copyTo(result, 24);
      h4.copyTo(result, 32);
      h5.copyTo(result, 40);
    }
    return result;
  }
  return hash;
}();
exports.calculateSHA512 = calculateSHA512;
function calculateSHA384(data, offset, length) {
  return calculateSHA512(data, offset, length, true);
}
class NullCipher {
  decryptBlock(data) {
    return data;
  }
  encrypt(data) {
    return data;
  }
}
class AESBaseCipher {
  constructor() {
    if (this.constructor === AESBaseCipher) {
      (0, _util.unreachable)("Cannot initialize AESBaseCipher.");
    }
    this._s = new Uint8Array([0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]);
    this._inv_s = new Uint8Array([0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]);
    this._mix = new Uint32Array([0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]);
    this._mixCol = new Uint8Array(256);
    for (let i = 0; i < 256; i++) {
      if (i < 128) {
        this._mixCol[i] = i << 1;
      } else {
        this._mixCol[i] = i << 1 ^ 0x1b;
      }
    }
    this.buffer = new Uint8Array(16);
    this.bufferPosition = 0;
  }
  _expandKey(cipherKey) {
    (0, _util.unreachable)("Cannot call `_expandKey` on the base class");
  }
  _decrypt(input, key) {
    let t, u, v;
    const state = new Uint8Array(16);
    state.set(input);
    for (let j = 0, k = this._keySize; j < 16; ++j, ++k) {
      state[j] ^= key[k];
    }
    for (let i = this._cyclesOfRepetition - 1; i >= 1; --i) {
      t = state[13];
      state[13] = state[9];
      state[9] = state[5];
      state[5] = state[1];
      state[1] = t;
      t = state[14];
      u = state[10];
      state[14] = state[6];
      state[10] = state[2];
      state[6] = t;
      state[2] = u;
      t = state[15];
      u = state[11];
      v = state[7];
      state[15] = state[3];
      state[11] = t;
      state[7] = u;
      state[3] = v;
      for (let j = 0; j < 16; ++j) {
        state[j] = this._inv_s[state[j]];
      }
      for (let j = 0, k = i * 16; j < 16; ++j, ++k) {
        state[j] ^= key[k];
      }
      for (let j = 0; j < 16; j += 4) {
        const s0 = this._mix[state[j]];
        const s1 = this._mix[state[j + 1]];
        const s2 = this._mix[state[j + 2]];
        const s3 = this._mix[state[j + 3]];
        t = s0 ^ s1 >>> 8 ^ s1 << 24 ^ s2 >>> 16 ^ s2 << 16 ^ s3 >>> 24 ^ s3 << 8;
        state[j] = t >>> 24 & 0xff;
        state[j + 1] = t >> 16 & 0xff;
        state[j + 2] = t >> 8 & 0xff;
        state[j + 3] = t & 0xff;
      }
    }
    t = state[13];
    state[13] = state[9];
    state[9] = state[5];
    state[5] = state[1];
    state[1] = t;
    t = state[14];
    u = state[10];
    state[14] = state[6];
    state[10] = state[2];
    state[6] = t;
    state[2] = u;
    t = state[15];
    u = state[11];
    v = state[7];
    state[15] = state[3];
    state[11] = t;
    state[7] = u;
    state[3] = v;
    for (let j = 0; j < 16; ++j) {
      state[j] = this._inv_s[state[j]];
      state[j] ^= key[j];
    }
    return state;
  }
  _encrypt(input, key) {
    const s = this._s;
    let t, u, v;
    const state = new Uint8Array(16);
    state.set(input);
    for (let j = 0; j < 16; ++j) {
      state[j] ^= key[j];
    }
    for (let i = 1; i < this._cyclesOfRepetition; i++) {
      for (let j = 0; j < 16; ++j) {
        state[j] = s[state[j]];
      }
      v = state[1];
      state[1] = state[5];
      state[5] = state[9];
      state[9] = state[13];
      state[13] = v;
      v = state[2];
      u = state[6];
      state[2] = state[10];
      state[6] = state[14];
      state[10] = v;
      state[14] = u;
      v = state[3];
      u = state[7];
      t = state[11];
      state[3] = state[15];
      state[7] = v;
      state[11] = u;
      state[15] = t;
      for (let j = 0; j < 16; j += 4) {
        const s0 = state[j + 0];
        const s1 = state[j + 1];
        const s2 = state[j + 2];
        const s3 = state[j + 3];
        t = s0 ^ s1 ^ s2 ^ s3;
        state[j + 0] ^= t ^ this._mixCol[s0 ^ s1];
        state[j + 1] ^= t ^ this._mixCol[s1 ^ s2];
        state[j + 2] ^= t ^ this._mixCol[s2 ^ s3];
        state[j + 3] ^= t ^ this._mixCol[s3 ^ s0];
      }
      for (let j = 0, k = i * 16; j < 16; ++j, ++k) {
        state[j] ^= key[k];
      }
    }
    for (let j = 0; j < 16; ++j) {
      state[j] = s[state[j]];
    }
    v = state[1];
    state[1] = state[5];
    state[5] = state[9];
    state[9] = state[13];
    state[13] = v;
    v = state[2];
    u = state[6];
    state[2] = state[10];
    state[6] = state[14];
    state[10] = v;
    state[14] = u;
    v = state[3];
    u = state[7];
    t = state[11];
    state[3] = state[15];
    state[7] = v;
    state[11] = u;
    state[15] = t;
    for (let j = 0, k = this._keySize; j < 16; ++j, ++k) {
      state[j] ^= key[k];
    }
    return state;
  }
  _decryptBlock2(data, finalize) {
    const sourceLength = data.length;
    let buffer = this.buffer,
      bufferLength = this.bufferPosition;
    const result = [];
    let iv = this.iv;
    for (let i = 0; i < sourceLength; ++i) {
      buffer[bufferLength] = data[i];
      ++bufferLength;
      if (bufferLength < 16) {
        continue;
      }
      const plain = this._decrypt(buffer, this._key);
      for (let j = 0; j < 16; ++j) {
        plain[j] ^= iv[j];
      }
      iv = buffer;
      result.push(plain);
      buffer = new Uint8Array(16);
      bufferLength = 0;
    }
    this.buffer = buffer;
    this.bufferLength = bufferLength;
    this.iv = iv;
    if (result.length === 0) {
      return new Uint8Array(0);
    }
    let outputLength = 16 * result.length;
    if (finalize) {
      const lastBlock = result.at(-1);
      let psLen = lastBlock[15];
      if (psLen <= 16) {
        for (let i = 15, ii = 16 - psLen; i >= ii; --i) {
          if (lastBlock[i] !== psLen) {
            psLen = 0;
            break;
          }
        }
        outputLength -= psLen;
        result[result.length - 1] = lastBlock.subarray(0, 16 - psLen);
      }
    }
    const output = new Uint8Array(outputLength);
    for (let i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
      output.set(result[i], j);
    }
    return output;
  }
  decryptBlock(data, finalize, iv = null) {
    const sourceLength = data.length;
    const buffer = this.buffer;
    let bufferLength = this.bufferPosition;
    if (iv) {
      this.iv = iv;
    } else {
      for (let i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {
        buffer[bufferLength] = data[i];
      }
      if (bufferLength < 16) {
        this.bufferLength = bufferLength;
        return new Uint8Array(0);
      }
      this.iv = buffer;
      data = data.subarray(16);
    }
    this.buffer = new Uint8Array(16);
    this.bufferLength = 0;
    this.decryptBlock = this._decryptBlock2;
    return this.decryptBlock(data, finalize);
  }
  encrypt(data, iv) {
    const sourceLength = data.length;
    let buffer = this.buffer,
      bufferLength = this.bufferPosition;
    const result = [];
    if (!iv) {
      iv = new Uint8Array(16);
    }
    for (let i = 0; i < sourceLength; ++i) {
      buffer[bufferLength] = data[i];
      ++bufferLength;
      if (bufferLength < 16) {
        continue;
      }
      for (let j = 0; j < 16; ++j) {
        buffer[j] ^= iv[j];
      }
      const cipher = this._encrypt(buffer, this._key);
      iv = cipher;
      result.push(cipher);
      buffer = new Uint8Array(16);
      bufferLength = 0;
    }
    this.buffer = buffer;
    this.bufferLength = bufferLength;
    this.iv = iv;
    if (result.length === 0) {
      return new Uint8Array(0);
    }
    const outputLength = 16 * result.length;
    const output = new Uint8Array(outputLength);
    for (let i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {
      output.set(result[i], j);
    }
    return output;
  }
}
class AES128Cipher extends AESBaseCipher {
  constructor(key) {
    super();
    this._cyclesOfRepetition = 10;
    this._keySize = 160;
    this._rcon = new Uint8Array([0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d]);
    this._key = this._expandKey(key);
  }
  _expandKey(cipherKey) {
    const b = 176;
    const s = this._s;
    const rcon = this._rcon;
    const result = new Uint8Array(b);
    result.set(cipherKey);
    for (let j = 16, i = 1; j < b; ++i) {
      let t1 = result[j - 3];
      let t2 = result[j - 2];
      let t3 = result[j - 1];
      let t4 = result[j - 4];
      t1 = s[t1];
      t2 = s[t2];
      t3 = s[t3];
      t4 = s[t4];
      t1 ^= rcon[i];
      for (let n = 0; n < 4; ++n) {
        result[j] = t1 ^= result[j - 16];
        j++;
        result[j] = t2 ^= result[j - 16];
        j++;
        result[j] = t3 ^= result[j - 16];
        j++;
        result[j] = t4 ^= result[j - 16];
        j++;
      }
    }
    return result;
  }
}
exports.AES128Cipher = AES128Cipher;
class AES256Cipher extends AESBaseCipher {
  constructor(key) {
    super();
    this._cyclesOfRepetition = 14;
    this._keySize = 224;
    this._key = this._expandKey(key);
  }
  _expandKey(cipherKey) {
    const b = 240;
    const s = this._s;
    const result = new Uint8Array(b);
    result.set(cipherKey);
    let r = 1;
    let t1, t2, t3, t4;
    for (let j = 32, i = 1; j < b; ++i) {
      if (j % 32 === 16) {
        t1 = s[t1];
        t2 = s[t2];
        t3 = s[t3];
        t4 = s[t4];
      } else if (j % 32 === 0) {
        t1 = result[j - 3];
        t2 = result[j - 2];
        t3 = result[j - 1];
        t4 = result[j - 4];
        t1 = s[t1];
        t2 = s[t2];
        t3 = s[t3];
        t4 = s[t4];
        t1 ^= r;
        if ((r <<= 1) >= 256) {
          r = (r ^ 0x1b) & 0xff;
        }
      }
      for (let n = 0; n < 4; ++n) {
        result[j] = t1 ^= result[j - 32];
        j++;
        result[j] = t2 ^= result[j - 32];
        j++;
        result[j] = t3 ^= result[j - 32];
        j++;
        result[j] = t4 ^= result[j - 32];
        j++;
      }
    }
    return result;
  }
}
exports.AES256Cipher = AES256Cipher;
class PDF17 {
  checkOwnerPassword(password, ownerValidationSalt, userBytes, ownerPassword) {
    const hashData = new Uint8Array(password.length + 56);
    hashData.set(password, 0);
    hashData.set(ownerValidationSalt, password.length);
    hashData.set(userBytes, password.length + ownerValidationSalt.length);
    const result = calculateSHA256(hashData, 0, hashData.length);
    return (0, _util.isArrayEqual)(result, ownerPassword);
  }
  checkUserPassword(password, userValidationSalt, userPassword) {
    const hashData = new Uint8Array(password.length + 8);
    hashData.set(password, 0);
    hashData.set(userValidationSalt, password.length);
    const result = calculateSHA256(hashData, 0, hashData.length);
    return (0, _util.isArrayEqual)(result, userPassword);
  }
  getOwnerKey(password, ownerKeySalt, userBytes, ownerEncryption) {
    const hashData = new Uint8Array(password.length + 56);
    hashData.set(password, 0);
    hashData.set(ownerKeySalt, password.length);
    hashData.set(userBytes, password.length + ownerKeySalt.length);
    const key = calculateSHA256(hashData, 0, hashData.length);
    const cipher = new AES256Cipher(key);
    return cipher.decryptBlock(ownerEncryption, false, new Uint8Array(16));
  }
  getUserKey(password, userKeySalt, userEncryption) {
    const hashData = new Uint8Array(password.length + 8);
    hashData.set(password, 0);
    hashData.set(userKeySalt, password.length);
    const key = calculateSHA256(hashData, 0, hashData.length);
    const cipher = new AES256Cipher(key);
    return cipher.decryptBlock(userEncryption, false, new Uint8Array(16));
  }
}
exports.PDF17 = PDF17;
const PDF20 = function PDF20Closure() {
  function calculatePDF20Hash(password, input, userBytes) {
    let k = calculateSHA256(input, 0, input.length).subarray(0, 32);
    let e = [0];
    let i = 0;
    while (i < 64 || e.at(-1) > i - 32) {
      const combinedLength = password.length + k.length + userBytes.length,
        combinedArray = new Uint8Array(combinedLength);
      let writeOffset = 0;
      combinedArray.set(password, writeOffset);
      writeOffset += password.length;
      combinedArray.set(k, writeOffset);
      writeOffset += k.length;
      combinedArray.set(userBytes, writeOffset);
      const k1 = new Uint8Array(combinedLength * 64);
      for (let j = 0, pos = 0; j < 64; j++, pos += combinedLength) {
        k1.set(combinedArray, pos);
      }
      const cipher = new AES128Cipher(k.subarray(0, 16));
      e = cipher.encrypt(k1, k.subarray(16, 32));
      const remainder = e.slice(0, 16).reduce((a, b) => a + b, 0) % 3;
      if (remainder === 0) {
        k = calculateSHA256(e, 0, e.length);
      } else if (remainder === 1) {
        k = calculateSHA384(e, 0, e.length);
      } else if (remainder === 2) {
        k = calculateSHA512(e, 0, e.length);
      }
      i++;
    }
    return k.subarray(0, 32);
  }
  class PDF20 {
    hash(password, concatBytes, userBytes) {
      return calculatePDF20Hash(password, concatBytes, userBytes);
    }
    checkOwnerPassword(password, ownerValidationSalt, userBytes, ownerPassword) {
      const hashData = new Uint8Array(password.length + 56);
      hashData.set(password, 0);
      hashData.set(ownerValidationSalt, password.length);
      hashData.set(userBytes, password.length + ownerValidationSalt.length);
      const result = calculatePDF20Hash(password, hashData, userBytes);
      return (0, _util.isArrayEqual)(result, ownerPassword);
    }
    checkUserPassword(password, userValidationSalt, userPassword) {
      const hashData = new Uint8Array(password.length + 8);
      hashData.set(password, 0);
      hashData.set(userValidationSalt, password.length);
      const result = calculatePDF20Hash(password, hashData, []);
      return (0, _util.isArrayEqual)(result, userPassword);
    }
    getOwnerKey(password, ownerKeySalt, userBytes, ownerEncryption) {
      const hashData = new Uint8Array(password.length + 56);
      hashData.set(password, 0);
      hashData.set(ownerKeySalt, password.length);
      hashData.set(userBytes, password.length + ownerKeySalt.length);
      const key = calculatePDF20Hash(password, hashData, userBytes);
      const cipher = new AES256Cipher(key);
      return cipher.decryptBlock(ownerEncryption, false, new Uint8Array(16));
    }
    getUserKey(password, userKeySalt, userEncryption) {
      const hashData = new Uint8Array(password.length + 8);
      hashData.set(password, 0);
      hashData.set(userKeySalt, password.length);
      const key = calculatePDF20Hash(password, hashData, []);
      const cipher = new AES256Cipher(key);
      return cipher.decryptBlock(userEncryption, false, new Uint8Array(16));
    }
  }
  return PDF20;
}();
exports.PDF20 = PDF20;
class CipherTransform {
  constructor(stringCipherConstructor, streamCipherConstructor) {
    this.StringCipherConstructor = stringCipherConstructor;
    this.StreamCipherConstructor = streamCipherConstructor;
  }
  createStream(stream, length) {
    const cipher = new this.StreamCipherConstructor();
    return new _decrypt_stream.DecryptStream(stream, length, function cipherTransformDecryptStream(data, finalize) {
      return cipher.decryptBlock(data, finalize);
    });
  }
  decryptString(s) {
    const cipher = new this.StringCipherConstructor();
    let data = (0, _util.stringToBytes)(s);
    data = cipher.decryptBlock(data, true);
    return (0, _util.bytesToString)(data);
  }
  encryptString(s) {
    const cipher = new this.StringCipherConstructor();
    if (cipher instanceof AESBaseCipher) {
      const strLen = s.length;
      const pad = 16 - strLen % 16;
      s += String.fromCharCode(pad).repeat(pad);
      const iv = new Uint8Array(16);
      if (typeof crypto !== "undefined") {
        crypto.getRandomValues(iv);
      } else {
        for (let i = 0; i < 16; i++) {
          iv[i] = Math.floor(256 * Math.random());
        }
      }
      let data = (0, _util.stringToBytes)(s);
      data = cipher.encrypt(data, iv);
      const buf = new Uint8Array(16 + data.length);
      buf.set(iv);
      buf.set(data, 16);
      return (0, _util.bytesToString)(buf);
    }
    let data = (0, _util.stringToBytes)(s);
    data = cipher.encrypt(data);
    return (0, _util.bytesToString)(data);
  }
}
const CipherTransformFactory = function CipherTransformFactoryClosure() {
  const defaultPasswordBytes = new Uint8Array([0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a]);
  function createEncryptionKey20(revision, password, ownerPassword, ownerValidationSalt, ownerKeySalt, uBytes, userPassword, userValidationSalt, userKeySalt, ownerEncryption, userEncryption, perms) {
    if (password) {
      const passwordLength = Math.min(127, password.length);
      password = password.subarray(0, passwordLength);
    } else {
      password = [];
    }
    let pdfAlgorithm;
    if (revision === 6) {
      pdfAlgorithm = new PDF20();
    } else {
      pdfAlgorithm = new PDF17();
    }
    if (pdfAlgorithm.checkUserPassword(password, userValidationSalt, userPassword)) {
      return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
    } else if (password.length && pdfAlgorithm.checkOwnerPassword(password, ownerValidationSalt, uBytes, ownerPassword)) {
      return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes, ownerEncryption);
    }
    return null;
  }
  function prepareKeyData(fileId, password, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata) {
    const hashDataSize = 40 + ownerPassword.length + fileId.length;
    const hashData = new Uint8Array(hashDataSize);
    let i = 0,
      j,
      n;
    if (password) {
      n = Math.min(32, password.length);
      for (; i < n; ++i) {
        hashData[i] = password[i];
      }
    }
    j = 0;
    while (i < 32) {
      hashData[i++] = defaultPasswordBytes[j++];
    }
    for (j = 0, n = ownerPassword.length; j < n; ++j) {
      hashData[i++] = ownerPassword[j];
    }
    hashData[i++] = flags & 0xff;
    hashData[i++] = flags >> 8 & 0xff;
    hashData[i++] = flags >> 16 & 0xff;
    hashData[i++] = flags >>> 24 & 0xff;
    for (j = 0, n = fileId.length; j < n; ++j) {
      hashData[i++] = fileId[j];
    }
    if (revision >= 4 && !encryptMetadata) {
      hashData[i++] = 0xff;
      hashData[i++] = 0xff;
      hashData[i++] = 0xff;
      hashData[i++] = 0xff;
    }
    let hash = calculateMD5(hashData, 0, i);
    const keyLengthInBytes = keyLength >> 3;
    if (revision >= 3) {
      for (j = 0; j < 50; ++j) {
        hash = calculateMD5(hash, 0, keyLengthInBytes);
      }
    }
    const encryptionKey = hash.subarray(0, keyLengthInBytes);
    let cipher, checkData;
    if (revision >= 3) {
      for (i = 0; i < 32; ++i) {
        hashData[i] = defaultPasswordBytes[i];
      }
      for (j = 0, n = fileId.length; j < n; ++j) {
        hashData[i++] = fileId[j];
      }
      cipher = new ARCFourCipher(encryptionKey);
      checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
      n = encryptionKey.length;
      const derivedKey = new Uint8Array(n);
      for (j = 1; j <= 19; ++j) {
        for (let k = 0; k < n; ++k) {
          derivedKey[k] = encryptionKey[k] ^ j;
        }
        cipher = new ARCFourCipher(derivedKey);
        checkData = cipher.encryptBlock(checkData);
      }
      for (j = 0, n = checkData.length; j < n; ++j) {
        if (userPassword[j] !== checkData[j]) {
          return null;
        }
      }
    } else {
      cipher = new ARCFourCipher(encryptionKey);
      checkData = cipher.encryptBlock(defaultPasswordBytes);
      for (j = 0, n = checkData.length; j < n; ++j) {
        if (userPassword[j] !== checkData[j]) {
          return null;
        }
      }
    }
    return encryptionKey;
  }
  function decodeUserPassword(password, ownerPassword, revision, keyLength) {
    const hashData = new Uint8Array(32);
    let i = 0;
    const n = Math.min(32, password.length);
    for (; i < n; ++i) {
      hashData[i] = password[i];
    }
    let j = 0;
    while (i < 32) {
      hashData[i++] = defaultPasswordBytes[j++];
    }
    let hash = calculateMD5(hashData, 0, i);
    const keyLengthInBytes = keyLength >> 3;
    if (revision >= 3) {
      for (j = 0; j < 50; ++j) {
        hash = calculateMD5(hash, 0, hash.length);
      }
    }
    let cipher, userPassword;
    if (revision >= 3) {
      userPassword = ownerPassword;
      const derivedKey = new Uint8Array(keyLengthInBytes);
      for (j = 19; j >= 0; j--) {
        for (let k = 0; k < keyLengthInBytes; ++k) {
          derivedKey[k] = hash[k] ^ j;
        }
        cipher = new ARCFourCipher(derivedKey);
        userPassword = cipher.encryptBlock(userPassword);
      }
    } else {
      cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
      userPassword = cipher.encryptBlock(ownerPassword);
    }
    return userPassword;
  }
  const identityName = _primitives.Name.get("Identity");
  function buildObjectKey(num, gen, encryptionKey, isAes = false) {
    const key = new Uint8Array(encryptionKey.length + 9);
    const n = encryptionKey.length;
    let i;
    for (i = 0; i < n; ++i) {
      key[i] = encryptionKey[i];
    }
    key[i++] = num & 0xff;
    key[i++] = num >> 8 & 0xff;
    key[i++] = num >> 16 & 0xff;
    key[i++] = gen & 0xff;
    key[i++] = gen >> 8 & 0xff;
    if (isAes) {
      key[i++] = 0x73;
      key[i++] = 0x41;
      key[i++] = 0x6c;
      key[i++] = 0x54;
    }
    const hash = calculateMD5(key, 0, i);
    return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
  }
  function buildCipherConstructor(cf, name, num, gen, key) {
    if (!(name instanceof _primitives.Name)) {
      throw new _util.FormatError("Invalid crypt filter name.");
    }
    const cryptFilter = cf.get(name.name);
    let cfm;
    if (cryptFilter !== null && cryptFilter !== undefined) {
      cfm = cryptFilter.get("CFM");
    }
    if (!cfm || cfm.name === "None") {
      return function cipherTransformFactoryBuildCipherConstructorNone() {
        return new NullCipher();
      };
    }
    if (cfm.name === "V2") {
      return function cipherTransformFactoryBuildCipherConstructorV2() {
        return new ARCFourCipher(buildObjectKey(num, gen, key, false));
      };
    }
    if (cfm.name === "AESV2") {
      return function cipherTransformFactoryBuildCipherConstructorAESV2() {
        return new AES128Cipher(buildObjectKey(num, gen, key, true));
      };
    }
    if (cfm.name === "AESV3") {
      return function cipherTransformFactoryBuildCipherConstructorAESV3() {
        return new AES256Cipher(key);
      };
    }
    throw new _util.FormatError("Unknown crypto method");
  }
  class CipherTransformFactory {
    constructor(dict, fileId, password) {
      const filter = dict.get("Filter");
      if (!(0, _primitives.isName)(filter, "Standard")) {
        throw new _util.FormatError("unknown encryption method");
      }
      this.filterName = filter.name;
      this.dict = dict;
      const algorithm = dict.get("V");
      if (!Number.isInteger(algorithm) || algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && algorithm !== 5) {
        throw new _util.FormatError("unsupported encryption algorithm");
      }
      this.algorithm = algorithm;
      let keyLength = dict.get("Length");
      if (!keyLength) {
        if (algorithm <= 3) {
          keyLength = 40;
        } else {
          const cfDict = dict.get("CF");
          const streamCryptoName = dict.get("StmF");
          if (cfDict instanceof _primitives.Dict && streamCryptoName instanceof _primitives.Name) {
            cfDict.suppressEncryption = true;
            const handlerDict = cfDict.get(streamCryptoName.name);
            keyLength = handlerDict && handlerDict.get("Length") || 128;
            if (keyLength < 40) {
              keyLength <<= 3;
            }
          }
        }
      }
      if (!Number.isInteger(keyLength) || keyLength < 40 || keyLength % 8 !== 0) {
        throw new _util.FormatError("invalid key length");
      }
      const ownerPassword = (0, _util.stringToBytes)(dict.get("O")).subarray(0, 32);
      const userPassword = (0, _util.stringToBytes)(dict.get("U")).subarray(0, 32);
      const flags = dict.get("P");
      const revision = dict.get("R");
      const encryptMetadata = (algorithm === 4 || algorithm === 5) && dict.get("EncryptMetadata") !== false;
      this.encryptMetadata = encryptMetadata;
      const fileIdBytes = (0, _util.stringToBytes)(fileId);
      let passwordBytes;
      if (password) {
        if (revision === 6) {
          try {
            password = (0, _util.utf8StringToString)(password);
          } catch (ex) {
            (0, _util.warn)("CipherTransformFactory: " + "Unable to convert UTF8 encoded password.");
          }
        }
        passwordBytes = (0, _util.stringToBytes)(password);
      }
      let encryptionKey;
      if (algorithm !== 5) {
        encryptionKey = prepareKeyData(fileIdBytes, passwordBytes, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata);
      } else {
        const ownerValidationSalt = (0, _util.stringToBytes)(dict.get("O")).subarray(32, 40);
        const ownerKeySalt = (0, _util.stringToBytes)(dict.get("O")).subarray(40, 48);
        const uBytes = (0, _util.stringToBytes)(dict.get("U")).subarray(0, 48);
        const userValidationSalt = (0, _util.stringToBytes)(dict.get("U")).subarray(32, 40);
        const userKeySalt = (0, _util.stringToBytes)(dict.get("U")).subarray(40, 48);
        const ownerEncryption = (0, _util.stringToBytes)(dict.get("OE"));
        const userEncryption = (0, _util.stringToBytes)(dict.get("UE"));
        const perms = (0, _util.stringToBytes)(dict.get("Perms"));
        encryptionKey = createEncryptionKey20(revision, passwordBytes, ownerPassword, ownerValidationSalt, ownerKeySalt, uBytes, userPassword, userValidationSalt, userKeySalt, ownerEncryption, userEncryption, perms);
      }
      if (!encryptionKey && !password) {
        throw new _util.PasswordException("No password given", _util.PasswordResponses.NEED_PASSWORD);
      } else if (!encryptionKey && password) {
        const decodedPassword = decodeUserPassword(passwordBytes, ownerPassword, revision, keyLength);
        encryptionKey = prepareKeyData(fileIdBytes, decodedPassword, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata);
      }
      if (!encryptionKey) {
        throw new _util.PasswordException("Incorrect Password", _util.PasswordResponses.INCORRECT_PASSWORD);
      }
      this.encryptionKey = encryptionKey;
      if (algorithm >= 4) {
        const cf = dict.get("CF");
        if (cf instanceof _primitives.Dict) {
          cf.suppressEncryption = true;
        }
        this.cf = cf;
        this.stmf = dict.get("StmF") || identityName;
        this.strf = dict.get("StrF") || identityName;
        this.eff = dict.get("EFF") || this.stmf;
      }
    }
    createCipherTransform(num, gen) {
      if (this.algorithm === 4 || this.algorithm === 5) {
        return new CipherTransform(buildCipherConstructor(this.cf, this.strf, num, gen, this.encryptionKey), buildCipherConstructor(this.cf, this.stmf, num, gen, this.encryptionKey));
      }
      const key = buildObjectKey(num, gen, this.encryptionKey, false);
      const cipherConstructor = function buildCipherCipherConstructor() {
        return new ARCFourCipher(key);
      };
      return new CipherTransform(cipherConstructor, cipherConstructor);
    }
  }
  return CipherTransformFactory;
}();
exports.CipherTransformFactory = CipherTransformFactory;

/***/ }),
/* 66 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.DecryptStream = void 0;
var _decode_stream = __w_pdfjs_require__(17);
const chunkSize = 512;
class DecryptStream extends _decode_stream.DecodeStream {
  constructor(str, maybeLength, decrypt) {
    super(maybeLength);
    this.str = str;
    this.dict = str.dict;
    this.decrypt = decrypt;
    this.nextChunk = null;
    this.initialized = false;
  }
  readBlock() {
    let chunk;
    if (this.initialized) {
      chunk = this.nextChunk;
    } else {
      chunk = this.str.getBytes(chunkSize);
      this.initialized = true;
    }
    if (!chunk || chunk.length === 0) {
      this.eof = true;
      return;
    }
    this.nextChunk = this.str.getBytes(chunkSize);
    const hasMoreData = this.nextChunk && this.nextChunk.length > 0;
    const decrypt = this.decrypt;
    chunk = decrypt(chunk, !hasMoreData);
    const bufferLength = this.bufferLength,
      newLength = bufferLength + chunk.length,
      buffer = this.ensureBuffer(newLength);
    buffer.set(chunk, bufferLength);
    this.bufferLength = newLength;
  }
}
exports.DecryptStream = DecryptStream;

/***/ }),
/* 67 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Catalog = void 0;
var _core_utils = __w_pdfjs_require__(4);
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _name_number_tree = __w_pdfjs_require__(68);
var _base_stream = __w_pdfjs_require__(5);
var _cleanup_helper = __w_pdfjs_require__(69);
var _colorspace = __w_pdfjs_require__(12);
var _file_spec = __w_pdfjs_require__(70);
var _image_utils = __w_pdfjs_require__(57);
var _metadata_parser = __w_pdfjs_require__(71);
var _struct_tree = __w_pdfjs_require__(72);
function fetchDestination(dest) {
  if (dest instanceof _primitives.Dict) {
    dest = dest.get("D");
  }
  return Array.isArray(dest) ? dest : null;
}
class Catalog {
  constructor(pdfManager, xref) {
    this.pdfManager = pdfManager;
    this.xref = xref;
    this._catDict = xref.getCatalogObj();
    if (!(this._catDict instanceof _primitives.Dict)) {
      throw new _util.FormatError("Catalog object is not a dictionary.");
    }
    this.toplevelPagesDict;
    this._actualNumPages = null;
    this.fontCache = new _primitives.RefSetCache();
    this.builtInCMapCache = new Map();
    this.standardFontDataCache = new Map();
    this.globalImageCache = new _image_utils.GlobalImageCache();
    this.pageKidsCountCache = new _primitives.RefSetCache();
    this.pageIndexCache = new _primitives.RefSetCache();
    this.nonBlendModesSet = new _primitives.RefSet();
  }
  get version() {
    const version = this._catDict.get("Version");
    if (version instanceof _primitives.Name) {
      if (_core_utils.PDF_VERSION_REGEXP.test(version.name)) {
        return (0, _util.shadow)(this, "version", version.name);
      }
      (0, _util.warn)(`Invalid PDF catalog version: ${version.name}`);
    }
    return (0, _util.shadow)(this, "version", null);
  }
  get lang() {
    const lang = this._catDict.get("Lang");
    return (0, _util.shadow)(this, "lang", typeof lang === "string" ? (0, _util.stringToPDFString)(lang) : null);
  }
  get needsRendering() {
    const needsRendering = this._catDict.get("NeedsRendering");
    return (0, _util.shadow)(this, "needsRendering", typeof needsRendering === "boolean" ? needsRendering : false);
  }
  get collection() {
    let collection = null;
    try {
      const obj = this._catDict.get("Collection");
      if (obj instanceof _primitives.Dict && obj.size > 0) {
        collection = obj;
      }
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.info)("Cannot fetch Collection entry; assuming no collection is present.");
    }
    return (0, _util.shadow)(this, "collection", collection);
  }
  get acroForm() {
    let acroForm = null;
    try {
      const obj = this._catDict.get("AcroForm");
      if (obj instanceof _primitives.Dict && obj.size > 0) {
        acroForm = obj;
      }
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.info)("Cannot fetch AcroForm entry; assuming no forms are present.");
    }
    return (0, _util.shadow)(this, "acroForm", acroForm);
  }
  get acroFormRef() {
    const value = this._catDict.getRaw("AcroForm");
    return (0, _util.shadow)(this, "acroFormRef", value instanceof _primitives.Ref ? value : null);
  }
  get metadata() {
    const streamRef = this._catDict.getRaw("Metadata");
    if (!(streamRef instanceof _primitives.Ref)) {
      return (0, _util.shadow)(this, "metadata", null);
    }
    let metadata = null;
    try {
      const suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
      const stream = this.xref.fetch(streamRef, suppressEncryption);
      if (stream instanceof _base_stream.BaseStream && stream.dict instanceof _primitives.Dict) {
        const type = stream.dict.get("Type");
        const subtype = stream.dict.get("Subtype");
        if ((0, _primitives.isName)(type, "Metadata") && (0, _primitives.isName)(subtype, "XML")) {
          const data = (0, _util.stringToUTF8String)(stream.getString());
          if (data) {
            metadata = new _metadata_parser.MetadataParser(data).serializable;
          }
        }
      }
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.info)(`Skipping invalid Metadata: "${ex}".`);
    }
    return (0, _util.shadow)(this, "metadata", metadata);
  }
  get markInfo() {
    let markInfo = null;
    try {
      markInfo = this._readMarkInfo();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)("Unable to read mark info.");
    }
    return (0, _util.shadow)(this, "markInfo", markInfo);
  }
  _readMarkInfo() {
    const obj = this._catDict.get("MarkInfo");
    if (!(obj instanceof _primitives.Dict)) {
      return null;
    }
    const markInfo = {
      Marked: false,
      UserProperties: false,
      Suspects: false
    };
    for (const key in markInfo) {
      const value = obj.get(key);
      if (typeof value === "boolean") {
        markInfo[key] = value;
      }
    }
    return markInfo;
  }
  get structTreeRoot() {
    let structTree = null;
    try {
      structTree = this._readStructTreeRoot();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)("Unable read to structTreeRoot info.");
    }
    return (0, _util.shadow)(this, "structTreeRoot", structTree);
  }
  _readStructTreeRoot() {
    const obj = this._catDict.get("StructTreeRoot");
    if (!(obj instanceof _primitives.Dict)) {
      return null;
    }
    const root = new _struct_tree.StructTreeRoot(obj);
    root.init();
    return root;
  }
  get toplevelPagesDict() {
    const pagesObj = this._catDict.get("Pages");
    if (!(pagesObj instanceof _primitives.Dict)) {
      throw new _util.FormatError("Invalid top-level pages dictionary.");
    }
    return (0, _util.shadow)(this, "toplevelPagesDict", pagesObj);
  }
  get documentOutline() {
    let obj = null;
    try {
      obj = this._readDocumentOutline();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)("Unable to read document outline.");
    }
    return (0, _util.shadow)(this, "documentOutline", obj);
  }
  _readDocumentOutline() {
    let obj = this._catDict.get("Outlines");
    if (!(obj instanceof _primitives.Dict)) {
      return null;
    }
    obj = obj.getRaw("First");
    if (!(obj instanceof _primitives.Ref)) {
      return null;
    }
    const root = {
      items: []
    };
    const queue = [{
      obj,
      parent: root
    }];
    const processed = new _primitives.RefSet();
    processed.put(obj);
    const xref = this.xref,
      blackColor = new Uint8ClampedArray(3);
    while (queue.length > 0) {
      const i = queue.shift();
      const outlineDict = xref.fetchIfRef(i.obj);
      if (outlineDict === null) {
        continue;
      }
      if (!outlineDict.has("Title")) {
        throw new _util.FormatError("Invalid outline item encountered.");
      }
      const data = {
        url: null,
        dest: null,
        action: null
      };
      Catalog.parseDestDictionary({
        destDict: outlineDict,
        resultObj: data,
        docBaseUrl: this.pdfManager.docBaseUrl,
        docAttachments: this.attachments
      });
      const title = outlineDict.get("Title");
      const flags = outlineDict.get("F") || 0;
      const color = outlineDict.getArray("C");
      const count = outlineDict.get("Count");
      let rgbColor = blackColor;
      if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
        rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
      }
      const outlineItem = {
        action: data.action,
        attachment: data.attachment,
        dest: data.dest,
        url: data.url,
        unsafeUrl: data.unsafeUrl,
        newWindow: data.newWindow,
        setOCGState: data.setOCGState,
        title: (0, _util.stringToPDFString)(title),
        color: rgbColor,
        count: Number.isInteger(count) ? count : undefined,
        bold: !!(flags & 2),
        italic: !!(flags & 1),
        items: []
      };
      i.parent.items.push(outlineItem);
      obj = outlineDict.getRaw("First");
      if (obj instanceof _primitives.Ref && !processed.has(obj)) {
        queue.push({
          obj,
          parent: outlineItem
        });
        processed.put(obj);
      }
      obj = outlineDict.getRaw("Next");
      if (obj instanceof _primitives.Ref && !processed.has(obj)) {
        queue.push({
          obj,
          parent: i.parent
        });
        processed.put(obj);
      }
    }
    return root.items.length > 0 ? root.items : null;
  }
  get permissions() {
    let permissions = null;
    try {
      permissions = this._readPermissions();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)("Unable to read permissions.");
    }
    return (0, _util.shadow)(this, "permissions", permissions);
  }
  _readPermissions() {
    const encrypt = this.xref.trailer.get("Encrypt");
    if (!(encrypt instanceof _primitives.Dict)) {
      return null;
    }
    let flags = encrypt.get("P");
    if (typeof flags !== "number") {
      return null;
    }
    flags += 2 ** 32;
    const permissions = [];
    for (const key in _util.PermissionFlag) {
      const value = _util.PermissionFlag[key];
      if (flags & value) {
        permissions.push(value);
      }
    }
    return permissions;
  }
  get optionalContentConfig() {
    let config = null;
    try {
      const properties = this._catDict.get("OCProperties");
      if (!properties) {
        return (0, _util.shadow)(this, "optionalContentConfig", null);
      }
      const defaultConfig = properties.get("D");
      if (!defaultConfig) {
        return (0, _util.shadow)(this, "optionalContentConfig", null);
      }
      const groupsData = properties.get("OCGs");
      if (!Array.isArray(groupsData)) {
        return (0, _util.shadow)(this, "optionalContentConfig", null);
      }
      const groups = [];
      const groupRefs = [];
      for (const groupRef of groupsData) {
        if (!(groupRef instanceof _primitives.Ref)) {
          continue;
        }
        groupRefs.push(groupRef);
        const group = this.xref.fetchIfRef(groupRef);
        groups.push({
          id: groupRef.toString(),
          name: typeof group.get("Name") === "string" ? (0, _util.stringToPDFString)(group.get("Name")) : null,
          intent: typeof group.get("Intent") === "string" ? (0, _util.stringToPDFString)(group.get("Intent")) : null
        });
      }
      config = this._readOptionalContentConfig(defaultConfig, groupRefs);
      config.groups = groups;
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`Unable to read optional content config: ${ex}`);
    }
    return (0, _util.shadow)(this, "optionalContentConfig", config);
  }
  _readOptionalContentConfig(config, contentGroupRefs) {
    function parseOnOff(refs) {
      const onParsed = [];
      if (Array.isArray(refs)) {
        for (const value of refs) {
          if (!(value instanceof _primitives.Ref)) {
            continue;
          }
          if (contentGroupRefs.includes(value)) {
            onParsed.push(value.toString());
          }
        }
      }
      return onParsed;
    }
    function parseOrder(refs, nestedLevels = 0) {
      if (!Array.isArray(refs)) {
        return null;
      }
      const order = [];
      for (const value of refs) {
        if (value instanceof _primitives.Ref && contentGroupRefs.includes(value)) {
          parsedOrderRefs.put(value);
          order.push(value.toString());
          continue;
        }
        const nestedOrder = parseNestedOrder(value, nestedLevels);
        if (nestedOrder) {
          order.push(nestedOrder);
        }
      }
      if (nestedLevels > 0) {
        return order;
      }
      const hiddenGroups = [];
      for (const groupRef of contentGroupRefs) {
        if (parsedOrderRefs.has(groupRef)) {
          continue;
        }
        hiddenGroups.push(groupRef.toString());
      }
      if (hiddenGroups.length) {
        order.push({
          name: null,
          order: hiddenGroups
        });
      }
      return order;
    }
    function parseNestedOrder(ref, nestedLevels) {
      if (++nestedLevels > MAX_NESTED_LEVELS) {
        (0, _util.warn)("parseNestedOrder - reached MAX_NESTED_LEVELS.");
        return null;
      }
      const value = xref.fetchIfRef(ref);
      if (!Array.isArray(value)) {
        return null;
      }
      const nestedName = xref.fetchIfRef(value[0]);
      if (typeof nestedName !== "string") {
        return null;
      }
      const nestedOrder = parseOrder(value.slice(1), nestedLevels);
      if (!nestedOrder || !nestedOrder.length) {
        return null;
      }
      return {
        name: (0, _util.stringToPDFString)(nestedName),
        order: nestedOrder
      };
    }
    const xref = this.xref,
      parsedOrderRefs = new _primitives.RefSet(),
      MAX_NESTED_LEVELS = 10;
    return {
      name: typeof config.get("Name") === "string" ? (0, _util.stringToPDFString)(config.get("Name")) : null,
      creator: typeof config.get("Creator") === "string" ? (0, _util.stringToPDFString)(config.get("Creator")) : null,
      baseState: config.get("BaseState") instanceof _primitives.Name ? config.get("BaseState").name : null,
      on: parseOnOff(config.get("ON")),
      off: parseOnOff(config.get("OFF")),
      order: parseOrder(config.get("Order")),
      groups: null
    };
  }
  setActualNumPages(num = null) {
    this._actualNumPages = num;
  }
  get hasActualNumPages() {
    return this._actualNumPages !== null;
  }
  get _pagesCount() {
    const obj = this.toplevelPagesDict.get("Count");
    if (!Number.isInteger(obj)) {
      throw new _util.FormatError("Page count in top-level pages dictionary is not an integer.");
    }
    return (0, _util.shadow)(this, "_pagesCount", obj);
  }
  get numPages() {
    return this.hasActualNumPages ? this._actualNumPages : this._pagesCount;
  }
  get destinations() {
    const obj = this._readDests(),
      dests = Object.create(null);
    if (obj instanceof _name_number_tree.NameTree) {
      for (const [key, value] of obj.getAll()) {
        const dest = fetchDestination(value);
        if (dest) {
          dests[(0, _util.stringToPDFString)(key)] = dest;
        }
      }
    } else if (obj instanceof _primitives.Dict) {
      obj.forEach(function (key, value) {
        const dest = fetchDestination(value);
        if (dest) {
          dests[key] = dest;
        }
      });
    }
    return (0, _util.shadow)(this, "destinations", dests);
  }
  getDestination(id) {
    const obj = this._readDests();
    if (obj instanceof _name_number_tree.NameTree) {
      const dest = fetchDestination(obj.get(id));
      if (dest) {
        return dest;
      }
      const allDest = this.destinations[id];
      if (allDest) {
        (0, _util.warn)(`Found "${id}" at an incorrect position in the NameTree.`);
        return allDest;
      }
    } else if (obj instanceof _primitives.Dict) {
      const dest = fetchDestination(obj.get(id));
      if (dest) {
        return dest;
      }
    }
    return null;
  }
  _readDests() {
    const obj = this._catDict.get("Names");
    if (obj && obj.has("Dests")) {
      return new _name_number_tree.NameTree(obj.getRaw("Dests"), this.xref);
    } else if (this._catDict.has("Dests")) {
      return this._catDict.get("Dests");
    }
    return undefined;
  }
  get pageLabels() {
    let obj = null;
    try {
      obj = this._readPageLabels();
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)("Unable to read page labels.");
    }
    return (0, _util.shadow)(this, "pageLabels", obj);
  }
  _readPageLabels() {
    const obj = this._catDict.getRaw("PageLabels");
    if (!obj) {
      return null;
    }
    const pageLabels = new Array(this.numPages);
    let style = null,
      prefix = "";
    const numberTree = new _name_number_tree.NumberTree(obj, this.xref);
    const nums = numberTree.getAll();
    let currentLabel = "",
      currentIndex = 1;
    for (let i = 0, ii = this.numPages; i < ii; i++) {
      const labelDict = nums.get(i);
      if (labelDict !== undefined) {
        if (!(labelDict instanceof _primitives.Dict)) {
          throw new _util.FormatError("PageLabel is not a dictionary.");
        }
        if (labelDict.has("Type") && !(0, _primitives.isName)(labelDict.get("Type"), "PageLabel")) {
          throw new _util.FormatError("Invalid type in PageLabel dictionary.");
        }
        if (labelDict.has("S")) {
          const s = labelDict.get("S");
          if (!(s instanceof _primitives.Name)) {
            throw new _util.FormatError("Invalid style in PageLabel dictionary.");
          }
          style = s.name;
        } else {
          style = null;
        }
        if (labelDict.has("P")) {
          const p = labelDict.get("P");
          if (typeof p !== "string") {
            throw new _util.FormatError("Invalid prefix in PageLabel dictionary.");
          }
          prefix = (0, _util.stringToPDFString)(p);
        } else {
          prefix = "";
        }
        if (labelDict.has("St")) {
          const st = labelDict.get("St");
          if (!(Number.isInteger(st) && st >= 1)) {
            throw new _util.FormatError("Invalid start in PageLabel dictionary.");
          }
          currentIndex = st;
        } else {
          currentIndex = 1;
        }
      }
      switch (style) {
        case "D":
          currentLabel = currentIndex;
          break;
        case "R":
        case "r":
          currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === "r");
          break;
        case "A":
        case "a":
          const LIMIT = 26;
          const A_UPPER_CASE = 0x41,
            A_LOWER_CASE = 0x61;
          const baseCharCode = style === "a" ? A_LOWER_CASE : A_UPPER_CASE;
          const letterIndex = currentIndex - 1;
          const character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
          currentLabel = character.repeat(Math.floor(letterIndex / LIMIT) + 1);
          break;
        default:
          if (style) {
            throw new _util.FormatError(`Invalid style "${style}" in PageLabel dictionary.`);
          }
          currentLabel = "";
      }
      pageLabels[i] = prefix + currentLabel;
      currentIndex++;
    }
    return pageLabels;
  }
  get pageLayout() {
    const obj = this._catDict.get("PageLayout");
    let pageLayout = "";
    if (obj instanceof _primitives.Name) {
      switch (obj.name) {
        case "SinglePage":
        case "OneColumn":
        case "TwoColumnLeft":
        case "TwoColumnRight":
        case "TwoPageLeft":
        case "TwoPageRight":
          pageLayout = obj.name;
      }
    }
    return (0, _util.shadow)(this, "pageLayout", pageLayout);
  }
  get pageMode() {
    const obj = this._catDict.get("PageMode");
    let pageMode = "UseNone";
    if (obj instanceof _primitives.Name) {
      switch (obj.name) {
        case "UseNone":
        case "UseOutlines":
        case "UseThumbs":
        case "FullScreen":
        case "UseOC":
        case "UseAttachments":
          pageMode = obj.name;
      }
    }
    return (0, _util.shadow)(this, "pageMode", pageMode);
  }
  get viewerPreferences() {
    const obj = this._catDict.get("ViewerPreferences");
    if (!(obj instanceof _primitives.Dict)) {
      return (0, _util.shadow)(this, "viewerPreferences", null);
    }
    let prefs = null;
    for (const key of obj.getKeys()) {
      const value = obj.get(key);
      let prefValue;
      switch (key) {
        case "HideToolbar":
        case "HideMenubar":
        case "HideWindowUI":
        case "FitWindow":
        case "CenterWindow":
        case "DisplayDocTitle":
        case "PickTrayByPDFSize":
          if (typeof value === "boolean") {
            prefValue = value;
          }
          break;
        case "NonFullScreenPageMode":
          if (value instanceof _primitives.Name) {
            switch (value.name) {
              case "UseNone":
              case "UseOutlines":
              case "UseThumbs":
              case "UseOC":
                prefValue = value.name;
                break;
              default:
                prefValue = "UseNone";
            }
          }
          break;
        case "Direction":
          if (value instanceof _primitives.Name) {
            switch (value.name) {
              case "L2R":
              case "R2L":
                prefValue = value.name;
                break;
              default:
                prefValue = "L2R";
            }
          }
          break;
        case "ViewArea":
        case "ViewClip":
        case "PrintArea":
        case "PrintClip":
          if (value instanceof _primitives.Name) {
            switch (value.name) {
              case "MediaBox":
              case "CropBox":
              case "BleedBox":
              case "TrimBox":
              case "ArtBox":
                prefValue = value.name;
                break;
              default:
                prefValue = "CropBox";
            }
          }
          break;
        case "PrintScaling":
          if (value instanceof _primitives.Name) {
            switch (value.name) {
              case "None":
              case "AppDefault":
                prefValue = value.name;
                break;
              default:
                prefValue = "AppDefault";
            }
          }
          break;
        case "Duplex":
          if (value instanceof _primitives.Name) {
            switch (value.name) {
              case "Simplex":
              case "DuplexFlipShortEdge":
              case "DuplexFlipLongEdge":
                prefValue = value.name;
                break;
              default:
                prefValue = "None";
            }
          }
          break;
        case "PrintPageRange":
          if (Array.isArray(value) && value.length % 2 === 0) {
            const isValid = value.every((page, i, arr) => {
              return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= this.numPages;
            });
            if (isValid) {
              prefValue = value;
            }
          }
          break;
        case "NumCopies":
          if (Number.isInteger(value) && value > 0) {
            prefValue = value;
          }
          break;
        default:
          (0, _util.warn)(`Ignoring non-standard key in ViewerPreferences: ${key}.`);
          continue;
      }
      if (prefValue === undefined) {
        (0, _util.warn)(`Bad value, for key "${key}", in ViewerPreferences: ${value}.`);
        continue;
      }
      if (!prefs) {
        prefs = Object.create(null);
      }
      prefs[key] = prefValue;
    }
    return (0, _util.shadow)(this, "viewerPreferences", prefs);
  }
  get openAction() {
    const obj = this._catDict.get("OpenAction");
    const openAction = Object.create(null);
    if (obj instanceof _primitives.Dict) {
      const destDict = new _primitives.Dict(this.xref);
      destDict.set("A", obj);
      const resultObj = {
        url: null,
        dest: null,
        action: null
      };
      Catalog.parseDestDictionary({
        destDict,
        resultObj
      });
      if (Array.isArray(resultObj.dest)) {
        openAction.dest = resultObj.dest;
      } else if (resultObj.action) {
        openAction.action = resultObj.action;
      }
    } else if (Array.isArray(obj)) {
      openAction.dest = obj;
    }
    return (0, _util.shadow)(this, "openAction", (0, _util.objectSize)(openAction) > 0 ? openAction : null);
  }
  get attachments() {
    const obj = this._catDict.get("Names");
    let attachments = null;
    if (obj instanceof _primitives.Dict && obj.has("EmbeddedFiles")) {
      const nameTree = new _name_number_tree.NameTree(obj.getRaw("EmbeddedFiles"), this.xref);
      for (const [key, value] of nameTree.getAll()) {
        const fs = new _file_spec.FileSpec(value, this.xref);
        if (!attachments) {
          attachments = Object.create(null);
        }
        attachments[(0, _util.stringToPDFString)(key)] = fs.serializable;
      }
    }
    return (0, _util.shadow)(this, "attachments", attachments);
  }
  get xfaImages() {
    const obj = this._catDict.get("Names");
    let xfaImages = null;
    if (obj instanceof _primitives.Dict && obj.has("XFAImages")) {
      const nameTree = new _name_number_tree.NameTree(obj.getRaw("XFAImages"), this.xref);
      for (const [key, value] of nameTree.getAll()) {
        if (!xfaImages) {
          xfaImages = new _primitives.Dict(this.xref);
        }
        xfaImages.set((0, _util.stringToPDFString)(key), value);
      }
    }
    return (0, _util.shadow)(this, "xfaImages", xfaImages);
  }
  _collectJavaScript() {
    const obj = this._catDict.get("Names");
    let javaScript = null;
    function appendIfJavaScriptDict(name, jsDict) {
      if (!(jsDict instanceof _primitives.Dict)) {
        return;
      }
      if (!(0, _primitives.isName)(jsDict.get("S"), "JavaScript")) {
        return;
      }
      let js = jsDict.get("JS");
      if (js instanceof _base_stream.BaseStream) {
        js = js.getString();
      } else if (typeof js !== "string") {
        return;
      }
      if (javaScript === null) {
        javaScript = new Map();
      }
      js = (0, _util.stringToPDFString)(js).replace(/\u0000/g, "");
      javaScript.set(name, js);
    }
    if (obj instanceof _primitives.Dict && obj.has("JavaScript")) {
      const nameTree = new _name_number_tree.NameTree(obj.getRaw("JavaScript"), this.xref);
      for (const [key, value] of nameTree.getAll()) {
        appendIfJavaScriptDict((0, _util.stringToPDFString)(key), value);
      }
    }
    const openAction = this._catDict.get("OpenAction");
    if (openAction) {
      appendIfJavaScriptDict("OpenAction", openAction);
    }
    return javaScript;
  }
  get javaScript() {
    const javaScript = this._collectJavaScript();
    return (0, _util.shadow)(this, "javaScript", javaScript ? [...javaScript.values()] : null);
  }
  get jsActions() {
    const javaScript = this._collectJavaScript();
    let actions = (0, _core_utils.collectActions)(this.xref, this._catDict, _util.DocumentActionEventType);
    if (javaScript) {
      if (!actions) {
        actions = Object.create(null);
      }
      for (const [key, val] of javaScript) {
        if (key in actions) {
          actions[key].push(val);
        } else {
          actions[key] = [val];
        }
      }
    }
    return (0, _util.shadow)(this, "jsActions", actions);
  }
  async fontFallback(id, handler) {
    const translatedFonts = await Promise.all(this.fontCache);
    for (const translatedFont of translatedFonts) {
      if (translatedFont.loadedName === id) {
        translatedFont.fallback(handler);
        return;
      }
    }
  }
  async cleanup(manuallyTriggered = false) {
    (0, _cleanup_helper.clearGlobalCaches)();
    this.globalImageCache.clear(manuallyTriggered);
    this.pageKidsCountCache.clear();
    this.pageIndexCache.clear();
    this.nonBlendModesSet.clear();
    const translatedFonts = await Promise.all(this.fontCache);
    for (const {
      dict
    } of translatedFonts) {
      delete dict.cacheKey;
    }
    this.fontCache.clear();
    this.builtInCMapCache.clear();
    this.standardFontDataCache.clear();
  }
  async getPageDict(pageIndex) {
    const nodesToVisit = [this.toplevelPagesDict];
    const visitedNodes = new _primitives.RefSet();
    const pagesRef = this._catDict.getRaw("Pages");
    if (pagesRef instanceof _primitives.Ref) {
      visitedNodes.put(pagesRef);
    }
    const xref = this.xref,
      pageKidsCountCache = this.pageKidsCountCache,
      pageIndexCache = this.pageIndexCache;
    let currentPageIndex = 0;
    while (nodesToVisit.length) {
      const currentNode = nodesToVisit.pop();
      if (currentNode instanceof _primitives.Ref) {
        const count = pageKidsCountCache.get(currentNode);
        if (count >= 0 && currentPageIndex + count <= pageIndex) {
          currentPageIndex += count;
          continue;
        }
        if (visitedNodes.has(currentNode)) {
          throw new _util.FormatError("Pages tree contains circular reference.");
        }
        visitedNodes.put(currentNode);
        const obj = await xref.fetchAsync(currentNode);
        if (obj instanceof _primitives.Dict) {
          let type = obj.getRaw("Type");
          if (type instanceof _primitives.Ref) {
            type = await xref.fetchAsync(type);
          }
          if ((0, _primitives.isName)(type, "Page") || !obj.has("Kids")) {
            if (!pageKidsCountCache.has(currentNode)) {
              pageKidsCountCache.put(currentNode, 1);
            }
            if (!pageIndexCache.has(currentNode)) {
              pageIndexCache.put(currentNode, currentPageIndex);
            }
            if (currentPageIndex === pageIndex) {
              return [obj, currentNode];
            }
            currentPageIndex++;
            continue;
          }
        }
        nodesToVisit.push(obj);
        continue;
      }
      if (!(currentNode instanceof _primitives.Dict)) {
        throw new _util.FormatError("Page dictionary kid reference points to wrong type of object.");
      }
      const {
        objId
      } = currentNode;
      let count = currentNode.getRaw("Count");
      if (count instanceof _primitives.Ref) {
        count = await xref.fetchAsync(count);
      }
      if (Number.isInteger(count) && count >= 0) {
        if (objId && !pageKidsCountCache.has(objId)) {
          pageKidsCountCache.put(objId, count);
        }
        if (currentPageIndex + count <= pageIndex) {
          currentPageIndex += count;
          continue;
        }
      }
      let kids = currentNode.getRaw("Kids");
      if (kids instanceof _primitives.Ref) {
        kids = await xref.fetchAsync(kids);
      }
      if (!Array.isArray(kids)) {
        let type = currentNode.getRaw("Type");
        if (type instanceof _primitives.Ref) {
          type = await xref.fetchAsync(type);
        }
        if ((0, _primitives.isName)(type, "Page") || !currentNode.has("Kids")) {
          if (currentPageIndex === pageIndex) {
            return [currentNode, null];
          }
          currentPageIndex++;
          continue;
        }
        throw new _util.FormatError("Page dictionary kids object is not an array.");
      }
      for (let last = kids.length - 1; last >= 0; last--) {
        nodesToVisit.push(kids[last]);
      }
    }
    throw new Error(`Page index ${pageIndex} not found.`);
  }
  async getAllPageDicts(recoveryMode = false) {
    const {
      ignoreErrors
    } = this.pdfManager.evaluatorOptions;
    const queue = [{
      currentNode: this.toplevelPagesDict,
      posInKids: 0
    }];
    const visitedNodes = new _primitives.RefSet();
    const pagesRef = this._catDict.getRaw("Pages");
    if (pagesRef instanceof _primitives.Ref) {
      visitedNodes.put(pagesRef);
    }
    const map = new Map(),
      xref = this.xref,
      pageIndexCache = this.pageIndexCache;
    let pageIndex = 0;
    function addPageDict(pageDict, pageRef) {
      if (pageRef && !pageIndexCache.has(pageRef)) {
        pageIndexCache.put(pageRef, pageIndex);
      }
      map.set(pageIndex++, [pageDict, pageRef]);
    }
    function addPageError(error) {
      if (error instanceof _core_utils.XRefEntryException && !recoveryMode) {
        throw error;
      }
      if (recoveryMode && ignoreErrors && pageIndex === 0) {
        (0, _util.warn)(`getAllPageDicts - Skipping invalid first page: "${error}".`);
        error = _primitives.Dict.empty;
      }
      map.set(pageIndex++, [error, null]);
    }
    while (queue.length > 0) {
      const queueItem = queue.at(-1);
      const {
        currentNode,
        posInKids
      } = queueItem;
      let kids = currentNode.getRaw("Kids");
      if (kids instanceof _primitives.Ref) {
        try {
          kids = await xref.fetchAsync(kids);
        } catch (ex) {
          addPageError(ex);
          break;
        }
      }
      if (!Array.isArray(kids)) {
        addPageError(new _util.FormatError("Page dictionary kids object is not an array."));
        break;
      }
      if (posInKids >= kids.length) {
        queue.pop();
        continue;
      }
      const kidObj = kids[posInKids];
      let obj;
      if (kidObj instanceof _primitives.Ref) {
        if (visitedNodes.has(kidObj)) {
          addPageError(new _util.FormatError("Pages tree contains circular reference."));
          break;
        }
        visitedNodes.put(kidObj);
        try {
          obj = await xref.fetchAsync(kidObj);
        } catch (ex) {
          addPageError(ex);
          break;
        }
      } else {
        obj = kidObj;
      }
      if (!(obj instanceof _primitives.Dict)) {
        addPageError(new _util.FormatError("Page dictionary kid reference points to wrong type of object."));
        break;
      }
      let type = obj.getRaw("Type");
      if (type instanceof _primitives.Ref) {
        try {
          type = await xref.fetchAsync(type);
        } catch (ex) {
          addPageError(ex);
          break;
        }
      }
      if ((0, _primitives.isName)(type, "Page") || !obj.has("Kids")) {
        addPageDict(obj, kidObj instanceof _primitives.Ref ? kidObj : null);
      } else {
        queue.push({
          currentNode: obj,
          posInKids: 0
        });
      }
      queueItem.posInKids++;
    }
    return map;
  }
  getPageIndex(pageRef) {
    const cachedPageIndex = this.pageIndexCache.get(pageRef);
    if (cachedPageIndex !== undefined) {
      return Promise.resolve(cachedPageIndex);
    }
    const xref = this.xref;
    function pagesBeforeRef(kidRef) {
      let total = 0,
        parentRef;
      return xref.fetchAsync(kidRef).then(function (node) {
        if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, "Page") && !(node instanceof _primitives.Dict && !node.has("Type") && node.has("Contents"))) {
          throw new _util.FormatError("The reference does not point to a /Page dictionary.");
        }
        if (!node) {
          return null;
        }
        if (!(node instanceof _primitives.Dict)) {
          throw new _util.FormatError("Node must be a dictionary.");
        }
        parentRef = node.getRaw("Parent");
        return node.getAsync("Parent");
      }).then(function (parent) {
        if (!parent) {
          return null;
        }
        if (!(parent instanceof _primitives.Dict)) {
          throw new _util.FormatError("Parent must be a dictionary.");
        }
        return parent.getAsync("Kids");
      }).then(function (kids) {
        if (!kids) {
          return null;
        }
        const kidPromises = [];
        let found = false;
        for (const kid of kids) {
          if (!(kid instanceof _primitives.Ref)) {
            throw new _util.FormatError("Kid must be a reference.");
          }
          if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
            found = true;
            break;
          }
          kidPromises.push(xref.fetchAsync(kid).then(function (obj) {
            if (!(obj instanceof _primitives.Dict)) {
              throw new _util.FormatError("Kid node must be a dictionary.");
            }
            if (obj.has("Count")) {
              total += obj.get("Count");
            } else {
              total++;
            }
          }));
        }
        if (!found) {
          throw new _util.FormatError("Kid reference not found in parent's kids.");
        }
        return Promise.all(kidPromises).then(function () {
          return [total, parentRef];
        });
      });
    }
    let total = 0;
    const next = ref => pagesBeforeRef(ref).then(args => {
      if (!args) {
        this.pageIndexCache.put(pageRef, total);
        return total;
      }
      const [count, parentRef] = args;
      total += count;
      return next(parentRef);
    });
    return next(pageRef);
  }
  get baseUrl() {
    const uri = this._catDict.get("URI");
    if (uri instanceof _primitives.Dict) {
      const base = uri.get("Base");
      if (typeof base === "string") {
        const absoluteUrl = (0, _util.createValidAbsoluteUrl)(base, null, {
          tryConvertEncoding: true
        });
        if (absoluteUrl) {
          return (0, _util.shadow)(this, "baseUrl", absoluteUrl.href);
        }
      }
    }
    return (0, _util.shadow)(this, "baseUrl", null);
  }
  static parseDestDictionary(params) {
    const destDict = params.destDict;
    if (!(destDict instanceof _primitives.Dict)) {
      (0, _util.warn)("parseDestDictionary: `destDict` must be a dictionary.");
      return;
    }
    const resultObj = params.resultObj;
    if (typeof resultObj !== "object") {
      (0, _util.warn)("parseDestDictionary: `resultObj` must be an object.");
      return;
    }
    const docBaseUrl = params.docBaseUrl || null;
    const docAttachments = params.docAttachments || null;
    let action = destDict.get("A"),
      url,
      dest;
    if (!(action instanceof _primitives.Dict)) {
      if (destDict.has("Dest")) {
        action = destDict.get("Dest");
      } else {
        action = destDict.get("AA");
        if (action instanceof _primitives.Dict) {
          if (action.has("D")) {
            action = action.get("D");
          } else if (action.has("U")) {
            action = action.get("U");
          }
        }
      }
    }
    if (action instanceof _primitives.Dict) {
      const actionType = action.get("S");
      if (!(actionType instanceof _primitives.Name)) {
        (0, _util.warn)("parseDestDictionary: Invalid type in Action dictionary.");
        return;
      }
      const actionName = actionType.name;
      switch (actionName) {
        case "ResetForm":
          const flags = action.get("Flags");
          const include = ((typeof flags === "number" ? flags : 0) & 1) === 0;
          const fields = [];
          const refs = [];
          for (const obj of action.get("Fields") || []) {
            if (obj instanceof _primitives.Ref) {
              refs.push(obj.toString());
            } else if (typeof obj === "string") {
              fields.push((0, _util.stringToPDFString)(obj));
            }
          }
          resultObj.resetForm = {
            fields,
            refs,
            include
          };
          break;
        case "URI":
          url = action.get("URI");
          if (url instanceof _primitives.Name) {
            url = "/" + url.name;
          }
          break;
        case "GoTo":
          dest = action.get("D");
          break;
        case "Launch":
        case "GoToR":
          const urlDict = action.get("F");
          if (urlDict instanceof _primitives.Dict) {
            url = urlDict.get("F") || null;
          } else if (typeof urlDict === "string") {
            url = urlDict;
          }
          let remoteDest = action.get("D");
          if (remoteDest) {
            if (remoteDest instanceof _primitives.Name) {
              remoteDest = remoteDest.name;
            }
            if (typeof url === "string") {
              const baseUrl = url.split("#")[0];
              if (typeof remoteDest === "string") {
                url = baseUrl + "#" + remoteDest;
              } else if (Array.isArray(remoteDest)) {
                url = baseUrl + "#" + JSON.stringify(remoteDest);
              }
            }
          }
          const newWindow = action.get("NewWindow");
          if (typeof newWindow === "boolean") {
            resultObj.newWindow = newWindow;
          }
          break;
        case "GoToE":
          const target = action.get("T");
          let attachment;
          if (docAttachments && target instanceof _primitives.Dict) {
            const relationship = target.get("R");
            const name = target.get("N");
            if ((0, _primitives.isName)(relationship, "C") && typeof name === "string") {
              attachment = docAttachments[(0, _util.stringToPDFString)(name)];
            }
          }
          if (attachment) {
            resultObj.attachment = attachment;
          } else {
            (0, _util.warn)(`parseDestDictionary - unimplemented "GoToE" action.`);
          }
          break;
        case "Named":
          const namedAction = action.get("N");
          if (namedAction instanceof _primitives.Name) {
            resultObj.action = namedAction.name;
          }
          break;
        case "SetOCGState":
          const state = action.get("State");
          const preserveRB = action.get("PreserveRB");
          if (!Array.isArray(state) || state.length === 0) {
            break;
          }
          const stateArr = [];
          for (const elem of state) {
            if (elem instanceof _primitives.Name) {
              switch (elem.name) {
                case "ON":
                case "OFF":
                case "Toggle":
                  stateArr.push(elem.name);
                  break;
              }
            } else if (elem instanceof _primitives.Ref) {
              stateArr.push(elem.toString());
            }
          }
          if (stateArr.length !== state.length) {
            break;
          }
          resultObj.setOCGState = {
            state: stateArr,
            preserveRB: typeof preserveRB === "boolean" ? preserveRB : true
          };
          break;
        case "JavaScript":
          const jsAction = action.get("JS");
          let js;
          if (jsAction instanceof _base_stream.BaseStream) {
            js = jsAction.getString();
          } else if (typeof jsAction === "string") {
            js = jsAction;
          }
          const jsURL = js && (0, _core_utils.recoverJsURL)((0, _util.stringToPDFString)(js));
          if (jsURL) {
            url = jsURL.url;
            resultObj.newWindow = jsURL.newWindow;
            break;
          }
        default:
          if (actionName === "JavaScript" || actionName === "SubmitForm") {
            break;
          }
          (0, _util.warn)(`parseDestDictionary - unsupported action: "${actionName}".`);
          break;
      }
    } else if (destDict.has("Dest")) {
      dest = destDict.get("Dest");
    }
    if (typeof url === "string") {
      const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl, {
        addDefaultProtocol: true,
        tryConvertEncoding: true
      });
      if (absoluteUrl) {
        resultObj.url = absoluteUrl.href;
      }
      resultObj.unsafeUrl = url;
    }
    if (dest) {
      if (dest instanceof _primitives.Name) {
        dest = dest.name;
      }
      if (typeof dest === "string") {
        resultObj.dest = (0, _util.stringToPDFString)(dest);
      } else if (Array.isArray(dest)) {
        resultObj.dest = dest;
      }
    }
  }
}
exports.Catalog = Catalog;

/***/ }),
/* 68 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.NumberTree = exports.NameTree = void 0;
var _primitives = __w_pdfjs_require__(3);
var _util = __w_pdfjs_require__(2);
class NameOrNumberTree {
  constructor(root, xref, type) {
    if (this.constructor === NameOrNumberTree) {
      (0, _util.unreachable)("Cannot initialize NameOrNumberTree.");
    }
    this.root = root;
    this.xref = xref;
    this._type = type;
  }
  getAll() {
    const map = new Map();
    if (!this.root) {
      return map;
    }
    const xref = this.xref;
    const processed = new _primitives.RefSet();
    processed.put(this.root);
    const queue = [this.root];
    while (queue.length > 0) {
      const obj = xref.fetchIfRef(queue.shift());
      if (!(obj instanceof _primitives.Dict)) {
        continue;
      }
      if (obj.has("Kids")) {
        const kids = obj.get("Kids");
        if (!Array.isArray(kids)) {
          continue;
        }
        for (const kid of kids) {
          if (processed.has(kid)) {
            throw new _util.FormatError(`Duplicate entry in "${this._type}" tree.`);
          }
          queue.push(kid);
          processed.put(kid);
        }
        continue;
      }
      const entries = obj.get(this._type);
      if (!Array.isArray(entries)) {
        continue;
      }
      for (let i = 0, ii = entries.length; i < ii; i += 2) {
        map.set(xref.fetchIfRef(entries[i]), xref.fetchIfRef(entries[i + 1]));
      }
    }
    return map;
  }
  get(key) {
    if (!this.root) {
      return null;
    }
    const xref = this.xref;
    let kidsOrEntries = xref.fetchIfRef(this.root);
    let loopCount = 0;
    const MAX_LEVELS = 10;
    while (kidsOrEntries.has("Kids")) {
      if (++loopCount > MAX_LEVELS) {
        (0, _util.warn)(`Search depth limit reached for "${this._type}" tree.`);
        return null;
      }
      const kids = kidsOrEntries.get("Kids");
      if (!Array.isArray(kids)) {
        return null;
      }
      let l = 0,
        r = kids.length - 1;
      while (l <= r) {
        const m = l + r >> 1;
        const kid = xref.fetchIfRef(kids[m]);
        const limits = kid.get("Limits");
        if (key < xref.fetchIfRef(limits[0])) {
          r = m - 1;
        } else if (key > xref.fetchIfRef(limits[1])) {
          l = m + 1;
        } else {
          kidsOrEntries = kid;
          break;
        }
      }
      if (l > r) {
        return null;
      }
    }
    const entries = kidsOrEntries.get(this._type);
    if (Array.isArray(entries)) {
      let l = 0,
        r = entries.length - 2;
      while (l <= r) {
        const tmp = l + r >> 1,
          m = tmp + (tmp & 1);
        const currentKey = xref.fetchIfRef(entries[m]);
        if (key < currentKey) {
          r = m - 2;
        } else if (key > currentKey) {
          l = m + 2;
        } else {
          return xref.fetchIfRef(entries[m + 1]);
        }
      }
    }
    return null;
  }
}
class NameTree extends NameOrNumberTree {
  constructor(root, xref) {
    super(root, xref, "Names");
  }
}
exports.NameTree = NameTree;
class NumberTree extends NameOrNumberTree {
  constructor(root, xref) {
    super(root, xref, "Nums");
  }
}
exports.NumberTree = NumberTree;

/***/ }),
/* 69 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.clearGlobalCaches = clearGlobalCaches;
var _primitives = __w_pdfjs_require__(3);
var _unicode = __w_pdfjs_require__(38);
function clearGlobalCaches() {
  (0, _primitives.clearPrimitiveCaches)();
  (0, _unicode.clearUnicodeCaches)();
}

/***/ }),
/* 70 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FileSpec = void 0;
var _util = __w_pdfjs_require__(2);
var _base_stream = __w_pdfjs_require__(5);
var _primitives = __w_pdfjs_require__(3);
function pickPlatformItem(dict) {
  if (dict.has("UF")) {
    return dict.get("UF");
  } else if (dict.has("F")) {
    return dict.get("F");
  } else if (dict.has("Unix")) {
    return dict.get("Unix");
  } else if (dict.has("Mac")) {
    return dict.get("Mac");
  } else if (dict.has("DOS")) {
    return dict.get("DOS");
  }
  return null;
}
class FileSpec {
  constructor(root, xref) {
    if (!(root instanceof _primitives.Dict)) {
      return;
    }
    this.xref = xref;
    this.root = root;
    if (root.has("FS")) {
      this.fs = root.get("FS");
    }
    this.description = root.has("Desc") ? (0, _util.stringToPDFString)(root.get("Desc")) : "";
    if (root.has("RF")) {
      (0, _util.warn)("Related file specifications are not supported");
    }
    this.contentAvailable = true;
    if (!root.has("EF")) {
      this.contentAvailable = false;
      (0, _util.warn)("Non-embedded file specifications are not supported");
    }
  }
  get filename() {
    if (!this._filename && this.root) {
      const filename = pickPlatformItem(this.root) || "unnamed";
      this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, "\\").replace(/\\\//g, "/").replace(/\\/g, "/");
    }
    return this._filename;
  }
  get content() {
    if (!this.contentAvailable) {
      return null;
    }
    if (!this.contentRef && this.root) {
      this.contentRef = pickPlatformItem(this.root.get("EF"));
    }
    let content = null;
    if (this.contentRef) {
      const fileObj = this.xref.fetchIfRef(this.contentRef);
      if (fileObj instanceof _base_stream.BaseStream) {
        content = fileObj.getBytes();
      } else {
        (0, _util.warn)("Embedded file specification points to non-existing/invalid content");
      }
    } else {
      (0, _util.warn)("Embedded file specification does not have a content");
    }
    return content;
  }
  get serializable() {
    return {
      filename: this.filename,
      content: this.content
    };
  }
}
exports.FileSpec = FileSpec;

/***/ }),
/* 71 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MetadataParser = void 0;
var _xml_parser = __w_pdfjs_require__(64);
class MetadataParser {
  constructor(data) {
    data = this._repair(data);
    const parser = new _xml_parser.SimpleXMLParser({
      lowerCaseName: true
    });
    const xmlDocument = parser.parseFromString(data);
    this._metadataMap = new Map();
    this._data = data;
    if (xmlDocument) {
      this._parse(xmlDocument);
    }
  }
  _repair(data) {
    return data.replace(/^[^<]+/, "").replace(/>\\376\\377([^<]+)/g, function (all, codes) {
      const bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
        return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
      }).replace(/&(amp|apos|gt|lt|quot);/g, function (str, name) {
        switch (name) {
          case "amp":
            return "&";
          case "apos":
            return "'";
          case "gt":
            return ">";
          case "lt":
            return "<";
          case "quot":
            return '"';
        }
        throw new Error(`_repair: ${name} isn't defined.`);
      });
      const charBuf = [">"];
      for (let i = 0, ii = bytes.length; i < ii; i += 2) {
        const code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
        if (code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38) {
          charBuf.push(String.fromCharCode(code));
        } else {
          charBuf.push("&#x" + (0x10000 + code).toString(16).substring(1) + ";");
        }
      }
      return charBuf.join("");
    });
  }
  _getSequence(entry) {
    const name = entry.nodeName;
    if (name !== "rdf:bag" && name !== "rdf:seq" && name !== "rdf:alt") {
      return null;
    }
    return entry.childNodes.filter(node => node.nodeName === "rdf:li");
  }
  _parseArray(entry) {
    if (!entry.hasChildNodes()) {
      return;
    }
    const [seqNode] = entry.childNodes;
    const sequence = this._getSequence(seqNode) || [];
    this._metadataMap.set(entry.nodeName, sequence.map(node => node.textContent.trim()));
  }
  _parse(xmlDocument) {
    let rdf = xmlDocument.documentElement;
    if (rdf.nodeName !== "rdf:rdf") {
      rdf = rdf.firstChild;
      while (rdf && rdf.nodeName !== "rdf:rdf") {
        rdf = rdf.nextSibling;
      }
    }
    if (!rdf || rdf.nodeName !== "rdf:rdf" || !rdf.hasChildNodes()) {
      return;
    }
    for (const desc of rdf.childNodes) {
      if (desc.nodeName !== "rdf:description") {
        continue;
      }
      for (const entry of desc.childNodes) {
        const name = entry.nodeName;
        switch (name) {
          case "#text":
            continue;
          case "dc:creator":
          case "dc:subject":
            this._parseArray(entry);
            continue;
        }
        this._metadataMap.set(name, entry.textContent.trim());
      }
    }
  }
  get serializable() {
    return {
      parsedData: this._metadataMap,
      rawData: this._data
    };
  }
}
exports.MetadataParser = MetadataParser;

/***/ }),
/* 72 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.StructTreeRoot = exports.StructTreePage = void 0;
var _primitives = __w_pdfjs_require__(3);
var _util = __w_pdfjs_require__(2);
var _name_number_tree = __w_pdfjs_require__(68);
const MAX_DEPTH = 40;
const StructElementType = {
  PAGE_CONTENT: "PAGE_CONTENT",
  STREAM_CONTENT: "STREAM_CONTENT",
  OBJECT: "OBJECT",
  ELEMENT: "ELEMENT"
};
class StructTreeRoot {
  constructor(rootDict) {
    this.dict = rootDict;
    this.roleMap = new Map();
  }
  init() {
    this.readRoleMap();
  }
  readRoleMap() {
    const roleMapDict = this.dict.get("RoleMap");
    if (!(roleMapDict instanceof _primitives.Dict)) {
      return;
    }
    roleMapDict.forEach((key, value) => {
      if (!(value instanceof _primitives.Name)) {
        return;
      }
      this.roleMap.set(key, value.name);
    });
  }
}
exports.StructTreeRoot = StructTreeRoot;
class StructElementNode {
  constructor(tree, dict) {
    this.tree = tree;
    this.dict = dict;
    this.kids = [];
    this.parseKids();
  }
  get role() {
    const nameObj = this.dict.get("S");
    const name = nameObj instanceof _primitives.Name ? nameObj.name : "";
    const {
      root
    } = this.tree;
    if (root.roleMap.has(name)) {
      return root.roleMap.get(name);
    }
    return name;
  }
  parseKids() {
    let pageObjId = null;
    const objRef = this.dict.getRaw("Pg");
    if (objRef instanceof _primitives.Ref) {
      pageObjId = objRef.toString();
    }
    const kids = this.dict.get("K");
    if (Array.isArray(kids)) {
      for (const kid of kids) {
        const element = this.parseKid(pageObjId, kid);
        if (element) {
          this.kids.push(element);
        }
      }
    } else {
      const element = this.parseKid(pageObjId, kids);
      if (element) {
        this.kids.push(element);
      }
    }
  }
  parseKid(pageObjId, kid) {
    if (Number.isInteger(kid)) {
      if (this.tree.pageDict.objId !== pageObjId) {
        return null;
      }
      return new StructElement({
        type: StructElementType.PAGE_CONTENT,
        mcid: kid,
        pageObjId
      });
    }
    let kidDict = null;
    if (kid instanceof _primitives.Ref) {
      kidDict = this.dict.xref.fetch(kid);
    } else if (kid instanceof _primitives.Dict) {
      kidDict = kid;
    }
    if (!kidDict) {
      return null;
    }
    const pageRef = kidDict.getRaw("Pg");
    if (pageRef instanceof _primitives.Ref) {
      pageObjId = pageRef.toString();
    }
    const type = kidDict.get("Type") instanceof _primitives.Name ? kidDict.get("Type").name : null;
    if (type === "MCR") {
      if (this.tree.pageDict.objId !== pageObjId) {
        return null;
      }
      return new StructElement({
        type: StructElementType.STREAM_CONTENT,
        refObjId: kidDict.getRaw("Stm") instanceof _primitives.Ref ? kidDict.getRaw("Stm").toString() : null,
        pageObjId,
        mcid: kidDict.get("MCID")
      });
    }
    if (type === "OBJR") {
      if (this.tree.pageDict.objId !== pageObjId) {
        return null;
      }
      return new StructElement({
        type: StructElementType.OBJECT,
        refObjId: kidDict.getRaw("Obj") instanceof _primitives.Ref ? kidDict.getRaw("Obj").toString() : null,
        pageObjId
      });
    }
    return new StructElement({
      type: StructElementType.ELEMENT,
      dict: kidDict
    });
  }
}
class StructElement {
  constructor({
    type,
    dict = null,
    mcid = null,
    pageObjId = null,
    refObjId = null
  }) {
    this.type = type;
    this.dict = dict;
    this.mcid = mcid;
    this.pageObjId = pageObjId;
    this.refObjId = refObjId;
    this.parentNode = null;
  }
}
class StructTreePage {
  constructor(structTreeRoot, pageDict) {
    this.root = structTreeRoot;
    this.rootDict = structTreeRoot ? structTreeRoot.dict : null;
    this.pageDict = pageDict;
    this.nodes = [];
  }
  parse() {
    if (!this.root || !this.rootDict) {
      return;
    }
    const parentTree = this.rootDict.get("ParentTree");
    if (!parentTree) {
      return;
    }
    const id = this.pageDict.get("StructParents");
    if (!Number.isInteger(id)) {
      return;
    }
    const numberTree = new _name_number_tree.NumberTree(parentTree, this.rootDict.xref);
    const parentArray = numberTree.get(id);
    if (!Array.isArray(parentArray)) {
      return;
    }
    const map = new Map();
    for (const ref of parentArray) {
      if (ref instanceof _primitives.Ref) {
        this.addNode(this.rootDict.xref.fetch(ref), map);
      }
    }
  }
  addNode(dict, map, level = 0) {
    if (level > MAX_DEPTH) {
      (0, _util.warn)("StructTree MAX_DEPTH reached.");
      return null;
    }
    if (map.has(dict)) {
      return map.get(dict);
    }
    const element = new StructElementNode(this, dict);
    map.set(dict, element);
    const parent = dict.get("P");
    if (!parent || (0, _primitives.isName)(parent.get("Type"), "StructTreeRoot")) {
      if (!this.addTopLevelNode(dict, element)) {
        map.delete(dict);
      }
      return element;
    }
    const parentNode = this.addNode(parent, map, level + 1);
    if (!parentNode) {
      return element;
    }
    let save = false;
    for (const kid of parentNode.kids) {
      if (kid.type === StructElementType.ELEMENT && kid.dict === dict) {
        kid.parentNode = element;
        save = true;
      }
    }
    if (!save) {
      map.delete(dict);
    }
    return element;
  }
  addTopLevelNode(dict, element) {
    const obj = this.rootDict.get("K");
    if (!obj) {
      return false;
    }
    if (obj instanceof _primitives.Dict) {
      if (obj.objId !== dict.objId) {
        return false;
      }
      this.nodes[0] = element;
      return true;
    }
    if (!Array.isArray(obj)) {
      return true;
    }
    let save = false;
    for (let i = 0; i < obj.length; i++) {
      const kidRef = obj[i];
      if (kidRef && kidRef.toString() === dict.objId) {
        this.nodes[i] = element;
        save = true;
      }
    }
    return save;
  }
  get serializable() {
    function nodeToSerializable(node, parent, level = 0) {
      if (level > MAX_DEPTH) {
        (0, _util.warn)("StructTree too deep to be fully serialized.");
        return;
      }
      const obj = Object.create(null);
      obj.role = node.role;
      obj.children = [];
      parent.children.push(obj);
      const alt = node.dict.get("Alt");
      if (typeof alt === "string") {
        obj.alt = (0, _util.stringToPDFString)(alt);
      }
      const lang = node.dict.get("Lang");
      if (typeof lang === "string") {
        obj.lang = (0, _util.stringToPDFString)(lang);
      }
      for (const kid of node.kids) {
        const kidElement = kid.type === StructElementType.ELEMENT ? kid.parentNode : null;
        if (kidElement) {
          nodeToSerializable(kidElement, obj, level + 1);
          continue;
        } else if (kid.type === StructElementType.PAGE_CONTENT || kid.type === StructElementType.STREAM_CONTENT) {
          obj.children.push({
            type: "content",
            id: `page${kid.pageObjId}_mcid${kid.mcid}`
          });
        } else if (kid.type === StructElementType.OBJECT) {
          obj.children.push({
            type: "object",
            id: kid.refObjId
          });
        }
      }
    }
    const root = Object.create(null);
    root.children = [];
    root.role = "Root";
    for (const child of this.nodes) {
      if (!child) {
        continue;
      }
      nodeToSerializable(child, root);
    }
    return root;
  }
}
exports.StructTreePage = StructTreePage;

/***/ }),
/* 73 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ObjectLoader = void 0;
var _primitives = __w_pdfjs_require__(3);
var _base_stream = __w_pdfjs_require__(5);
var _core_utils = __w_pdfjs_require__(4);
var _util = __w_pdfjs_require__(2);
function mayHaveChildren(value) {
  return value instanceof _primitives.Ref || value instanceof _primitives.Dict || value instanceof _base_stream.BaseStream || Array.isArray(value);
}
function addChildren(node, nodesToVisit) {
  if (node instanceof _primitives.Dict) {
    node = node.getRawValues();
  } else if (node instanceof _base_stream.BaseStream) {
    node = node.dict.getRawValues();
  } else if (!Array.isArray(node)) {
    return;
  }
  for (const rawValue of node) {
    if (mayHaveChildren(rawValue)) {
      nodesToVisit.push(rawValue);
    }
  }
}
class ObjectLoader {
  constructor(dict, keys, xref) {
    this.dict = dict;
    this.keys = keys;
    this.xref = xref;
    this.refSet = null;
  }
  async load() {
    if (this.xref.stream.isDataLoaded) {
      return undefined;
    }
    const {
      keys,
      dict
    } = this;
    this.refSet = new _primitives.RefSet();
    const nodesToVisit = [];
    for (const key of keys) {
      const rawValue = dict.getRaw(key);
      if (rawValue !== undefined) {
        nodesToVisit.push(rawValue);
      }
    }
    return this._walk(nodesToVisit);
  }
  async _walk(nodesToVisit) {
    const nodesToRevisit = [];
    const pendingRequests = [];
    while (nodesToVisit.length) {
      let currentNode = nodesToVisit.pop();
      if (currentNode instanceof _primitives.Ref) {
        if (this.refSet.has(currentNode)) {
          continue;
        }
        try {
          this.refSet.put(currentNode);
          currentNode = this.xref.fetch(currentNode);
        } catch (ex) {
          if (!(ex instanceof _core_utils.MissingDataException)) {
            (0, _util.warn)(`ObjectLoader._walk - requesting all data: "${ex}".`);
            this.refSet = null;
            const {
              manager
            } = this.xref.stream;
            return manager.requestAllChunks();
          }
          nodesToRevisit.push(currentNode);
          pendingRequests.push({
            begin: ex.begin,
            end: ex.end
          });
        }
      }
      if (currentNode instanceof _base_stream.BaseStream) {
        const baseStreams = currentNode.getBaseStreams();
        if (baseStreams) {
          let foundMissingData = false;
          for (const stream of baseStreams) {
            if (stream.isDataLoaded) {
              continue;
            }
            foundMissingData = true;
            pendingRequests.push({
              begin: stream.start,
              end: stream.end
            });
          }
          if (foundMissingData) {
            nodesToRevisit.push(currentNode);
          }
        }
      }
      addChildren(currentNode, nodesToVisit);
    }
    if (pendingRequests.length) {
      await this.xref.stream.manager.requestRanges(pendingRequests);
      for (const node of nodesToRevisit) {
        if (node instanceof _primitives.Ref) {
          this.refSet.remove(node);
        }
      }
      return this._walk(nodesToRevisit);
    }
    this.refSet = null;
    return undefined;
  }
}
exports.ObjectLoader = ObjectLoader;

/***/ }),
/* 74 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XFAFactory = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _bind = __w_pdfjs_require__(79);
var _data = __w_pdfjs_require__(85);
var _fonts = __w_pdfjs_require__(83);
var _utils = __w_pdfjs_require__(76);
var _util = __w_pdfjs_require__(2);
var _parser = __w_pdfjs_require__(86);
var _xhtml = __w_pdfjs_require__(96);
class XFAFactory {
  constructor(data) {
    try {
      this.root = new _parser.XFAParser().parse(XFAFactory._createDocument(data));
      const binder = new _bind.Binder(this.root);
      this.form = binder.bind();
      this.dataHandler = new _data.DataHandler(this.root, binder.getData());
      this.form[_xfa_object.$globalData].template = this.form;
    } catch (e) {
      (0, _util.warn)(`XFA - an error occurred during parsing and binding: ${e}`);
    }
  }
  isValid() {
    return this.root && this.form;
  }
  _createPagesHelper() {
    const iterator = this.form[_xfa_object.$toPages]();
    return new Promise((resolve, reject) => {
      const nextIteration = () => {
        try {
          const value = iterator.next();
          if (value.done) {
            resolve(value.value);
          } else {
            setTimeout(nextIteration, 0);
          }
        } catch (e) {
          reject(e);
        }
      };
      setTimeout(nextIteration, 0);
    });
  }
  async _createPages() {
    try {
      this.pages = await this._createPagesHelper();
      this.dims = this.pages.children.map(c => {
        const {
          width,
          height
        } = c.attributes.style;
        return [0, 0, parseInt(width), parseInt(height)];
      });
    } catch (e) {
      (0, _util.warn)(`XFA - an error occurred during layout: ${e}`);
    }
  }
  getBoundingBox(pageIndex) {
    return this.dims[pageIndex];
  }
  async getNumPages() {
    if (!this.pages) {
      await this._createPages();
    }
    return this.dims.length;
  }
  setImages(images) {
    this.form[_xfa_object.$globalData].images = images;
  }
  setFonts(fonts) {
    this.form[_xfa_object.$globalData].fontFinder = new _fonts.FontFinder(fonts);
    const missingFonts = [];
    for (let typeface of this.form[_xfa_object.$globalData].usedTypefaces) {
      typeface = (0, _utils.stripQuotes)(typeface);
      const font = this.form[_xfa_object.$globalData].fontFinder.find(typeface);
      if (!font) {
        missingFonts.push(typeface);
      }
    }
    if (missingFonts.length > 0) {
      return missingFonts;
    }
    return null;
  }
  appendFonts(fonts, reallyMissingFonts) {
    this.form[_xfa_object.$globalData].fontFinder.add(fonts, reallyMissingFonts);
  }
  async getPages() {
    if (!this.pages) {
      await this._createPages();
    }
    const pages = this.pages;
    this.pages = null;
    return pages;
  }
  serializeData(storage) {
    return this.dataHandler.serialize(storage);
  }
  static _createDocument(data) {
    if (!data["/xdp:xdp"]) {
      return data["xdp:xdp"];
    }
    return Object.values(data).join("");
  }
  static getRichTextAsHtml(rc) {
    if (!rc || typeof rc !== "string") {
      return null;
    }
    try {
      let root = new _parser.XFAParser(_xhtml.XhtmlNamespace, true).parse(rc);
      if (!["body", "xhtml"].includes(root[_xfa_object.$nodeName])) {
        const newRoot = _xhtml.XhtmlNamespace.body({});
        newRoot[_xfa_object.$appendChild](root);
        root = newRoot;
      }
      const result = root[_xfa_object.$toHTML]();
      if (!result.success) {
        return null;
      }
      const {
        html
      } = result;
      const {
        attributes
      } = html;
      if (attributes) {
        if (attributes.class) {
          attributes.class = attributes.class.filter(attr => !attr.startsWith("xfa"));
        }
        attributes.dir = "auto";
      }
      return {
        html,
        str: root[_xfa_object.$text]()
      };
    } catch (e) {
      (0, _util.warn)(`XFA - an error occurred during parsing of rich text: ${e}`);
    }
    return null;
  }
}
exports.XFAFactory = XFAFactory;

/***/ }),
/* 75 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XmlObject = exports.XFAObjectArray = exports.XFAObject = exports.XFAAttribute = exports.StringObject = exports.OptionObject = exports.Option10 = exports.Option01 = exports.IntegerObject = exports.ContentObject = exports.$uid = exports.$toStyle = exports.$toString = exports.$toPages = exports.$toHTML = exports.$text = exports.$tabIndex = exports.$setValue = exports.$setSetAttributes = exports.$setId = exports.$searchNode = exports.$root = exports.$resolvePrototypes = exports.$removeChild = exports.$pushPara = exports.$pushGlyphs = exports.$popPara = exports.$onText = exports.$onChildCheck = exports.$onChild = exports.$nsAttributes = exports.$nodeName = exports.$namespaceId = exports.$isUsable = exports.$isTransparent = exports.$isThereMoreWidth = exports.$isSplittable = exports.$isNsAgnostic = exports.$isDescendent = exports.$isDataValue = exports.$isCDATAXml = exports.$isBindable = exports.$insertAt = exports.$indexOf = exports.$ids = exports.$hasSettableValue = exports.$globalData = exports.$getTemplateRoot = exports.$getSubformParent = exports.$getRealChildrenByNameIt = exports.$getParent = exports.$getNextPage = exports.$getExtra = exports.$getDataValue = exports.$getContainedChildren = exports.$getChildrenByNameIt = exports.$getChildrenByName = exports.$getChildrenByClass = exports.$getChildren = exports.$getAvailableSpace = exports.$getAttributes = exports.$getAttributeIt = exports.$flushHTML = exports.$finalize = exports.$extra = exports.$dump = exports.$data = exports.$content = exports.$consumed = exports.$clone = exports.$cleanup = exports.$cleanPage = exports.$clean = exports.$childrenToHTML = exports.$appendChild = exports.$addHTML = exports.$acceptWhitespace = void 0;
var _utils = __w_pdfjs_require__(76);
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _namespaces = __w_pdfjs_require__(77);
var _som = __w_pdfjs_require__(78);
const $acceptWhitespace = Symbol();
exports.$acceptWhitespace = $acceptWhitespace;
const $addHTML = Symbol();
exports.$addHTML = $addHTML;
const $appendChild = Symbol();
exports.$appendChild = $appendChild;
const $childrenToHTML = Symbol();
exports.$childrenToHTML = $childrenToHTML;
const $clean = Symbol();
exports.$clean = $clean;
const $cleanPage = Symbol();
exports.$cleanPage = $cleanPage;
const $cleanup = Symbol();
exports.$cleanup = $cleanup;
const $clone = Symbol();
exports.$clone = $clone;
const $consumed = Symbol();
exports.$consumed = $consumed;
const $content = Symbol("content");
exports.$content = $content;
const $data = Symbol("data");
exports.$data = $data;
const $dump = Symbol();
exports.$dump = $dump;
const $extra = Symbol("extra");
exports.$extra = $extra;
const $finalize = Symbol();
exports.$finalize = $finalize;
const $flushHTML = Symbol();
exports.$flushHTML = $flushHTML;
const $getAttributeIt = Symbol();
exports.$getAttributeIt = $getAttributeIt;
const $getAttributes = Symbol();
exports.$getAttributes = $getAttributes;
const $getAvailableSpace = Symbol();
exports.$getAvailableSpace = $getAvailableSpace;
const $getChildrenByClass = Symbol();
exports.$getChildrenByClass = $getChildrenByClass;
const $getChildrenByName = Symbol();
exports.$getChildrenByName = $getChildrenByName;
const $getChildrenByNameIt = Symbol();
exports.$getChildrenByNameIt = $getChildrenByNameIt;
const $getDataValue = Symbol();
exports.$getDataValue = $getDataValue;
const $getExtra = Symbol();
exports.$getExtra = $getExtra;
const $getRealChildrenByNameIt = Symbol();
exports.$getRealChildrenByNameIt = $getRealChildrenByNameIt;
const $getChildren = Symbol();
exports.$getChildren = $getChildren;
const $getContainedChildren = Symbol();
exports.$getContainedChildren = $getContainedChildren;
const $getNextPage = Symbol();
exports.$getNextPage = $getNextPage;
const $getSubformParent = Symbol();
exports.$getSubformParent = $getSubformParent;
const $getParent = Symbol();
exports.$getParent = $getParent;
const $getTemplateRoot = Symbol();
exports.$getTemplateRoot = $getTemplateRoot;
const $globalData = Symbol();
exports.$globalData = $globalData;
const $hasSettableValue = Symbol();
exports.$hasSettableValue = $hasSettableValue;
const $ids = Symbol();
exports.$ids = $ids;
const $indexOf = Symbol();
exports.$indexOf = $indexOf;
const $insertAt = Symbol();
exports.$insertAt = $insertAt;
const $isCDATAXml = Symbol();
exports.$isCDATAXml = $isCDATAXml;
const $isBindable = Symbol();
exports.$isBindable = $isBindable;
const $isDataValue = Symbol();
exports.$isDataValue = $isDataValue;
const $isDescendent = Symbol();
exports.$isDescendent = $isDescendent;
const $isNsAgnostic = Symbol();
exports.$isNsAgnostic = $isNsAgnostic;
const $isSplittable = Symbol();
exports.$isSplittable = $isSplittable;
const $isThereMoreWidth = Symbol();
exports.$isThereMoreWidth = $isThereMoreWidth;
const $isTransparent = Symbol();
exports.$isTransparent = $isTransparent;
const $isUsable = Symbol();
exports.$isUsable = $isUsable;
const $lastAttribute = Symbol();
const $namespaceId = Symbol("namespaceId");
exports.$namespaceId = $namespaceId;
const $nodeName = Symbol("nodeName");
exports.$nodeName = $nodeName;
const $nsAttributes = Symbol();
exports.$nsAttributes = $nsAttributes;
const $onChild = Symbol();
exports.$onChild = $onChild;
const $onChildCheck = Symbol();
exports.$onChildCheck = $onChildCheck;
const $onText = Symbol();
exports.$onText = $onText;
const $pushGlyphs = Symbol();
exports.$pushGlyphs = $pushGlyphs;
const $popPara = Symbol();
exports.$popPara = $popPara;
const $pushPara = Symbol();
exports.$pushPara = $pushPara;
const $removeChild = Symbol();
exports.$removeChild = $removeChild;
const $root = Symbol("root");
exports.$root = $root;
const $resolvePrototypes = Symbol();
exports.$resolvePrototypes = $resolvePrototypes;
const $searchNode = Symbol();
exports.$searchNode = $searchNode;
const $setId = Symbol();
exports.$setId = $setId;
const $setSetAttributes = Symbol();
exports.$setSetAttributes = $setSetAttributes;
const $setValue = Symbol();
exports.$setValue = $setValue;
const $tabIndex = Symbol();
exports.$tabIndex = $tabIndex;
const $text = Symbol();
exports.$text = $text;
const $toPages = Symbol();
exports.$toPages = $toPages;
const $toHTML = Symbol();
exports.$toHTML = $toHTML;
const $toString = Symbol();
exports.$toString = $toString;
const $toStyle = Symbol();
exports.$toStyle = $toStyle;
const $uid = Symbol("uid");
exports.$uid = $uid;
const _applyPrototype = Symbol();
const _attributes = Symbol();
const _attributeNames = Symbol();
const _children = Symbol("_children");
const _cloneAttribute = Symbol();
const _dataValue = Symbol();
const _defaultValue = Symbol();
const _filteredChildrenGenerator = Symbol();
const _getPrototype = Symbol();
const _getUnsetAttributes = Symbol();
const _hasChildren = Symbol();
const _max = Symbol();
const _options = Symbol();
const _parent = Symbol("parent");
const _resolvePrototypesHelper = Symbol();
const _setAttributes = Symbol();
const _validator = Symbol();
let uid = 0;
const NS_DATASETS = _namespaces.NamespaceIds.datasets.id;
class XFAObject {
  constructor(nsId, name, hasChildren = false) {
    this[$namespaceId] = nsId;
    this[$nodeName] = name;
    this[_hasChildren] = hasChildren;
    this[_parent] = null;
    this[_children] = [];
    this[$uid] = `${name}${uid++}`;
    this[$globalData] = null;
  }
  [$onChild](child) {
    if (!this[_hasChildren] || !this[$onChildCheck](child)) {
      return false;
    }
    const name = child[$nodeName];
    const node = this[name];
    if (node instanceof XFAObjectArray) {
      if (node.push(child)) {
        this[$appendChild](child);
        return true;
      }
    } else {
      if (node !== null) {
        this[$removeChild](node);
      }
      this[name] = child;
      this[$appendChild](child);
      return true;
    }
    let id = "";
    if (this.id) {
      id = ` (id: ${this.id})`;
    } else if (this.name) {
      id = ` (name: ${this.name} ${this.h.value})`;
    }
    (0, _util.warn)(`XFA - node "${this[$nodeName]}"${id} has already enough "${name}"!`);
    return false;
  }
  [$onChildCheck](child) {
    return this.hasOwnProperty(child[$nodeName]) && child[$namespaceId] === this[$namespaceId];
  }
  [$isNsAgnostic]() {
    return false;
  }
  [$acceptWhitespace]() {
    return false;
  }
  [$isCDATAXml]() {
    return false;
  }
  [$isBindable]() {
    return false;
  }
  [$popPara]() {
    if (this.para) {
      this[$getTemplateRoot]()[$extra].paraStack.pop();
    }
  }
  [$pushPara]() {
    this[$getTemplateRoot]()[$extra].paraStack.push(this.para);
  }
  [$setId](ids) {
    if (this.id && this[$namespaceId] === _namespaces.NamespaceIds.template.id) {
      ids.set(this.id, this);
    }
  }
  [$getTemplateRoot]() {
    return this[$globalData].template;
  }
  [$isSplittable]() {
    return false;
  }
  [$isThereMoreWidth]() {
    return false;
  }
  [$appendChild](child) {
    child[_parent] = this;
    this[_children].push(child);
    if (!child[$globalData] && this[$globalData]) {
      child[$globalData] = this[$globalData];
    }
  }
  [$removeChild](child) {
    const i = this[_children].indexOf(child);
    this[_children].splice(i, 1);
  }
  [$hasSettableValue]() {
    return this.hasOwnProperty("value");
  }
  [$setValue](_) {}
  [$onText](_) {}
  [$finalize]() {}
  [$clean](builder) {
    delete this[_hasChildren];
    if (this[$cleanup]) {
      builder.clean(this[$cleanup]);
      delete this[$cleanup];
    }
  }
  [$indexOf](child) {
    return this[_children].indexOf(child);
  }
  [$insertAt](i, child) {
    child[_parent] = this;
    this[_children].splice(i, 0, child);
    if (!child[$globalData] && this[$globalData]) {
      child[$globalData] = this[$globalData];
    }
  }
  [$isTransparent]() {
    return !this.name;
  }
  [$lastAttribute]() {
    return "";
  }
  [$text]() {
    if (this[_children].length === 0) {
      return this[$content];
    }
    return this[_children].map(c => c[$text]()).join("");
  }
  get [_attributeNames]() {
    const proto = Object.getPrototypeOf(this);
    if (!proto._attributes) {
      const attributes = proto._attributes = new Set();
      for (const name of Object.getOwnPropertyNames(this)) {
        if (this[name] === null || this[name] instanceof XFAObject || this[name] instanceof XFAObjectArray) {
          break;
        }
        attributes.add(name);
      }
    }
    return (0, _util.shadow)(this, _attributeNames, proto._attributes);
  }
  [$isDescendent](parent) {
    let node = this;
    while (node) {
      if (node === parent) {
        return true;
      }
      node = node[$getParent]();
    }
    return false;
  }
  [$getParent]() {
    return this[_parent];
  }
  [$getSubformParent]() {
    return this[$getParent]();
  }
  [$getChildren](name = null) {
    if (!name) {
      return this[_children];
    }
    return this[name];
  }
  [$dump]() {
    const dumped = Object.create(null);
    if (this[$content]) {
      dumped.$content = this[$content];
    }
    for (const name of Object.getOwnPropertyNames(this)) {
      const value = this[name];
      if (value === null) {
        continue;
      }
      if (value instanceof XFAObject) {
        dumped[name] = value[$dump]();
      } else if (value instanceof XFAObjectArray) {
        if (!value.isEmpty()) {
          dumped[name] = value.dump();
        }
      } else {
        dumped[name] = value;
      }
    }
    return dumped;
  }
  [$toStyle]() {
    return null;
  }
  [$toHTML]() {
    return _utils.HTMLResult.EMPTY;
  }
  *[$getContainedChildren]() {
    for (const node of this[$getChildren]()) {
      yield node;
    }
  }
  *[_filteredChildrenGenerator](filter, include) {
    for (const node of this[$getContainedChildren]()) {
      if (!filter || include === filter.has(node[$nodeName])) {
        const availableSpace = this[$getAvailableSpace]();
        const res = node[$toHTML](availableSpace);
        if (!res.success) {
          this[$extra].failingNode = node;
        }
        yield res;
      }
    }
  }
  [$flushHTML]() {
    return null;
  }
  [$addHTML](html, bbox) {
    this[$extra].children.push(html);
  }
  [$getAvailableSpace]() {}
  [$childrenToHTML]({
    filter = null,
    include = true
  }) {
    if (!this[$extra].generator) {
      this[$extra].generator = this[_filteredChildrenGenerator](filter, include);
    } else {
      const availableSpace = this[$getAvailableSpace]();
      const res = this[$extra].failingNode[$toHTML](availableSpace);
      if (!res.success) {
        return res;
      }
      if (res.html) {
        this[$addHTML](res.html, res.bbox);
      }
      delete this[$extra].failingNode;
    }
    while (true) {
      const gen = this[$extra].generator.next();
      if (gen.done) {
        break;
      }
      const res = gen.value;
      if (!res.success) {
        return res;
      }
      if (res.html) {
        this[$addHTML](res.html, res.bbox);
      }
    }
    this[$extra].generator = null;
    return _utils.HTMLResult.EMPTY;
  }
  [$setSetAttributes](attributes) {
    this[_setAttributes] = new Set(Object.keys(attributes));
  }
  [_getUnsetAttributes](protoAttributes) {
    const allAttr = this[_attributeNames];
    const setAttr = this[_setAttributes];
    return [...protoAttributes].filter(x => allAttr.has(x) && !setAttr.has(x));
  }
  [$resolvePrototypes](ids, ancestors = new Set()) {
    for (const child of this[_children]) {
      child[_resolvePrototypesHelper](ids, ancestors);
    }
  }
  [_resolvePrototypesHelper](ids, ancestors) {
    const proto = this[_getPrototype](ids, ancestors);
    if (proto) {
      this[_applyPrototype](proto, ids, ancestors);
    } else {
      this[$resolvePrototypes](ids, ancestors);
    }
  }
  [_getPrototype](ids, ancestors) {
    const {
      use,
      usehref
    } = this;
    if (!use && !usehref) {
      return null;
    }
    let proto = null;
    let somExpression = null;
    let id = null;
    let ref = use;
    if (usehref) {
      ref = usehref;
      if (usehref.startsWith("#som(") && usehref.endsWith(")")) {
        somExpression = usehref.slice("#som(".length, usehref.length - 1);
      } else if (usehref.startsWith(".#som(") && usehref.endsWith(")")) {
        somExpression = usehref.slice(".#som(".length, usehref.length - 1);
      } else if (usehref.startsWith("#")) {
        id = usehref.slice(1);
      } else if (usehref.startsWith(".#")) {
        id = usehref.slice(2);
      }
    } else if (use.startsWith("#")) {
      id = use.slice(1);
    } else {
      somExpression = use;
    }
    this.use = this.usehref = "";
    if (id) {
      proto = ids.get(id);
    } else {
      proto = (0, _som.searchNode)(ids.get($root), this, somExpression, true, false);
      if (proto) {
        proto = proto[0];
      }
    }
    if (!proto) {
      (0, _util.warn)(`XFA - Invalid prototype reference: ${ref}.`);
      return null;
    }
    if (proto[$nodeName] !== this[$nodeName]) {
      (0, _util.warn)(`XFA - Incompatible prototype: ${proto[$nodeName]} !== ${this[$nodeName]}.`);
      return null;
    }
    if (ancestors.has(proto)) {
      (0, _util.warn)(`XFA - Cycle detected in prototypes use.`);
      return null;
    }
    ancestors.add(proto);
    const protoProto = proto[_getPrototype](ids, ancestors);
    if (protoProto) {
      proto[_applyPrototype](protoProto, ids, ancestors);
    }
    proto[$resolvePrototypes](ids, ancestors);
    ancestors.delete(proto);
    return proto;
  }
  [_applyPrototype](proto, ids, ancestors) {
    if (ancestors.has(proto)) {
      (0, _util.warn)(`XFA - Cycle detected in prototypes use.`);
      return;
    }
    if (!this[$content] && proto[$content]) {
      this[$content] = proto[$content];
    }
    const newAncestors = new Set(ancestors);
    newAncestors.add(proto);
    for (const unsetAttrName of this[_getUnsetAttributes](proto[_setAttributes])) {
      this[unsetAttrName] = proto[unsetAttrName];
      if (this[_setAttributes]) {
        this[_setAttributes].add(unsetAttrName);
      }
    }
    for (const name of Object.getOwnPropertyNames(this)) {
      if (this[_attributeNames].has(name)) {
        continue;
      }
      const value = this[name];
      const protoValue = proto[name];
      if (value instanceof XFAObjectArray) {
        for (const child of value[_children]) {
          child[_resolvePrototypesHelper](ids, ancestors);
        }
        for (let i = value[_children].length, ii = protoValue[_children].length; i < ii; i++) {
          const child = proto[_children][i][$clone]();
          if (value.push(child)) {
            child[_parent] = this;
            this[_children].push(child);
            child[_resolvePrototypesHelper](ids, ancestors);
          } else {
            break;
          }
        }
        continue;
      }
      if (value !== null) {
        value[$resolvePrototypes](ids, ancestors);
        if (protoValue) {
          value[_applyPrototype](protoValue, ids, ancestors);
        }
        continue;
      }
      if (protoValue !== null) {
        const child = protoValue[$clone]();
        child[_parent] = this;
        this[name] = child;
        this[_children].push(child);
        child[_resolvePrototypesHelper](ids, ancestors);
      }
    }
  }
  static [_cloneAttribute](obj) {
    if (Array.isArray(obj)) {
      return obj.map(x => XFAObject[_cloneAttribute](x));
    }
    if (typeof obj === "object" && obj !== null) {
      return Object.assign({}, obj);
    }
    return obj;
  }
  [$clone]() {
    const clone = Object.create(Object.getPrototypeOf(this));
    for (const $symbol of Object.getOwnPropertySymbols(this)) {
      try {
        clone[$symbol] = this[$symbol];
      } catch (_) {
        (0, _util.shadow)(clone, $symbol, this[$symbol]);
      }
    }
    clone[$uid] = `${clone[$nodeName]}${uid++}`;
    clone[_children] = [];
    for (const name of Object.getOwnPropertyNames(this)) {
      if (this[_attributeNames].has(name)) {
        clone[name] = XFAObject[_cloneAttribute](this[name]);
        continue;
      }
      const value = this[name];
      if (value instanceof XFAObjectArray) {
        clone[name] = new XFAObjectArray(value[_max]);
      } else {
        clone[name] = null;
      }
    }
    for (const child of this[_children]) {
      const name = child[$nodeName];
      const clonedChild = child[$clone]();
      clone[_children].push(clonedChild);
      clonedChild[_parent] = clone;
      if (clone[name] === null) {
        clone[name] = clonedChild;
      } else {
        clone[name][_children].push(clonedChild);
      }
    }
    return clone;
  }
  [$getChildren](name = null) {
    if (!name) {
      return this[_children];
    }
    return this[_children].filter(c => c[$nodeName] === name);
  }
  [$getChildrenByClass](name) {
    return this[name];
  }
  [$getChildrenByName](name, allTransparent, first = true) {
    return Array.from(this[$getChildrenByNameIt](name, allTransparent, first));
  }
  *[$getChildrenByNameIt](name, allTransparent, first = true) {
    if (name === "parent") {
      yield this[_parent];
      return;
    }
    for (const child of this[_children]) {
      if (child[$nodeName] === name) {
        yield child;
      }
      if (child.name === name) {
        yield child;
      }
      if (allTransparent || child[$isTransparent]()) {
        yield* child[$getChildrenByNameIt](name, allTransparent, false);
      }
    }
    if (first && this[_attributeNames].has(name)) {
      yield new XFAAttribute(this, name, this[name]);
    }
  }
}
exports.XFAObject = XFAObject;
class XFAObjectArray {
  constructor(max = Infinity) {
    this[_max] = max;
    this[_children] = [];
  }
  push(child) {
    const len = this[_children].length;
    if (len <= this[_max]) {
      this[_children].push(child);
      return true;
    }
    (0, _util.warn)(`XFA - node "${child[$nodeName]}" accepts no more than ${this[_max]} children`);
    return false;
  }
  isEmpty() {
    return this[_children].length === 0;
  }
  dump() {
    return this[_children].length === 1 ? this[_children][0][$dump]() : this[_children].map(x => x[$dump]());
  }
  [$clone]() {
    const clone = new XFAObjectArray(this[_max]);
    clone[_children] = this[_children].map(c => c[$clone]());
    return clone;
  }
  get children() {
    return this[_children];
  }
  clear() {
    this[_children].length = 0;
  }
}
exports.XFAObjectArray = XFAObjectArray;
class XFAAttribute {
  constructor(node, name, value) {
    this[_parent] = node;
    this[$nodeName] = name;
    this[$content] = value;
    this[$consumed] = false;
    this[$uid] = `attribute${uid++}`;
  }
  [$getParent]() {
    return this[_parent];
  }
  [$isDataValue]() {
    return true;
  }
  [$getDataValue]() {
    return this[$content].trim();
  }
  [$setValue](value) {
    value = value.value || "";
    this[$content] = value.toString();
  }
  [$text]() {
    return this[$content];
  }
  [$isDescendent](parent) {
    return this[_parent] === parent || this[_parent][$isDescendent](parent);
  }
}
exports.XFAAttribute = XFAAttribute;
class XmlObject extends XFAObject {
  constructor(nsId, name, attributes = {}) {
    super(nsId, name);
    this[$content] = "";
    this[_dataValue] = null;
    if (name !== "#text") {
      const map = new Map();
      this[_attributes] = map;
      for (const [attrName, value] of Object.entries(attributes)) {
        map.set(attrName, new XFAAttribute(this, attrName, value));
      }
      if (attributes.hasOwnProperty($nsAttributes)) {
        const dataNode = attributes[$nsAttributes].xfa.dataNode;
        if (dataNode !== undefined) {
          if (dataNode === "dataGroup") {
            this[_dataValue] = false;
          } else if (dataNode === "dataValue") {
            this[_dataValue] = true;
          }
        }
      }
    }
    this[$consumed] = false;
  }
  [$toString](buf) {
    const tagName = this[$nodeName];
    if (tagName === "#text") {
      buf.push((0, _core_utils.encodeToXmlString)(this[$content]));
      return;
    }
    const utf8TagName = (0, _util.utf8StringToString)(tagName);
    const prefix = this[$namespaceId] === NS_DATASETS ? "xfa:" : "";
    buf.push(`<${prefix}${utf8TagName}`);
    for (const [name, value] of this[_attributes].entries()) {
      const utf8Name = (0, _util.utf8StringToString)(name);
      buf.push(` ${utf8Name}="${(0, _core_utils.encodeToXmlString)(value[$content])}"`);
    }
    if (this[_dataValue] !== null) {
      if (this[_dataValue]) {
        buf.push(` xfa:dataNode="dataValue"`);
      } else {
        buf.push(` xfa:dataNode="dataGroup"`);
      }
    }
    if (!this[$content] && this[_children].length === 0) {
      buf.push("/>");
      return;
    }
    buf.push(">");
    if (this[$content]) {
      if (typeof this[$content] === "string") {
        buf.push((0, _core_utils.encodeToXmlString)(this[$content]));
      } else {
        this[$content][$toString](buf);
      }
    } else {
      for (const child of this[_children]) {
        child[$toString](buf);
      }
    }
    buf.push(`</${prefix}${utf8TagName}>`);
  }
  [$onChild](child) {
    if (this[$content]) {
      const node = new XmlObject(this[$namespaceId], "#text");
      this[$appendChild](node);
      node[$content] = this[$content];
      this[$content] = "";
    }
    this[$appendChild](child);
    return true;
  }
  [$onText](str) {
    this[$content] += str;
  }
  [$finalize]() {
    if (this[$content] && this[_children].length > 0) {
      const node = new XmlObject(this[$namespaceId], "#text");
      this[$appendChild](node);
      node[$content] = this[$content];
      delete this[$content];
    }
  }
  [$toHTML]() {
    if (this[$nodeName] === "#text") {
      return _utils.HTMLResult.success({
        name: "#text",
        value: this[$content]
      });
    }
    return _utils.HTMLResult.EMPTY;
  }
  [$getChildren](name = null) {
    if (!name) {
      return this[_children];
    }
    return this[_children].filter(c => c[$nodeName] === name);
  }
  [$getAttributes]() {
    return this[_attributes];
  }
  [$getChildrenByClass](name) {
    const value = this[_attributes].get(name);
    if (value !== undefined) {
      return value;
    }
    return this[$getChildren](name);
  }
  *[$getChildrenByNameIt](name, allTransparent) {
    const value = this[_attributes].get(name);
    if (value) {
      yield value;
    }
    for (const child of this[_children]) {
      if (child[$nodeName] === name) {
        yield child;
      }
      if (allTransparent) {
        yield* child[$getChildrenByNameIt](name, allTransparent);
      }
    }
  }
  *[$getAttributeIt](name, skipConsumed) {
    const value = this[_attributes].get(name);
    if (value && (!skipConsumed || !value[$consumed])) {
      yield value;
    }
    for (const child of this[_children]) {
      yield* child[$getAttributeIt](name, skipConsumed);
    }
  }
  *[$getRealChildrenByNameIt](name, allTransparent, skipConsumed) {
    for (const child of this[_children]) {
      if (child[$nodeName] === name && (!skipConsumed || !child[$consumed])) {
        yield child;
      }
      if (allTransparent) {
        yield* child[$getRealChildrenByNameIt](name, allTransparent, skipConsumed);
      }
    }
  }
  [$isDataValue]() {
    if (this[_dataValue] === null) {
      return this[_children].length === 0 || this[_children][0][$namespaceId] === _namespaces.NamespaceIds.xhtml.id;
    }
    return this[_dataValue];
  }
  [$getDataValue]() {
    if (this[_dataValue] === null) {
      if (this[_children].length === 0) {
        return this[$content].trim();
      }
      if (this[_children][0][$namespaceId] === _namespaces.NamespaceIds.xhtml.id) {
        return this[_children][0][$text]().trim();
      }
      return null;
    }
    return this[$content].trim();
  }
  [$setValue](value) {
    value = value.value || "";
    this[$content] = value.toString();
  }
  [$dump](hasNS = false) {
    const dumped = Object.create(null);
    if (hasNS) {
      dumped.$ns = this[$namespaceId];
    }
    if (this[$content]) {
      dumped.$content = this[$content];
    }
    dumped.$name = this[$nodeName];
    dumped.children = [];
    for (const child of this[_children]) {
      dumped.children.push(child[$dump](hasNS));
    }
    dumped.attributes = Object.create(null);
    for (const [name, value] of this[_attributes]) {
      dumped.attributes[name] = value[$content];
    }
    return dumped;
  }
}
exports.XmlObject = XmlObject;
class ContentObject extends XFAObject {
  constructor(nsId, name) {
    super(nsId, name);
    this[$content] = "";
  }
  [$onText](text) {
    this[$content] += text;
  }
  [$finalize]() {}
}
exports.ContentObject = ContentObject;
class OptionObject extends ContentObject {
  constructor(nsId, name, options) {
    super(nsId, name);
    this[_options] = options;
  }
  [$finalize]() {
    this[$content] = (0, _utils.getKeyword)({
      data: this[$content],
      defaultValue: this[_options][0],
      validate: k => this[_options].includes(k)
    });
  }
  [$clean](builder) {
    super[$clean](builder);
    delete this[_options];
  }
}
exports.OptionObject = OptionObject;
class StringObject extends ContentObject {
  [$finalize]() {
    this[$content] = this[$content].trim();
  }
}
exports.StringObject = StringObject;
class IntegerObject extends ContentObject {
  constructor(nsId, name, defaultValue, validator) {
    super(nsId, name);
    this[_defaultValue] = defaultValue;
    this[_validator] = validator;
  }
  [$finalize]() {
    this[$content] = (0, _utils.getInteger)({
      data: this[$content],
      defaultValue: this[_defaultValue],
      validate: this[_validator]
    });
  }
  [$clean](builder) {
    super[$clean](builder);
    delete this[_defaultValue];
    delete this[_validator];
  }
}
exports.IntegerObject = IntegerObject;
class Option01 extends IntegerObject {
  constructor(nsId, name) {
    super(nsId, name, 0, n => n === 1);
  }
}
exports.Option01 = Option01;
class Option10 extends IntegerObject {
  constructor(nsId, name) {
    super(nsId, name, 1, n => n === 0);
  }
}
exports.Option10 = Option10;

/***/ }),
/* 76 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.HTMLResult = void 0;
exports.getBBox = getBBox;
exports.getColor = getColor;
exports.getFloat = getFloat;
exports.getInteger = getInteger;
exports.getKeyword = getKeyword;
exports.getMeasurement = getMeasurement;
exports.getRatio = getRatio;
exports.getRelevant = getRelevant;
exports.getStringOption = getStringOption;
exports.stripQuotes = stripQuotes;
var _util = __w_pdfjs_require__(2);
const dimConverters = {
  pt: x => x,
  cm: x => x / 2.54 * 72,
  mm: x => x / (10 * 2.54) * 72,
  in: x => x * 72,
  px: x => x
};
const measurementPattern = /([+-]?\d+\.?\d*)(.*)/;
function stripQuotes(str) {
  if (str.startsWith("'") || str.startsWith('"')) {
    return str.slice(1, str.length - 1);
  }
  return str;
}
function getInteger({
  data,
  defaultValue,
  validate
}) {
  if (!data) {
    return defaultValue;
  }
  data = data.trim();
  const n = parseInt(data, 10);
  if (!isNaN(n) && validate(n)) {
    return n;
  }
  return defaultValue;
}
function getFloat({
  data,
  defaultValue,
  validate
}) {
  if (!data) {
    return defaultValue;
  }
  data = data.trim();
  const n = parseFloat(data);
  if (!isNaN(n) && validate(n)) {
    return n;
  }
  return defaultValue;
}
function getKeyword({
  data,
  defaultValue,
  validate
}) {
  if (!data) {
    return defaultValue;
  }
  data = data.trim();
  if (validate(data)) {
    return data;
  }
  return defaultValue;
}
function getStringOption(data, options) {
  return getKeyword({
    data,
    defaultValue: options[0],
    validate: k => options.includes(k)
  });
}
function getMeasurement(str, def = "0") {
  def = def || "0";
  if (!str) {
    return getMeasurement(def);
  }
  const match = str.trim().match(measurementPattern);
  if (!match) {
    return getMeasurement(def);
  }
  const [, valueStr, unit] = match;
  const value = parseFloat(valueStr);
  if (isNaN(value)) {
    return getMeasurement(def);
  }
  if (value === 0) {
    return 0;
  }
  const conv = dimConverters[unit];
  if (conv) {
    return conv(value);
  }
  return value;
}
function getRatio(data) {
  if (!data) {
    return {
      num: 1,
      den: 1
    };
  }
  const ratio = data.trim().split(/\s*:\s*/).map(x => parseFloat(x)).filter(x => !isNaN(x));
  if (ratio.length === 1) {
    ratio.push(1);
  }
  if (ratio.length === 0) {
    return {
      num: 1,
      den: 1
    };
  }
  const [num, den] = ratio;
  return {
    num,
    den
  };
}
function getRelevant(data) {
  if (!data) {
    return [];
  }
  return data.trim().split(/\s+/).map(e => {
    return {
      excluded: e[0] === "-",
      viewname: e.substring(1)
    };
  });
}
function getColor(data, def = [0, 0, 0]) {
  let [r, g, b] = def;
  if (!data) {
    return {
      r,
      g,
      b
    };
  }
  const color = data.trim().split(/\s*,\s*/).map(c => Math.min(Math.max(0, parseInt(c.trim(), 10)), 255)).map(c => isNaN(c) ? 0 : c);
  if (color.length < 3) {
    return {
      r,
      g,
      b
    };
  }
  [r, g, b] = color;
  return {
    r,
    g,
    b
  };
}
function getBBox(data) {
  const def = -1;
  if (!data) {
    return {
      x: def,
      y: def,
      width: def,
      height: def
    };
  }
  const bbox = data.trim().split(/\s*,\s*/).map(m => getMeasurement(m, "-1"));
  if (bbox.length < 4 || bbox[2] < 0 || bbox[3] < 0) {
    return {
      x: def,
      y: def,
      width: def,
      height: def
    };
  }
  const [x, y, width, height] = bbox;
  return {
    x,
    y,
    width,
    height
  };
}
class HTMLResult {
  static get FAILURE() {
    return (0, _util.shadow)(this, "FAILURE", new HTMLResult(false, null, null, null));
  }
  static get EMPTY() {
    return (0, _util.shadow)(this, "EMPTY", new HTMLResult(true, null, null, null));
  }
  constructor(success, html, bbox, breakNode) {
    this.success = success;
    this.html = html;
    this.bbox = bbox;
    this.breakNode = breakNode;
  }
  isBreak() {
    return !!this.breakNode;
  }
  static breakNode(node) {
    return new HTMLResult(false, null, null, node);
  }
  static success(html, bbox = null) {
    return new HTMLResult(true, html, bbox, null);
  }
}
exports.HTMLResult = HTMLResult;

/***/ }),
/* 77 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.NamespaceIds = exports.$buildXFAObject = void 0;
const $buildXFAObject = Symbol();
exports.$buildXFAObject = $buildXFAObject;
const NamespaceIds = {
  config: {
    id: 0,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xci/")
  },
  connectionSet: {
    id: 1,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-connection-set/")
  },
  datasets: {
    id: 2,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-data/")
  },
  form: {
    id: 3,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-form/")
  },
  localeSet: {
    id: 4,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-locale-set/")
  },
  pdf: {
    id: 5,
    check: ns => ns === "http://ns.adobe.com/xdp/pdf/"
  },
  signature: {
    id: 6,
    check: ns => ns === "http://www.w3.org/2000/09/xmldsig#"
  },
  sourceSet: {
    id: 7,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-source-set/")
  },
  stylesheet: {
    id: 8,
    check: ns => ns === "http://www.w3.org/1999/XSL/Transform"
  },
  template: {
    id: 9,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xfa-template/")
  },
  xdc: {
    id: 10,
    check: ns => ns.startsWith("http://www.xfa.org/schema/xdc/")
  },
  xdp: {
    id: 11,
    check: ns => ns === "http://ns.adobe.com/xdp/"
  },
  xfdf: {
    id: 12,
    check: ns => ns === "http://ns.adobe.com/xfdf/"
  },
  xhtml: {
    id: 13,
    check: ns => ns === "http://www.w3.org/1999/xhtml"
  },
  xmpmeta: {
    id: 14,
    check: ns => ns === "http://ns.adobe.com/xmpmeta/"
  }
};
exports.NamespaceIds = NamespaceIds;

/***/ }),
/* 78 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.createDataNode = createDataNode;
exports.searchNode = searchNode;
var _xfa_object = __w_pdfjs_require__(75);
var _namespaces = __w_pdfjs_require__(77);
var _util = __w_pdfjs_require__(2);
const namePattern = /^[^.[]+/;
const indexPattern = /^[^\]]+/;
const operators = {
  dot: 0,
  dotDot: 1,
  dotHash: 2,
  dotBracket: 3,
  dotParen: 4
};
const shortcuts = new Map([["$data", (root, current) => root.datasets ? root.datasets.data : root], ["$record", (root, current) => (root.datasets ? root.datasets.data : root)[_xfa_object.$getChildren]()[0]], ["$template", (root, current) => root.template], ["$connectionSet", (root, current) => root.connectionSet], ["$form", (root, current) => root.form], ["$layout", (root, current) => root.layout], ["$host", (root, current) => root.host], ["$dataWindow", (root, current) => root.dataWindow], ["$event", (root, current) => root.event], ["!", (root, current) => root.datasets], ["$xfa", (root, current) => root], ["xfa", (root, current) => root], ["$", (root, current) => current]]);
const somCache = new WeakMap();
const NS_DATASETS = _namespaces.NamespaceIds.datasets.id;
function parseIndex(index) {
  index = index.trim();
  if (index === "*") {
    return Infinity;
  }
  return parseInt(index, 10) || 0;
}
function parseExpression(expr, dotDotAllowed, noExpr = true) {
  let match = expr.match(namePattern);
  if (!match) {
    return null;
  }
  let [name] = match;
  const parsed = [{
    name,
    cacheName: "." + name,
    index: 0,
    js: null,
    formCalc: null,
    operator: operators.dot
  }];
  let pos = name.length;
  while (pos < expr.length) {
    const spos = pos;
    const char = expr.charAt(pos++);
    if (char === "[") {
      match = expr.slice(pos).match(indexPattern);
      if (!match) {
        (0, _util.warn)("XFA - Invalid index in SOM expression");
        return null;
      }
      parsed.at(-1).index = parseIndex(match[0]);
      pos += match[0].length + 1;
      continue;
    }
    let operator;
    switch (expr.charAt(pos)) {
      case ".":
        if (!dotDotAllowed) {
          return null;
        }
        pos++;
        operator = operators.dotDot;
        break;
      case "#":
        pos++;
        operator = operators.dotHash;
        break;
      case "[":
        if (noExpr) {
          (0, _util.warn)("XFA - SOM expression contains a FormCalc subexpression which is not supported for now.");
          return null;
        }
        operator = operators.dotBracket;
        break;
      case "(":
        if (noExpr) {
          (0, _util.warn)("XFA - SOM expression contains a JavaScript subexpression which is not supported for now.");
          return null;
        }
        operator = operators.dotParen;
        break;
      default:
        operator = operators.dot;
        break;
    }
    match = expr.slice(pos).match(namePattern);
    if (!match) {
      break;
    }
    [name] = match;
    pos += name.length;
    parsed.push({
      name,
      cacheName: expr.slice(spos, pos),
      operator,
      index: 0,
      js: null,
      formCalc: null
    });
  }
  return parsed;
}
function searchNode(root, container, expr, dotDotAllowed = true, useCache = true) {
  const parsed = parseExpression(expr, dotDotAllowed);
  if (!parsed) {
    return null;
  }
  const fn = shortcuts.get(parsed[0].name);
  let i = 0;
  let isQualified;
  if (fn) {
    isQualified = true;
    root = [fn(root, container)];
    i = 1;
  } else {
    isQualified = container === null;
    root = [container || root];
  }
  for (let ii = parsed.length; i < ii; i++) {
    const {
      name,
      cacheName,
      operator,
      index
    } = parsed[i];
    const nodes = [];
    for (const node of root) {
      if (!(node instanceof _xfa_object.XFAObject)) {
        continue;
      }
      let children, cached;
      if (useCache) {
        cached = somCache.get(node);
        if (!cached) {
          cached = new Map();
          somCache.set(node, cached);
        }
        children = cached.get(cacheName);
      }
      if (!children) {
        switch (operator) {
          case operators.dot:
            children = node[_xfa_object.$getChildrenByName](name, false);
            break;
          case operators.dotDot:
            children = node[_xfa_object.$getChildrenByName](name, true);
            break;
          case operators.dotHash:
            children = node[_xfa_object.$getChildrenByClass](name);
            if (children instanceof _xfa_object.XFAObjectArray) {
              children = children.children;
            } else {
              children = [children];
            }
            break;
          default:
            break;
        }
        if (useCache) {
          cached.set(cacheName, children);
        }
      }
      if (children.length > 0) {
        nodes.push(children);
      }
    }
    if (nodes.length === 0 && !isQualified && i === 0) {
      const parent = container[_xfa_object.$getParent]();
      container = parent;
      if (!container) {
        return null;
      }
      i = -1;
      root = [container];
      continue;
    }
    if (isFinite(index)) {
      root = nodes.filter(node => index < node.length).map(node => node[index]);
    } else {
      root = nodes.flat();
    }
  }
  if (root.length === 0) {
    return null;
  }
  return root;
}
function createNodes(root, path) {
  let node = null;
  for (const {
    name,
    index
  } of path) {
    for (let i = 0, ii = !isFinite(index) ? 0 : index; i <= ii; i++) {
      const nsId = root[_xfa_object.$namespaceId] === NS_DATASETS ? -1 : root[_xfa_object.$namespaceId];
      node = new _xfa_object.XmlObject(nsId, name);
      root[_xfa_object.$appendChild](node);
    }
    root = node;
  }
  return node;
}
function createDataNode(root, container, expr) {
  const parsed = parseExpression(expr);
  if (!parsed) {
    return null;
  }
  if (parsed.some(x => x.operator === operators.dotDot)) {
    return null;
  }
  const fn = shortcuts.get(parsed[0].name);
  let i = 0;
  if (fn) {
    root = fn(root, container);
    i = 1;
  } else {
    root = container || root;
  }
  for (let ii = parsed.length; i < ii; i++) {
    const {
      name,
      operator,
      index
    } = parsed[i];
    if (!isFinite(index)) {
      parsed[i].index = 0;
      return createNodes(root, parsed.slice(i));
    }
    let children;
    switch (operator) {
      case operators.dot:
        children = root[_xfa_object.$getChildrenByName](name, false);
        break;
      case operators.dotDot:
        children = root[_xfa_object.$getChildrenByName](name, true);
        break;
      case operators.dotHash:
        children = root[_xfa_object.$getChildrenByClass](name);
        if (children instanceof _xfa_object.XFAObjectArray) {
          children = children.children;
        } else {
          children = [children];
        }
        break;
      default:
        break;
    }
    if (children.length === 0) {
      return createNodes(root, parsed.slice(i));
    }
    if (index < children.length) {
      const child = children[index];
      if (!(child instanceof _xfa_object.XFAObject)) {
        (0, _util.warn)(`XFA - Cannot create a node.`);
        return null;
      }
      root = child;
    } else {
      parsed[i].index = index - children.length;
      return createNodes(root, parsed.slice(i));
    }
  }
  return null;
}

/***/ }),
/* 79 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Binder = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _template = __w_pdfjs_require__(80);
var _som = __w_pdfjs_require__(78);
var _namespaces = __w_pdfjs_require__(77);
var _util = __w_pdfjs_require__(2);
const NS_DATASETS = _namespaces.NamespaceIds.datasets.id;
function createText(content) {
  const node = new _template.Text({});
  node[_xfa_object.$content] = content;
  return node;
}
class Binder {
  constructor(root) {
    this.root = root;
    this.datasets = root.datasets;
    if (root.datasets && root.datasets.data) {
      this.data = root.datasets.data;
    } else {
      this.data = new _xfa_object.XmlObject(_namespaces.NamespaceIds.datasets.id, "data");
    }
    this.emptyMerge = this.data[_xfa_object.$getChildren]().length === 0;
    this.root.form = this.form = root.template[_xfa_object.$clone]();
  }
  _isConsumeData() {
    return !this.emptyMerge && this._mergeMode;
  }
  _isMatchTemplate() {
    return !this._isConsumeData();
  }
  bind() {
    this._bindElement(this.form, this.data);
    return this.form;
  }
  getData() {
    return this.data;
  }
  _bindValue(formNode, data, picture) {
    formNode[_xfa_object.$data] = data;
    if (formNode[_xfa_object.$hasSettableValue]()) {
      if (data[_xfa_object.$isDataValue]()) {
        const value = data[_xfa_object.$getDataValue]();
        formNode[_xfa_object.$setValue](createText(value));
      } else if (formNode instanceof _template.Field && formNode.ui && formNode.ui.choiceList && formNode.ui.choiceList.open === "multiSelect") {
        const value = data[_xfa_object.$getChildren]().map(child => child[_xfa_object.$content].trim()).join("\n");
        formNode[_xfa_object.$setValue](createText(value));
      } else if (this._isConsumeData()) {
        (0, _util.warn)(`XFA - Nodes haven't the same type.`);
      }
    } else if (!data[_xfa_object.$isDataValue]() || this._isMatchTemplate()) {
      this._bindElement(formNode, data);
    } else {
      (0, _util.warn)(`XFA - Nodes haven't the same type.`);
    }
  }
  _findDataByNameToConsume(name, isValue, dataNode, global) {
    if (!name) {
      return null;
    }
    let generator, match;
    for (let i = 0; i < 3; i++) {
      generator = dataNode[_xfa_object.$getRealChildrenByNameIt](name, false, true);
      while (true) {
        match = generator.next().value;
        if (!match) {
          break;
        }
        if (isValue === match[_xfa_object.$isDataValue]()) {
          return match;
        }
      }
      if (dataNode[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.datasets.id && dataNode[_xfa_object.$nodeName] === "data") {
        break;
      }
      dataNode = dataNode[_xfa_object.$getParent]();
    }
    if (!global) {
      return null;
    }
    generator = this.data[_xfa_object.$getRealChildrenByNameIt](name, true, false);
    match = generator.next().value;
    if (match) {
      return match;
    }
    generator = this.data[_xfa_object.$getAttributeIt](name, true);
    match = generator.next().value;
    if (match && match[_xfa_object.$isDataValue]()) {
      return match;
    }
    return null;
  }
  _setProperties(formNode, dataNode) {
    if (!formNode.hasOwnProperty("setProperty")) {
      return;
    }
    for (const {
      ref,
      target,
      connection
    } of formNode.setProperty.children) {
      if (connection) {
        continue;
      }
      if (!ref) {
        continue;
      }
      const nodes = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
      if (!nodes) {
        (0, _util.warn)(`XFA - Invalid reference: ${ref}.`);
        continue;
      }
      const [node] = nodes;
      if (!node[_xfa_object.$isDescendent](this.data)) {
        (0, _util.warn)(`XFA - Invalid node: must be a data node.`);
        continue;
      }
      const targetNodes = (0, _som.searchNode)(this.root, formNode, target, false, false);
      if (!targetNodes) {
        (0, _util.warn)(`XFA - Invalid target: ${target}.`);
        continue;
      }
      const [targetNode] = targetNodes;
      if (!targetNode[_xfa_object.$isDescendent](formNode)) {
        (0, _util.warn)(`XFA - Invalid target: must be a property or subproperty.`);
        continue;
      }
      const targetParent = targetNode[_xfa_object.$getParent]();
      if (targetNode instanceof _template.SetProperty || targetParent instanceof _template.SetProperty) {
        (0, _util.warn)(`XFA - Invalid target: cannot be a setProperty or one of its properties.`);
        continue;
      }
      if (targetNode instanceof _template.BindItems || targetParent instanceof _template.BindItems) {
        (0, _util.warn)(`XFA - Invalid target: cannot be a bindItems or one of its properties.`);
        continue;
      }
      const content = node[_xfa_object.$text]();
      const name = targetNode[_xfa_object.$nodeName];
      if (targetNode instanceof _xfa_object.XFAAttribute) {
        const attrs = Object.create(null);
        attrs[name] = content;
        const obj = Reflect.construct(Object.getPrototypeOf(targetParent).constructor, [attrs]);
        targetParent[name] = obj[name];
        continue;
      }
      if (!targetNode.hasOwnProperty(_xfa_object.$content)) {
        (0, _util.warn)(`XFA - Invalid node to use in setProperty`);
        continue;
      }
      targetNode[_xfa_object.$data] = node;
      targetNode[_xfa_object.$content] = content;
      targetNode[_xfa_object.$finalize]();
    }
  }
  _bindItems(formNode, dataNode) {
    if (!formNode.hasOwnProperty("items") || !formNode.hasOwnProperty("bindItems") || formNode.bindItems.isEmpty()) {
      return;
    }
    for (const item of formNode.items.children) {
      formNode[_xfa_object.$removeChild](item);
    }
    formNode.items.clear();
    const labels = new _template.Items({});
    const values = new _template.Items({});
    formNode[_xfa_object.$appendChild](labels);
    formNode.items.push(labels);
    formNode[_xfa_object.$appendChild](values);
    formNode.items.push(values);
    for (const {
      ref,
      labelRef,
      valueRef,
      connection
    } of formNode.bindItems.children) {
      if (connection) {
        continue;
      }
      if (!ref) {
        continue;
      }
      const nodes = (0, _som.searchNode)(this.root, dataNode, ref, false, false);
      if (!nodes) {
        (0, _util.warn)(`XFA - Invalid reference: ${ref}.`);
        continue;
      }
      for (const node of nodes) {
        if (!node[_xfa_object.$isDescendent](this.datasets)) {
          (0, _util.warn)(`XFA - Invalid ref (${ref}): must be a datasets child.`);
          continue;
        }
        const labelNodes = (0, _som.searchNode)(this.root, node, labelRef, true, false);
        if (!labelNodes) {
          (0, _util.warn)(`XFA - Invalid label: ${labelRef}.`);
          continue;
        }
        const [labelNode] = labelNodes;
        if (!labelNode[_xfa_object.$isDescendent](this.datasets)) {
          (0, _util.warn)(`XFA - Invalid label: must be a datasets child.`);
          continue;
        }
        const valueNodes = (0, _som.searchNode)(this.root, node, valueRef, true, false);
        if (!valueNodes) {
          (0, _util.warn)(`XFA - Invalid value: ${valueRef}.`);
          continue;
        }
        const [valueNode] = valueNodes;
        if (!valueNode[_xfa_object.$isDescendent](this.datasets)) {
          (0, _util.warn)(`XFA - Invalid value: must be a datasets child.`);
          continue;
        }
        const label = createText(labelNode[_xfa_object.$text]());
        const value = createText(valueNode[_xfa_object.$text]());
        labels[_xfa_object.$appendChild](label);
        labels.text.push(label);
        values[_xfa_object.$appendChild](value);
        values.text.push(value);
      }
    }
  }
  _bindOccurrences(formNode, matches, picture) {
    let baseClone;
    if (matches.length > 1) {
      baseClone = formNode[_xfa_object.$clone]();
      baseClone[_xfa_object.$removeChild](baseClone.occur);
      baseClone.occur = null;
    }
    this._bindValue(formNode, matches[0], picture);
    this._setProperties(formNode, matches[0]);
    this._bindItems(formNode, matches[0]);
    if (matches.length === 1) {
      return;
    }
    const parent = formNode[_xfa_object.$getParent]();
    const name = formNode[_xfa_object.$nodeName];
    const pos = parent[_xfa_object.$indexOf](formNode);
    for (let i = 1, ii = matches.length; i < ii; i++) {
      const match = matches[i];
      const clone = baseClone[_xfa_object.$clone]();
      parent[name].push(clone);
      parent[_xfa_object.$insertAt](pos + i, clone);
      this._bindValue(clone, match, picture);
      this._setProperties(clone, match);
      this._bindItems(clone, match);
    }
  }
  _createOccurrences(formNode) {
    if (!this.emptyMerge) {
      return;
    }
    const {
      occur
    } = formNode;
    if (!occur || occur.initial <= 1) {
      return;
    }
    const parent = formNode[_xfa_object.$getParent]();
    const name = formNode[_xfa_object.$nodeName];
    if (!(parent[name] instanceof _xfa_object.XFAObjectArray)) {
      return;
    }
    let currentNumber;
    if (formNode.name) {
      currentNumber = parent[name].children.filter(e => e.name === formNode.name).length;
    } else {
      currentNumber = parent[name].children.length;
    }
    const pos = parent[_xfa_object.$indexOf](formNode) + 1;
    const ii = occur.initial - currentNumber;
    if (ii) {
      const nodeClone = formNode[_xfa_object.$clone]();
      nodeClone[_xfa_object.$removeChild](nodeClone.occur);
      nodeClone.occur = null;
      parent[name].push(nodeClone);
      parent[_xfa_object.$insertAt](pos, nodeClone);
      for (let i = 1; i < ii; i++) {
        const clone = nodeClone[_xfa_object.$clone]();
        parent[name].push(clone);
        parent[_xfa_object.$insertAt](pos + i, clone);
      }
    }
  }
  _getOccurInfo(formNode) {
    const {
      name,
      occur
    } = formNode;
    if (!occur || !name) {
      return [1, 1];
    }
    const max = occur.max === -1 ? Infinity : occur.max;
    return [occur.min, max];
  }
  _setAndBind(formNode, dataNode) {
    this._setProperties(formNode, dataNode);
    this._bindItems(formNode, dataNode);
    this._bindElement(formNode, dataNode);
  }
  _bindElement(formNode, dataNode) {
    const uselessNodes = [];
    this._createOccurrences(formNode);
    for (const child of formNode[_xfa_object.$getChildren]()) {
      if (child[_xfa_object.$data]) {
        continue;
      }
      if (this._mergeMode === undefined && child[_xfa_object.$nodeName] === "subform") {
        this._mergeMode = child.mergeMode === "consumeData";
        const dataChildren = dataNode[_xfa_object.$getChildren]();
        if (dataChildren.length > 0) {
          this._bindOccurrences(child, [dataChildren[0]], null);
        } else if (this.emptyMerge) {
          const nsId = dataNode[_xfa_object.$namespaceId] === NS_DATASETS ? -1 : dataNode[_xfa_object.$namespaceId];
          const dataChild = child[_xfa_object.$data] = new _xfa_object.XmlObject(nsId, child.name || "root");
          dataNode[_xfa_object.$appendChild](dataChild);
          this._bindElement(child, dataChild);
        }
        continue;
      }
      if (!child[_xfa_object.$isBindable]()) {
        continue;
      }
      let global = false;
      let picture = null;
      let ref = null;
      let match = null;
      if (child.bind) {
        switch (child.bind.match) {
          case "none":
            this._setAndBind(child, dataNode);
            continue;
          case "global":
            global = true;
            break;
          case "dataRef":
            if (!child.bind.ref) {
              (0, _util.warn)(`XFA - ref is empty in node ${child[_xfa_object.$nodeName]}.`);
              this._setAndBind(child, dataNode);
              continue;
            }
            ref = child.bind.ref;
            break;
          default:
            break;
        }
        if (child.bind.picture) {
          picture = child.bind.picture[_xfa_object.$content];
        }
      }
      const [min, max] = this._getOccurInfo(child);
      if (ref) {
        match = (0, _som.searchNode)(this.root, dataNode, ref, true, false);
        if (match === null) {
          match = (0, _som.createDataNode)(this.data, dataNode, ref);
          if (!match) {
            continue;
          }
          if (this._isConsumeData()) {
            match[_xfa_object.$consumed] = true;
          }
          this._setAndBind(child, match);
          continue;
        } else {
          if (this._isConsumeData()) {
            match = match.filter(node => !node[_xfa_object.$consumed]);
          }
          if (match.length > max) {
            match = match.slice(0, max);
          } else if (match.length === 0) {
            match = null;
          }
          if (match && this._isConsumeData()) {
            match.forEach(node => {
              node[_xfa_object.$consumed] = true;
            });
          }
        }
      } else {
        if (!child.name) {
          this._setAndBind(child, dataNode);
          continue;
        }
        if (this._isConsumeData()) {
          const matches = [];
          while (matches.length < max) {
            const found = this._findDataByNameToConsume(child.name, child[_xfa_object.$hasSettableValue](), dataNode, global);
            if (!found) {
              break;
            }
            found[_xfa_object.$consumed] = true;
            matches.push(found);
          }
          match = matches.length > 0 ? matches : null;
        } else {
          match = dataNode[_xfa_object.$getRealChildrenByNameIt](child.name, false, this.emptyMerge).next().value;
          if (!match) {
            if (min === 0) {
              uselessNodes.push(child);
              continue;
            }
            const nsId = dataNode[_xfa_object.$namespaceId] === NS_DATASETS ? -1 : dataNode[_xfa_object.$namespaceId];
            match = child[_xfa_object.$data] = new _xfa_object.XmlObject(nsId, child.name);
            if (this.emptyMerge) {
              match[_xfa_object.$consumed] = true;
            }
            dataNode[_xfa_object.$appendChild](match);
            this._setAndBind(child, match);
            continue;
          }
          if (this.emptyMerge) {
            match[_xfa_object.$consumed] = true;
          }
          match = [match];
        }
      }
      if (match) {
        this._bindOccurrences(child, match, picture);
      } else if (min > 0) {
        this._setAndBind(child, dataNode);
      } else {
        uselessNodes.push(child);
      }
    }
    uselessNodes.forEach(node => node[_xfa_object.$getParent]()[_xfa_object.$removeChild](node));
  }
}
exports.Binder = Binder;

/***/ }),
/* 80 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Value = exports.Text = exports.TemplateNamespace = exports.Template = exports.SetProperty = exports.Items = exports.Field = exports.BindItems = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _namespaces = __w_pdfjs_require__(77);
var _layout = __w_pdfjs_require__(81);
var _html_utils = __w_pdfjs_require__(82);
var _utils = __w_pdfjs_require__(76);
var _util = __w_pdfjs_require__(2);
var _fonts = __w_pdfjs_require__(83);
var _core_utils = __w_pdfjs_require__(4);
var _som = __w_pdfjs_require__(78);
const TEMPLATE_NS_ID = _namespaces.NamespaceIds.template.id;
const SVG_NS = "http://www.w3.org/2000/svg";
const MAX_ATTEMPTS_FOR_LRTB_LAYOUT = 2;
const MAX_EMPTY_PAGES = 3;
const DEFAULT_TAB_INDEX = 5000;
const HEADING_PATTERN = /^H(\d+)$/;
const MIMES = new Set(["image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/png", "image/apng", "image/x-png", "image/bmp", "image/x-ms-bmp", "image/tiff", "image/tif", "application/octet-stream"]);
const IMAGES_HEADERS = [[[0x42, 0x4d], "image/bmp"], [[0xff, 0xd8, 0xff], "image/jpeg"], [[0x49, 0x49, 0x2a, 0x00], "image/tiff"], [[0x4d, 0x4d, 0x00, 0x2a], "image/tiff"], [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61], "image/gif"], [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], "image/png"]];
function getBorderDims(node) {
  if (!node || !node.border) {
    return {
      w: 0,
      h: 0
    };
  }
  const borderExtra = node.border[_xfa_object.$getExtra]();
  if (!borderExtra) {
    return {
      w: 0,
      h: 0
    };
  }
  return {
    w: borderExtra.widths[0] + borderExtra.widths[2] + borderExtra.insets[0] + borderExtra.insets[2],
    h: borderExtra.widths[1] + borderExtra.widths[3] + borderExtra.insets[1] + borderExtra.insets[3]
  };
}
function hasMargin(node) {
  return node.margin && (node.margin.topInset || node.margin.rightInset || node.margin.bottomInset || node.margin.leftInset);
}
function _setValue(templateNode, value) {
  if (!templateNode.value) {
    const nodeValue = new Value({});
    templateNode[_xfa_object.$appendChild](nodeValue);
    templateNode.value = nodeValue;
  }
  templateNode.value[_xfa_object.$setValue](value);
}
function* getContainedChildren(node) {
  for (const child of node[_xfa_object.$getChildren]()) {
    if (child instanceof SubformSet) {
      yield* child[_xfa_object.$getContainedChildren]();
      continue;
    }
    yield child;
  }
}
function isRequired(node) {
  return node.validate && node.validate.nullTest === "error";
}
function setTabIndex(node) {
  while (node) {
    if (!node.traversal) {
      node[_xfa_object.$tabIndex] = node[_xfa_object.$getParent]()[_xfa_object.$tabIndex];
      return;
    }
    if (node[_xfa_object.$tabIndex]) {
      return;
    }
    let next = null;
    for (const child of node.traversal[_xfa_object.$getChildren]()) {
      if (child.operation === "next") {
        next = child;
        break;
      }
    }
    if (!next || !next.ref) {
      node[_xfa_object.$tabIndex] = node[_xfa_object.$getParent]()[_xfa_object.$tabIndex];
      return;
    }
    const root = node[_xfa_object.$getTemplateRoot]();
    node[_xfa_object.$tabIndex] = ++root[_xfa_object.$tabIndex];
    const ref = root[_xfa_object.$searchNode](next.ref, node);
    if (!ref) {
      return;
    }
    node = ref[0];
  }
}
function applyAssist(obj, attributes) {
  const assist = obj.assist;
  if (assist) {
    const assistTitle = assist[_xfa_object.$toHTML]();
    if (assistTitle) {
      attributes.title = assistTitle;
    }
    const role = assist.role;
    const match = role.match(HEADING_PATTERN);
    if (match) {
      const ariaRole = "heading";
      const ariaLevel = match[1];
      attributes.role = ariaRole;
      attributes["aria-level"] = ariaLevel;
    }
  }
  if (obj.layout === "table") {
    attributes.role = "table";
  } else if (obj.layout === "row") {
    attributes.role = "row";
  } else {
    const parent = obj[_xfa_object.$getParent]();
    if (parent.layout === "row") {
      if (parent.assist && parent.assist.role === "TH") {
        attributes.role = "columnheader";
      } else {
        attributes.role = "cell";
      }
    }
  }
}
function ariaLabel(obj) {
  if (!obj.assist) {
    return null;
  }
  const assist = obj.assist;
  if (assist.speak && assist.speak[_xfa_object.$content] !== "") {
    return assist.speak[_xfa_object.$content];
  }
  if (assist.toolTip) {
    return assist.toolTip[_xfa_object.$content];
  }
  return null;
}
function valueToHtml(value) {
  return _utils.HTMLResult.success({
    name: "div",
    attributes: {
      class: ["xfaRich"],
      style: Object.create(null)
    },
    children: [{
      name: "span",
      attributes: {
        style: Object.create(null)
      },
      value
    }]
  });
}
function setFirstUnsplittable(node) {
  const root = node[_xfa_object.$getTemplateRoot]();
  if (root[_xfa_object.$extra].firstUnsplittable === null) {
    root[_xfa_object.$extra].firstUnsplittable = node;
    root[_xfa_object.$extra].noLayoutFailure = true;
  }
}
function unsetFirstUnsplittable(node) {
  const root = node[_xfa_object.$getTemplateRoot]();
  if (root[_xfa_object.$extra].firstUnsplittable === node) {
    root[_xfa_object.$extra].noLayoutFailure = false;
  }
}
function handleBreak(node) {
  if (node[_xfa_object.$extra]) {
    return false;
  }
  node[_xfa_object.$extra] = Object.create(null);
  if (node.targetType === "auto") {
    return false;
  }
  const root = node[_xfa_object.$getTemplateRoot]();
  let target = null;
  if (node.target) {
    target = root[_xfa_object.$searchNode](node.target, node[_xfa_object.$getParent]());
    if (!target) {
      return false;
    }
    target = target[0];
  }
  const {
    currentPageArea,
    currentContentArea
  } = root[_xfa_object.$extra];
  if (node.targetType === "pageArea") {
    if (!(target instanceof PageArea)) {
      target = null;
    }
    if (node.startNew) {
      node[_xfa_object.$extra].target = target || currentPageArea;
      return true;
    } else if (target && target !== currentPageArea) {
      node[_xfa_object.$extra].target = target;
      return true;
    }
    return false;
  }
  if (!(target instanceof ContentArea)) {
    target = null;
  }
  const pageArea = target && target[_xfa_object.$getParent]();
  let index;
  let nextPageArea = pageArea;
  if (node.startNew) {
    if (target) {
      const contentAreas = pageArea.contentArea.children;
      const indexForCurrent = contentAreas.indexOf(currentContentArea);
      const indexForTarget = contentAreas.indexOf(target);
      if (indexForCurrent !== -1 && indexForCurrent < indexForTarget) {
        nextPageArea = null;
      }
      index = indexForTarget - 1;
    } else {
      index = currentPageArea.contentArea.children.indexOf(currentContentArea);
    }
  } else if (target && target !== currentContentArea) {
    const contentAreas = pageArea.contentArea.children;
    index = contentAreas.indexOf(target) - 1;
    nextPageArea = pageArea === currentPageArea ? null : pageArea;
  } else {
    return false;
  }
  node[_xfa_object.$extra].target = nextPageArea;
  node[_xfa_object.$extra].index = index;
  return true;
}
function handleOverflow(node, extraNode, space) {
  const root = node[_xfa_object.$getTemplateRoot]();
  const saved = root[_xfa_object.$extra].noLayoutFailure;
  const savedMethod = extraNode[_xfa_object.$getSubformParent];
  extraNode[_xfa_object.$getSubformParent] = () => node;
  root[_xfa_object.$extra].noLayoutFailure = true;
  const res = extraNode[_xfa_object.$toHTML](space);
  node[_xfa_object.$addHTML](res.html, res.bbox);
  root[_xfa_object.$extra].noLayoutFailure = saved;
  extraNode[_xfa_object.$getSubformParent] = savedMethod;
}
class AppearanceFilter extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "appearanceFilter");
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Arc extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "arc", true);
    this.circular = (0, _utils.getInteger)({
      data: attributes.circular,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.hand = (0, _utils.getStringOption)(attributes.hand, ["even", "left", "right"]);
    this.id = attributes.id || "";
    this.startAngle = (0, _utils.getFloat)({
      data: attributes.startAngle,
      defaultValue: 0,
      validate: x => true
    });
    this.sweepAngle = (0, _utils.getFloat)({
      data: attributes.sweepAngle,
      defaultValue: 360,
      validate: x => true
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.edge = null;
    this.fill = null;
  }
  [_xfa_object.$toHTML]() {
    const edge = this.edge || new Edge({});
    const edgeStyle = edge[_xfa_object.$toStyle]();
    const style = Object.create(null);
    if (this.fill && this.fill.presence === "visible") {
      Object.assign(style, this.fill[_xfa_object.$toStyle]());
    } else {
      style.fill = "transparent";
    }
    style.strokeWidth = (0, _html_utils.measureToString)(edge.presence === "visible" ? edge.thickness : 0);
    style.stroke = edgeStyle.color;
    let arc;
    const attributes = {
      xmlns: SVG_NS,
      style: {
        width: "100%",
        height: "100%",
        overflow: "visible"
      }
    };
    if (this.sweepAngle === 360) {
      arc = {
        name: "ellipse",
        attributes: {
          xmlns: SVG_NS,
          cx: "50%",
          cy: "50%",
          rx: "50%",
          ry: "50%",
          style
        }
      };
    } else {
      const startAngle = this.startAngle * Math.PI / 180;
      const sweepAngle = this.sweepAngle * Math.PI / 180;
      const largeArc = this.sweepAngle > 180 ? 1 : 0;
      const [x1, y1, x2, y2] = [50 * (1 + Math.cos(startAngle)), 50 * (1 - Math.sin(startAngle)), 50 * (1 + Math.cos(startAngle + sweepAngle)), 50 * (1 - Math.sin(startAngle + sweepAngle))];
      arc = {
        name: "path",
        attributes: {
          xmlns: SVG_NS,
          d: `M ${x1} ${y1} A 50 50 0 ${largeArc} 0 ${x2} ${y2}`,
          vectorEffect: "non-scaling-stroke",
          style
        }
      };
      Object.assign(attributes, {
        viewBox: "0 0 100 100",
        preserveAspectRatio: "none"
      });
    }
    const svg = {
      name: "svg",
      children: [arc],
      attributes
    };
    const parent = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    if (hasMargin(parent)) {
      return _utils.HTMLResult.success({
        name: "div",
        attributes: {
          style: {
            display: "inline",
            width: "100%",
            height: "100%"
          }
        },
        children: [svg]
      });
    }
    svg.attributes.style.position = "absolute";
    return _utils.HTMLResult.success(svg);
  }
}
class Area extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "area", true);
    this.colSpan = (0, _utils.getInteger)({
      data: attributes.colSpan,
      defaultValue: 1,
      validate: n => n >= 1 || n === -1
    });
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.desc = null;
    this.extras = null;
    this.area = new _xfa_object.XFAObjectArray();
    this.draw = new _xfa_object.XFAObjectArray();
    this.exObject = new _xfa_object.XFAObjectArray();
    this.exclGroup = new _xfa_object.XFAObjectArray();
    this.field = new _xfa_object.XFAObjectArray();
    this.subform = new _xfa_object.XFAObjectArray();
    this.subformSet = new _xfa_object.XFAObjectArray();
  }
  *[_xfa_object.$getContainedChildren]() {
    yield* getContainedChildren(this);
  }
  [_xfa_object.$isTransparent]() {
    return true;
  }
  [_xfa_object.$isBindable]() {
    return true;
  }
  [_xfa_object.$addHTML](html, bbox) {
    const [x, y, w, h] = bbox;
    this[_xfa_object.$extra].width = Math.max(this[_xfa_object.$extra].width, x + w);
    this[_xfa_object.$extra].height = Math.max(this[_xfa_object.$extra].height, y + h);
    this[_xfa_object.$extra].children.push(html);
  }
  [_xfa_object.$getAvailableSpace]() {
    return this[_xfa_object.$extra].availableSpace;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)(this, "position");
    const attributes = {
      style,
      id: this[_xfa_object.$uid],
      class: ["xfaArea"]
    };
    if ((0, _html_utils.isPrintOnly)(this)) {
      attributes.class.push("xfaPrintOnly");
    }
    if (this.name) {
      attributes.xfaName = this.name;
    }
    const children = [];
    this[_xfa_object.$extra] = {
      children,
      width: 0,
      height: 0,
      availableSpace
    };
    const result = this[_xfa_object.$childrenToHTML]({
      filter: new Set(["area", "draw", "field", "exclGroup", "subform", "subformSet"]),
      include: true
    });
    if (!result.success) {
      if (result.isBreak()) {
        return result;
      }
      delete this[_xfa_object.$extra];
      return _utils.HTMLResult.FAILURE;
    }
    style.width = (0, _html_utils.measureToString)(this[_xfa_object.$extra].width);
    style.height = (0, _html_utils.measureToString)(this[_xfa_object.$extra].height);
    const html = {
      name: "div",
      attributes,
      children
    };
    const bbox = [this.x, this.y, this[_xfa_object.$extra].width, this[_xfa_object.$extra].height];
    delete this[_xfa_object.$extra];
    return _utils.HTMLResult.success(html, bbox);
  }
}
class Assist extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "assist", true);
    this.id = attributes.id || "";
    this.role = attributes.role || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.speak = null;
    this.toolTip = null;
  }
  [_xfa_object.$toHTML]() {
    return this.toolTip && this.toolTip[_xfa_object.$content] ? this.toolTip[_xfa_object.$content] : null;
  }
}
class Barcode extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "barcode", true);
    this.charEncoding = (0, _utils.getKeyword)({
      data: attributes.charEncoding ? attributes.charEncoding.toLowerCase() : "",
      defaultValue: "",
      validate: k => ["utf-8", "big-five", "fontspecific", "gbk", "gb-18030", "gb-2312", "ksc-5601", "none", "shift-jis", "ucs-2", "utf-16"].includes(k) || k.match(/iso-8859-\d{2}/)
    });
    this.checksum = (0, _utils.getStringOption)(attributes.checksum, ["none", "1mod10", "1mod10_1mod11", "2mod10", "auto"]);
    this.dataColumnCount = (0, _utils.getInteger)({
      data: attributes.dataColumnCount,
      defaultValue: -1,
      validate: x => x >= 0
    });
    this.dataLength = (0, _utils.getInteger)({
      data: attributes.dataLength,
      defaultValue: -1,
      validate: x => x >= 0
    });
    this.dataPrep = (0, _utils.getStringOption)(attributes.dataPrep, ["none", "flateCompress"]);
    this.dataRowCount = (0, _utils.getInteger)({
      data: attributes.dataRowCount,
      defaultValue: -1,
      validate: x => x >= 0
    });
    this.endChar = attributes.endChar || "";
    this.errorCorrectionLevel = (0, _utils.getInteger)({
      data: attributes.errorCorrectionLevel,
      defaultValue: -1,
      validate: x => x >= 0 && x <= 8
    });
    this.id = attributes.id || "";
    this.moduleHeight = (0, _utils.getMeasurement)(attributes.moduleHeight, "5mm");
    this.moduleWidth = (0, _utils.getMeasurement)(attributes.moduleWidth, "0.25mm");
    this.printCheckDigit = (0, _utils.getInteger)({
      data: attributes.printCheckDigit,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.rowColumnRatio = (0, _utils.getRatio)(attributes.rowColumnRatio);
    this.startChar = attributes.startChar || "";
    this.textLocation = (0, _utils.getStringOption)(attributes.textLocation, ["below", "above", "aboveEmbedded", "belowEmbedded", "none"]);
    this.truncate = (0, _utils.getInteger)({
      data: attributes.truncate,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.type = (0, _utils.getStringOption)(attributes.type ? attributes.type.toLowerCase() : "", ["aztec", "codabar", "code2of5industrial", "code2of5interleaved", "code2of5matrix", "code2of5standard", "code3of9", "code3of9extended", "code11", "code49", "code93", "code128", "code128a", "code128b", "code128c", "code128sscc", "datamatrix", "ean8", "ean8add2", "ean8add5", "ean13", "ean13add2", "ean13add5", "ean13pwcd", "fim", "logmars", "maxicode", "msi", "pdf417", "pdf417macro", "plessey", "postauscust2", "postauscust3", "postausreplypaid", "postausstandard", "postukrm4scc", "postusdpbc", "postusimb", "postusstandard", "postus5zip", "qrcode", "rfid", "rss14", "rss14expanded", "rss14limited", "rss14stacked", "rss14stackedomni", "rss14truncated", "telepen", "ucc128", "ucc128random", "ucc128sscc", "upca", "upcaadd2", "upcaadd5", "upcapwcd", "upce", "upceadd2", "upceadd5", "upcean2", "upcean5", "upsmaxicode"]);
    this.upsMode = (0, _utils.getStringOption)(attributes.upsMode, ["usCarrier", "internationalCarrier", "secureSymbol", "standardSymbol"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.wideNarrowRatio = (0, _utils.getRatio)(attributes.wideNarrowRatio);
    this.encrypt = null;
    this.extras = null;
  }
}
class Bind extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "bind", true);
    this.match = (0, _utils.getStringOption)(attributes.match, ["once", "dataRef", "global", "none"]);
    this.ref = attributes.ref || "";
    this.picture = null;
  }
}
class BindItems extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "bindItems");
    this.connection = attributes.connection || "";
    this.labelRef = attributes.labelRef || "";
    this.ref = attributes.ref || "";
    this.valueRef = attributes.valueRef || "";
  }
}
exports.BindItems = BindItems;
class Bookend extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "bookend");
    this.id = attributes.id || "";
    this.leader = attributes.leader || "";
    this.trailer = attributes.trailer || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class BooleanElement extends _xfa_object.Option01 {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "boolean");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] === 1 ? "1" : "0");
  }
}
class Border extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "border", true);
    this.break = (0, _utils.getStringOption)(attributes.break, ["close", "open"]);
    this.hand = (0, _utils.getStringOption)(attributes.hand, ["even", "left", "right"]);
    this.id = attributes.id || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.corner = new _xfa_object.XFAObjectArray(4);
    this.edge = new _xfa_object.XFAObjectArray(4);
    this.extras = null;
    this.fill = null;
    this.margin = null;
  }
  [_xfa_object.$getExtra]() {
    if (!this[_xfa_object.$extra]) {
      const edges = this.edge.children.slice();
      if (edges.length < 4) {
        const defaultEdge = edges.at(-1) || new Edge({});
        for (let i = edges.length; i < 4; i++) {
          edges.push(defaultEdge);
        }
      }
      const widths = edges.map(edge => edge.thickness);
      const insets = [0, 0, 0, 0];
      if (this.margin) {
        insets[0] = this.margin.topInset;
        insets[1] = this.margin.rightInset;
        insets[2] = this.margin.bottomInset;
        insets[3] = this.margin.leftInset;
      }
      this[_xfa_object.$extra] = {
        widths,
        insets,
        edges
      };
    }
    return this[_xfa_object.$extra];
  }
  [_xfa_object.$toStyle]() {
    const {
      edges
    } = this[_xfa_object.$getExtra]();
    const edgeStyles = edges.map(node => {
      const style = node[_xfa_object.$toStyle]();
      style.color = style.color || "#000000";
      return style;
    });
    const style = Object.create(null);
    if (this.margin) {
      Object.assign(style, this.margin[_xfa_object.$toStyle]());
    }
    if (this.fill && this.fill.presence === "visible") {
      Object.assign(style, this.fill[_xfa_object.$toStyle]());
    }
    if (this.corner.children.some(node => node.radius !== 0)) {
      const cornerStyles = this.corner.children.map(node => node[_xfa_object.$toStyle]());
      if (cornerStyles.length === 2 || cornerStyles.length === 3) {
        const last = cornerStyles.at(-1);
        for (let i = cornerStyles.length; i < 4; i++) {
          cornerStyles.push(last);
        }
      }
      style.borderRadius = cornerStyles.map(s => s.radius).join(" ");
    }
    switch (this.presence) {
      case "invisible":
      case "hidden":
        style.borderStyle = "";
        break;
      case "inactive":
        style.borderStyle = "none";
        break;
      default:
        style.borderStyle = edgeStyles.map(s => s.style).join(" ");
        break;
    }
    style.borderWidth = edgeStyles.map(s => s.width).join(" ");
    style.borderColor = edgeStyles.map(s => s.color).join(" ");
    return style;
  }
}
class Break extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "break", true);
    this.after = (0, _utils.getStringOption)(attributes.after, ["auto", "contentArea", "pageArea", "pageEven", "pageOdd"]);
    this.afterTarget = attributes.afterTarget || "";
    this.before = (0, _utils.getStringOption)(attributes.before, ["auto", "contentArea", "pageArea", "pageEven", "pageOdd"]);
    this.beforeTarget = attributes.beforeTarget || "";
    this.bookendLeader = attributes.bookendLeader || "";
    this.bookendTrailer = attributes.bookendTrailer || "";
    this.id = attributes.id || "";
    this.overflowLeader = attributes.overflowLeader || "";
    this.overflowTarget = attributes.overflowTarget || "";
    this.overflowTrailer = attributes.overflowTrailer || "";
    this.startNew = (0, _utils.getInteger)({
      data: attributes.startNew,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
}
class BreakAfter extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "breakAfter", true);
    this.id = attributes.id || "";
    this.leader = attributes.leader || "";
    this.startNew = (0, _utils.getInteger)({
      data: attributes.startNew,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.target = attributes.target || "";
    this.targetType = (0, _utils.getStringOption)(attributes.targetType, ["auto", "contentArea", "pageArea"]);
    this.trailer = attributes.trailer || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.script = null;
  }
}
class BreakBefore extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "breakBefore", true);
    this.id = attributes.id || "";
    this.leader = attributes.leader || "";
    this.startNew = (0, _utils.getInteger)({
      data: attributes.startNew,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.target = attributes.target || "";
    this.targetType = (0, _utils.getStringOption)(attributes.targetType, ["auto", "contentArea", "pageArea"]);
    this.trailer = attributes.trailer || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.script = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    this[_xfa_object.$extra] = {};
    return _utils.HTMLResult.FAILURE;
  }
}
class Button extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "button", true);
    this.highlight = (0, _utils.getStringOption)(attributes.highlight, ["inverted", "none", "outline", "push"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const parent = this[_xfa_object.$getParent]();
    const grandpa = parent[_xfa_object.$getParent]();
    const htmlButton = {
      name: "button",
      attributes: {
        id: this[_xfa_object.$uid],
        class: ["xfaButton"],
        style: {}
      },
      children: []
    };
    for (const event of grandpa.event.children) {
      if (event.activity !== "click" || !event.script) {
        continue;
      }
      const jsURL = (0, _core_utils.recoverJsURL)(event.script[_xfa_object.$content]);
      if (!jsURL) {
        continue;
      }
      const href = (0, _html_utils.fixURL)(jsURL.url);
      if (!href) {
        continue;
      }
      htmlButton.children.push({
        name: "a",
        attributes: {
          id: "link" + this[_xfa_object.$uid],
          href,
          newWindow: jsURL.newWindow,
          class: ["xfaLink"],
          style: {}
        },
        children: []
      });
    }
    return _utils.HTMLResult.success(htmlButton);
  }
}
class Calculate extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "calculate", true);
    this.id = attributes.id || "";
    this.override = (0, _utils.getStringOption)(attributes.override, ["disabled", "error", "ignore", "warning"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.message = null;
    this.script = null;
  }
}
class Caption extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "caption", true);
    this.id = attributes.id || "";
    this.placement = (0, _utils.getStringOption)(attributes.placement, ["left", "bottom", "inline", "right", "top"]);
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.reserve = Math.ceil((0, _utils.getMeasurement)(attributes.reserve));
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.font = null;
    this.margin = null;
    this.para = null;
    this.value = null;
  }
  [_xfa_object.$setValue](value) {
    _setValue(this, value);
  }
  [_xfa_object.$getExtra](availableSpace) {
    if (!this[_xfa_object.$extra]) {
      let {
        width,
        height
      } = availableSpace;
      switch (this.placement) {
        case "left":
        case "right":
        case "inline":
          width = this.reserve <= 0 ? width : this.reserve;
          break;
        case "top":
        case "bottom":
          height = this.reserve <= 0 ? height : this.reserve;
          break;
      }
      this[_xfa_object.$extra] = (0, _html_utils.layoutNode)(this, {
        width,
        height
      });
    }
    return this[_xfa_object.$extra];
  }
  [_xfa_object.$toHTML](availableSpace) {
    if (!this.value) {
      return _utils.HTMLResult.EMPTY;
    }
    this[_xfa_object.$pushPara]();
    const value = this.value[_xfa_object.$toHTML](availableSpace).html;
    if (!value) {
      this[_xfa_object.$popPara]();
      return _utils.HTMLResult.EMPTY;
    }
    const savedReserve = this.reserve;
    if (this.reserve <= 0) {
      const {
        w,
        h
      } = this[_xfa_object.$getExtra](availableSpace);
      switch (this.placement) {
        case "left":
        case "right":
        case "inline":
          this.reserve = w;
          break;
        case "top":
        case "bottom":
          this.reserve = h;
          break;
      }
    }
    const children = [];
    if (typeof value === "string") {
      children.push({
        name: "#text",
        value
      });
    } else {
      children.push(value);
    }
    const style = (0, _html_utils.toStyle)(this, "font", "margin", "visibility");
    switch (this.placement) {
      case "left":
      case "right":
        if (this.reserve > 0) {
          style.width = (0, _html_utils.measureToString)(this.reserve);
        }
        break;
      case "top":
      case "bottom":
        if (this.reserve > 0) {
          style.height = (0, _html_utils.measureToString)(this.reserve);
        }
        break;
    }
    (0, _html_utils.setPara)(this, null, value);
    this[_xfa_object.$popPara]();
    this.reserve = savedReserve;
    return _utils.HTMLResult.success({
      name: "div",
      attributes: {
        style,
        class: ["xfaCaption"]
      },
      children
    });
  }
}
class Certificate extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "certificate");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Certificates extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "certificates", true);
    this.credentialServerPolicy = (0, _utils.getStringOption)(attributes.credentialServerPolicy, ["optional", "required"]);
    this.id = attributes.id || "";
    this.url = attributes.url || "";
    this.urlPolicy = attributes.urlPolicy || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.encryption = null;
    this.issuers = null;
    this.keyUsage = null;
    this.oids = null;
    this.signing = null;
    this.subjectDNs = null;
  }
}
class CheckButton extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "checkButton", true);
    this.id = attributes.id || "";
    this.mark = (0, _utils.getStringOption)(attributes.mark, ["default", "check", "circle", "cross", "diamond", "square", "star"]);
    this.shape = (0, _utils.getStringOption)(attributes.shape, ["square", "round"]);
    this.size = (0, _utils.getMeasurement)(attributes.size, "10pt");
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)("margin");
    const size = (0, _html_utils.measureToString)(this.size);
    style.width = style.height = size;
    let type;
    let className;
    let groupId;
    const field = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    const items = field.items.children.length && field.items.children[0][_xfa_object.$toHTML]().html || [];
    const exportedValue = {
      on: (items[0] !== undefined ? items[0] : "on").toString(),
      off: (items[1] !== undefined ? items[1] : "off").toString()
    };
    const value = field.value && field.value[_xfa_object.$text]() || "off";
    const checked = value === exportedValue.on || undefined;
    const container = field[_xfa_object.$getSubformParent]();
    const fieldId = field[_xfa_object.$uid];
    let dataId;
    if (container instanceof ExclGroup) {
      groupId = container[_xfa_object.$uid];
      type = "radio";
      className = "xfaRadio";
      dataId = container[_xfa_object.$data] && container[_xfa_object.$data][_xfa_object.$uid] || container[_xfa_object.$uid];
    } else {
      type = "checkbox";
      className = "xfaCheckbox";
      dataId = field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid];
    }
    const input = {
      name: "input",
      attributes: {
        class: [className],
        style,
        fieldId,
        dataId,
        type,
        checked,
        xfaOn: exportedValue.on,
        xfaOff: exportedValue.off,
        "aria-label": ariaLabel(field),
        "aria-required": false
      }
    };
    if (groupId) {
      input.attributes.name = groupId;
    }
    if (isRequired(field)) {
      input.attributes["aria-required"] = true;
      input.attributes.required = true;
    }
    return _utils.HTMLResult.success({
      name: "label",
      attributes: {
        class: ["xfaLabel"]
      },
      children: [input]
    });
  }
}
class ChoiceList extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "choiceList", true);
    this.commitOn = (0, _utils.getStringOption)(attributes.commitOn, ["select", "exit"]);
    this.id = attributes.id || "";
    this.open = (0, _utils.getStringOption)(attributes.open, ["userControl", "always", "multiSelect", "onEntry"]);
    this.textEntry = (0, _utils.getInteger)({
      data: attributes.textEntry,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)(this, "border", "margin");
    const ui = this[_xfa_object.$getParent]();
    const field = ui[_xfa_object.$getParent]();
    const fontSize = field.font && field.font.size || 10;
    const optionStyle = {
      fontSize: `calc(${fontSize}px * var(--scale-factor))`
    };
    const children = [];
    if (field.items.children.length > 0) {
      const items = field.items;
      let displayedIndex = 0;
      let saveIndex = 0;
      if (items.children.length === 2) {
        displayedIndex = items.children[0].save;
        saveIndex = 1 - displayedIndex;
      }
      const displayed = items.children[displayedIndex][_xfa_object.$toHTML]().html;
      const values = items.children[saveIndex][_xfa_object.$toHTML]().html;
      let selected = false;
      const value = field.value && field.value[_xfa_object.$text]() || "";
      for (let i = 0, ii = displayed.length; i < ii; i++) {
        const option = {
          name: "option",
          attributes: {
            value: values[i] || displayed[i],
            style: optionStyle
          },
          value: displayed[i]
        };
        if (values[i] === value) {
          option.attributes.selected = selected = true;
        }
        children.push(option);
      }
      if (!selected) {
        children.splice(0, 0, {
          name: "option",
          attributes: {
            hidden: true,
            selected: true
          },
          value: " "
        });
      }
    }
    const selectAttributes = {
      class: ["xfaSelect"],
      fieldId: field[_xfa_object.$uid],
      dataId: field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid],
      style,
      "aria-label": ariaLabel(field),
      "aria-required": false
    };
    if (isRequired(field)) {
      selectAttributes["aria-required"] = true;
      selectAttributes.required = true;
    }
    if (this.open === "multiSelect") {
      selectAttributes.multiple = true;
    }
    return _utils.HTMLResult.success({
      name: "label",
      attributes: {
        class: ["xfaLabel"]
      },
      children: [{
        name: "select",
        children,
        attributes: selectAttributes
      }]
    });
  }
}
class Color extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "color", true);
    this.cSpace = (0, _utils.getStringOption)(attributes.cSpace, ["SRGB"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.value = attributes.value ? (0, _utils.getColor)(attributes.value) : "";
    this.extras = null;
  }
  [_xfa_object.$hasSettableValue]() {
    return false;
  }
  [_xfa_object.$toStyle]() {
    return this.value ? _util.Util.makeHexColor(this.value.r, this.value.g, this.value.b) : null;
  }
}
class Comb extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "comb");
    this.id = attributes.id || "";
    this.numberOfCells = (0, _utils.getInteger)({
      data: attributes.numberOfCells,
      defaultValue: 0,
      validate: x => x >= 0
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Connect extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "connect", true);
    this.connection = attributes.connection || "";
    this.id = attributes.id || "";
    this.ref = attributes.ref || "";
    this.usage = (0, _utils.getStringOption)(attributes.usage, ["exportAndImport", "exportOnly", "importOnly"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.picture = null;
  }
}
class ContentArea extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "contentArea", true);
    this.h = (0, _utils.getMeasurement)(attributes.h);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.w = (0, _utils.getMeasurement)(attributes.w);
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.desc = null;
    this.extras = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const left = (0, _html_utils.measureToString)(this.x);
    const top = (0, _html_utils.measureToString)(this.y);
    const style = {
      left,
      top,
      width: (0, _html_utils.measureToString)(this.w),
      height: (0, _html_utils.measureToString)(this.h)
    };
    const classNames = ["xfaContentarea"];
    if ((0, _html_utils.isPrintOnly)(this)) {
      classNames.push("xfaPrintOnly");
    }
    return _utils.HTMLResult.success({
      name: "div",
      children: [],
      attributes: {
        style,
        class: classNames,
        id: this[_xfa_object.$uid]
      }
    });
  }
}
class Corner extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "corner", true);
    this.id = attributes.id || "";
    this.inverted = (0, _utils.getInteger)({
      data: attributes.inverted,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.join = (0, _utils.getStringOption)(attributes.join, ["square", "round"]);
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.radius = (0, _utils.getMeasurement)(attributes.radius);
    this.stroke = (0, _utils.getStringOption)(attributes.stroke, ["solid", "dashDot", "dashDotDot", "dashed", "dotted", "embossed", "etched", "lowered", "raised"]);
    this.thickness = (0, _utils.getMeasurement)(attributes.thickness, "0.5pt");
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle]() {
    const style = (0, _html_utils.toStyle)(this, "visibility");
    style.radius = (0, _html_utils.measureToString)(this.join === "square" ? 0 : this.radius);
    return style;
  }
}
class DateElement extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "date");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const date = this[_xfa_object.$content].trim();
    this[_xfa_object.$content] = date ? new Date(date) : null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] ? this[_xfa_object.$content].toString() : "");
  }
}
class DateTime extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "dateTime");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const date = this[_xfa_object.$content].trim();
    this[_xfa_object.$content] = date ? new Date(date) : null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] ? this[_xfa_object.$content].toString() : "");
  }
}
class DateTimeEdit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "dateTimeEdit", true);
    this.hScrollPolicy = (0, _utils.getStringOption)(attributes.hScrollPolicy, ["auto", "off", "on"]);
    this.id = attributes.id || "";
    this.picker = (0, _utils.getStringOption)(attributes.picker, ["host", "none"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.comb = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)(this, "border", "font", "margin");
    const field = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    const html = {
      name: "input",
      attributes: {
        type: "text",
        fieldId: field[_xfa_object.$uid],
        dataId: field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid],
        class: ["xfaTextfield"],
        style,
        "aria-label": ariaLabel(field),
        "aria-required": false
      }
    };
    if (isRequired(field)) {
      html.attributes["aria-required"] = true;
      html.attributes.required = true;
    }
    return _utils.HTMLResult.success({
      name: "label",
      attributes: {
        class: ["xfaLabel"]
      },
      children: [html]
    });
  }
}
class Decimal extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "decimal");
    this.fracDigits = (0, _utils.getInteger)({
      data: attributes.fracDigits,
      defaultValue: 2,
      validate: x => true
    });
    this.id = attributes.id || "";
    this.leadDigits = (0, _utils.getInteger)({
      data: attributes.leadDigits,
      defaultValue: -1,
      validate: x => true
    });
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const number = parseFloat(this[_xfa_object.$content].trim());
    this[_xfa_object.$content] = isNaN(number) ? null : number;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] !== null ? this[_xfa_object.$content].toString() : "");
  }
}
class DefaultUi extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "defaultUi", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
}
class Desc extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "desc", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.boolean = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
  }
}
class DigestMethod extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "digestMethod", ["", "SHA1", "SHA256", "SHA512", "RIPEMD160"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class DigestMethods extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "digestMethods", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.digestMethod = new _xfa_object.XFAObjectArray();
  }
}
class Draw extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "draw", true);
    this.anchorType = (0, _utils.getStringOption)(attributes.anchorType, ["topLeft", "bottomCenter", "bottomLeft", "bottomRight", "middleCenter", "middleLeft", "middleRight", "topCenter", "topRight"]);
    this.colSpan = (0, _utils.getInteger)({
      data: attributes.colSpan,
      defaultValue: 1,
      validate: n => n >= 1 || n === -1
    });
    this.h = attributes.h ? (0, _utils.getMeasurement)(attributes.h) : "";
    this.hAlign = (0, _utils.getStringOption)(attributes.hAlign, ["left", "center", "justify", "justifyAll", "radix", "right"]);
    this.id = attributes.id || "";
    this.locale = attributes.locale || "";
    this.maxH = (0, _utils.getMeasurement)(attributes.maxH, "0pt");
    this.maxW = (0, _utils.getMeasurement)(attributes.maxW, "0pt");
    this.minH = (0, _utils.getMeasurement)(attributes.minH, "0pt");
    this.minW = (0, _utils.getMeasurement)(attributes.minW, "0pt");
    this.name = attributes.name || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.rotate = (0, _utils.getInteger)({
      data: attributes.rotate,
      defaultValue: 0,
      validate: x => x % 90 === 0
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.w = attributes.w ? (0, _utils.getMeasurement)(attributes.w) : "";
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.assist = null;
    this.border = null;
    this.caption = null;
    this.desc = null;
    this.extras = null;
    this.font = null;
    this.keep = null;
    this.margin = null;
    this.para = null;
    this.traversal = null;
    this.ui = null;
    this.value = null;
    this.setProperty = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$setValue](value) {
    _setValue(this, value);
  }
  [_xfa_object.$toHTML](availableSpace) {
    setTabIndex(this);
    if (this.presence === "hidden" || this.presence === "inactive") {
      return _utils.HTMLResult.EMPTY;
    }
    (0, _html_utils.fixDimensions)(this);
    this[_xfa_object.$pushPara]();
    const savedW = this.w;
    const savedH = this.h;
    const {
      w,
      h,
      isBroken
    } = (0, _html_utils.layoutNode)(this, availableSpace);
    if (w && this.w === "") {
      if (isBroken && this[_xfa_object.$getSubformParent]()[_xfa_object.$isThereMoreWidth]()) {
        this[_xfa_object.$popPara]();
        return _utils.HTMLResult.FAILURE;
      }
      this.w = w;
    }
    if (h && this.h === "") {
      this.h = h;
    }
    setFirstUnsplittable(this);
    if (!(0, _layout.checkDimensions)(this, availableSpace)) {
      this.w = savedW;
      this.h = savedH;
      this[_xfa_object.$popPara]();
      return _utils.HTMLResult.FAILURE;
    }
    unsetFirstUnsplittable(this);
    const style = (0, _html_utils.toStyle)(this, "font", "hAlign", "dimensions", "position", "presence", "rotate", "anchorType", "border", "margin");
    (0, _html_utils.setMinMaxDimensions)(this, style);
    if (style.margin) {
      style.padding = style.margin;
      delete style.margin;
    }
    const classNames = ["xfaDraw"];
    if (this.font) {
      classNames.push("xfaFont");
    }
    if ((0, _html_utils.isPrintOnly)(this)) {
      classNames.push("xfaPrintOnly");
    }
    const attributes = {
      style,
      id: this[_xfa_object.$uid],
      class: classNames
    };
    if (this.name) {
      attributes.xfaName = this.name;
    }
    const html = {
      name: "div",
      attributes,
      children: []
    };
    applyAssist(this, attributes);
    const bbox = (0, _html_utils.computeBbox)(this, html, availableSpace);
    const value = this.value ? this.value[_xfa_object.$toHTML](availableSpace).html : null;
    if (value === null) {
      this.w = savedW;
      this.h = savedH;
      this[_xfa_object.$popPara]();
      return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
    }
    html.children.push(value);
    (0, _html_utils.setPara)(this, style, value);
    this.w = savedW;
    this.h = savedH;
    this[_xfa_object.$popPara]();
    return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
  }
}
class Edge extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "edge", true);
    this.cap = (0, _utils.getStringOption)(attributes.cap, ["square", "butt", "round"]);
    this.id = attributes.id || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.stroke = (0, _utils.getStringOption)(attributes.stroke, ["solid", "dashDot", "dashDotDot", "dashed", "dotted", "embossed", "etched", "lowered", "raised"]);
    this.thickness = (0, _utils.getMeasurement)(attributes.thickness, "0.5pt");
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle]() {
    const style = (0, _html_utils.toStyle)(this, "visibility");
    Object.assign(style, {
      linecap: this.cap,
      width: (0, _html_utils.measureToString)(this.thickness),
      color: this.color ? this.color[_xfa_object.$toStyle]() : "#000000",
      style: ""
    });
    if (this.presence !== "visible") {
      style.style = "none";
    } else {
      switch (this.stroke) {
        case "solid":
          style.style = "solid";
          break;
        case "dashDot":
          style.style = "dashed";
          break;
        case "dashDotDot":
          style.style = "dashed";
          break;
        case "dashed":
          style.style = "dashed";
          break;
        case "dotted":
          style.style = "dotted";
          break;
        case "embossed":
          style.style = "ridge";
          break;
        case "etched":
          style.style = "groove";
          break;
        case "lowered":
          style.style = "inset";
          break;
        case "raised":
          style.style = "outset";
          break;
      }
    }
    return style;
  }
}
class Encoding extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encoding", ["adbe.x509.rsa_sha1", "adbe.pkcs7.detached", "adbe.pkcs7.sha1"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Encodings extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encodings", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.encoding = new _xfa_object.XFAObjectArray();
  }
}
class Encrypt extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encrypt", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.certificate = null;
  }
}
class EncryptData extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encryptData", true);
    this.id = attributes.id || "";
    this.operation = (0, _utils.getStringOption)(attributes.operation, ["encrypt", "decrypt"]);
    this.target = attributes.target || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.filter = null;
    this.manifest = null;
  }
}
class Encryption extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encryption", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.certificate = new _xfa_object.XFAObjectArray();
  }
}
class EncryptionMethod extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encryptionMethod", ["", "AES256-CBC", "TRIPLEDES-CBC", "AES128-CBC", "AES192-CBC"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class EncryptionMethods extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "encryptionMethods", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.encryptionMethod = new _xfa_object.XFAObjectArray();
  }
}
class Event extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "event", true);
    this.activity = (0, _utils.getStringOption)(attributes.activity, ["click", "change", "docClose", "docReady", "enter", "exit", "full", "indexChange", "initialize", "mouseDown", "mouseEnter", "mouseExit", "mouseUp", "postExecute", "postOpen", "postPrint", "postSave", "postSign", "postSubmit", "preExecute", "preOpen", "prePrint", "preSave", "preSign", "preSubmit", "ready", "validationState"]);
    this.id = attributes.id || "";
    this.listen = (0, _utils.getStringOption)(attributes.listen, ["refOnly", "refAndDescendents"]);
    this.name = attributes.name || "";
    this.ref = attributes.ref || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.encryptData = null;
    this.execute = null;
    this.script = null;
    this.signData = null;
    this.submit = null;
  }
}
class ExData extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "exData");
    this.contentType = attributes.contentType || "";
    this.href = attributes.href || "";
    this.id = attributes.id || "";
    this.maxLength = (0, _utils.getInteger)({
      data: attributes.maxLength,
      defaultValue: -1,
      validate: x => x >= -1
    });
    this.name = attributes.name || "";
    this.rid = attributes.rid || "";
    this.transferEncoding = (0, _utils.getStringOption)(attributes.transferEncoding, ["none", "base64", "package"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$isCDATAXml]() {
    return this.contentType === "text/html";
  }
  [_xfa_object.$onChild](child) {
    if (this.contentType === "text/html" && child[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.xhtml.id) {
      this[_xfa_object.$content] = child;
      return true;
    }
    if (this.contentType === "text/xml") {
      this[_xfa_object.$content] = child;
      return true;
    }
    return false;
  }
  [_xfa_object.$toHTML](availableSpace) {
    if (this.contentType !== "text/html" || !this[_xfa_object.$content]) {
      return _utils.HTMLResult.EMPTY;
    }
    return this[_xfa_object.$content][_xfa_object.$toHTML](availableSpace);
  }
}
class ExObject extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "exObject", true);
    this.archive = attributes.archive || "";
    this.classId = attributes.classId || "";
    this.codeBase = attributes.codeBase || "";
    this.codeType = attributes.codeType || "";
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.boolean = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.exObject = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
  }
}
class ExclGroup extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "exclGroup", true);
    this.access = (0, _utils.getStringOption)(attributes.access, ["open", "nonInteractive", "protected", "readOnly"]);
    this.accessKey = attributes.accessKey || "";
    this.anchorType = (0, _utils.getStringOption)(attributes.anchorType, ["topLeft", "bottomCenter", "bottomLeft", "bottomRight", "middleCenter", "middleLeft", "middleRight", "topCenter", "topRight"]);
    this.colSpan = (0, _utils.getInteger)({
      data: attributes.colSpan,
      defaultValue: 1,
      validate: n => n >= 1 || n === -1
    });
    this.h = attributes.h ? (0, _utils.getMeasurement)(attributes.h) : "";
    this.hAlign = (0, _utils.getStringOption)(attributes.hAlign, ["left", "center", "justify", "justifyAll", "radix", "right"]);
    this.id = attributes.id || "";
    this.layout = (0, _utils.getStringOption)(attributes.layout, ["position", "lr-tb", "rl-row", "rl-tb", "row", "table", "tb"]);
    this.maxH = (0, _utils.getMeasurement)(attributes.maxH, "0pt");
    this.maxW = (0, _utils.getMeasurement)(attributes.maxW, "0pt");
    this.minH = (0, _utils.getMeasurement)(attributes.minH, "0pt");
    this.minW = (0, _utils.getMeasurement)(attributes.minW, "0pt");
    this.name = attributes.name || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.w = attributes.w ? (0, _utils.getMeasurement)(attributes.w) : "";
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.assist = null;
    this.bind = null;
    this.border = null;
    this.calculate = null;
    this.caption = null;
    this.desc = null;
    this.extras = null;
    this.margin = null;
    this.para = null;
    this.traversal = null;
    this.validate = null;
    this.connect = new _xfa_object.XFAObjectArray();
    this.event = new _xfa_object.XFAObjectArray();
    this.field = new _xfa_object.XFAObjectArray();
    this.setProperty = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$isBindable]() {
    return true;
  }
  [_xfa_object.$hasSettableValue]() {
    return true;
  }
  [_xfa_object.$setValue](value) {
    for (const field of this.field.children) {
      if (!field.value) {
        const nodeValue = new Value({});
        field[_xfa_object.$appendChild](nodeValue);
        field.value = nodeValue;
      }
      field.value[_xfa_object.$setValue](value);
    }
  }
  [_xfa_object.$isThereMoreWidth]() {
    return this.layout.endsWith("-tb") && this[_xfa_object.$extra].attempt === 0 && this[_xfa_object.$extra].numberInLine > 0 || this[_xfa_object.$getParent]()[_xfa_object.$isThereMoreWidth]();
  }
  [_xfa_object.$isSplittable]() {
    const parent = this[_xfa_object.$getSubformParent]();
    if (!parent[_xfa_object.$isSplittable]()) {
      return false;
    }
    if (this[_xfa_object.$extra]._isSplittable !== undefined) {
      return this[_xfa_object.$extra]._isSplittable;
    }
    if (this.layout === "position" || this.layout.includes("row")) {
      this[_xfa_object.$extra]._isSplittable = false;
      return false;
    }
    if (parent.layout && parent.layout.endsWith("-tb") && parent[_xfa_object.$extra].numberInLine !== 0) {
      return false;
    }
    this[_xfa_object.$extra]._isSplittable = true;
    return true;
  }
  [_xfa_object.$flushHTML]() {
    return (0, _layout.flushHTML)(this);
  }
  [_xfa_object.$addHTML](html, bbox) {
    (0, _layout.addHTML)(this, html, bbox);
  }
  [_xfa_object.$getAvailableSpace]() {
    return (0, _layout.getAvailableSpace)(this);
  }
  [_xfa_object.$toHTML](availableSpace) {
    setTabIndex(this);
    if (this.presence === "hidden" || this.presence === "inactive" || this.h === 0 || this.w === 0) {
      return _utils.HTMLResult.EMPTY;
    }
    (0, _html_utils.fixDimensions)(this);
    const children = [];
    const attributes = {
      id: this[_xfa_object.$uid],
      class: []
    };
    (0, _html_utils.setAccess)(this, attributes.class);
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = Object.create(null);
    }
    Object.assign(this[_xfa_object.$extra], {
      children,
      attributes,
      attempt: 0,
      line: null,
      numberInLine: 0,
      availableSpace: {
        width: Math.min(this.w || Infinity, availableSpace.width),
        height: Math.min(this.h || Infinity, availableSpace.height)
      },
      width: 0,
      height: 0,
      prevHeight: 0,
      currentWidth: 0
    });
    const isSplittable = this[_xfa_object.$isSplittable]();
    if (!isSplittable) {
      setFirstUnsplittable(this);
    }
    if (!(0, _layout.checkDimensions)(this, availableSpace)) {
      return _utils.HTMLResult.FAILURE;
    }
    const filter = new Set(["field"]);
    if (this.layout.includes("row")) {
      const columnWidths = this[_xfa_object.$getSubformParent]().columnWidths;
      if (Array.isArray(columnWidths) && columnWidths.length > 0) {
        this[_xfa_object.$extra].columnWidths = columnWidths;
        this[_xfa_object.$extra].currentColumn = 0;
      }
    }
    const style = (0, _html_utils.toStyle)(this, "anchorType", "dimensions", "position", "presence", "border", "margin", "hAlign");
    const classNames = ["xfaExclgroup"];
    const cl = (0, _html_utils.layoutClass)(this);
    if (cl) {
      classNames.push(cl);
    }
    if ((0, _html_utils.isPrintOnly)(this)) {
      classNames.push("xfaPrintOnly");
    }
    attributes.style = style;
    attributes.class = classNames;
    if (this.name) {
      attributes.xfaName = this.name;
    }
    this[_xfa_object.$pushPara]();
    const isLrTb = this.layout === "lr-tb" || this.layout === "rl-tb";
    const maxRun = isLrTb ? MAX_ATTEMPTS_FOR_LRTB_LAYOUT : 1;
    for (; this[_xfa_object.$extra].attempt < maxRun; this[_xfa_object.$extra].attempt++) {
      if (isLrTb && this[_xfa_object.$extra].attempt === MAX_ATTEMPTS_FOR_LRTB_LAYOUT - 1) {
        this[_xfa_object.$extra].numberInLine = 0;
      }
      const result = this[_xfa_object.$childrenToHTML]({
        filter,
        include: true
      });
      if (result.success) {
        break;
      }
      if (result.isBreak()) {
        this[_xfa_object.$popPara]();
        return result;
      }
      if (isLrTb && this[_xfa_object.$extra].attempt === 0 && this[_xfa_object.$extra].numberInLine === 0 && !this[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
        this[_xfa_object.$extra].attempt = maxRun;
        break;
      }
    }
    this[_xfa_object.$popPara]();
    if (!isSplittable) {
      unsetFirstUnsplittable(this);
    }
    if (this[_xfa_object.$extra].attempt === maxRun) {
      if (!isSplittable) {
        delete this[_xfa_object.$extra];
      }
      return _utils.HTMLResult.FAILURE;
    }
    let marginH = 0;
    let marginV = 0;
    if (this.margin) {
      marginH = this.margin.leftInset + this.margin.rightInset;
      marginV = this.margin.topInset + this.margin.bottomInset;
    }
    const width = Math.max(this[_xfa_object.$extra].width + marginH, this.w || 0);
    const height = Math.max(this[_xfa_object.$extra].height + marginV, this.h || 0);
    const bbox = [this.x, this.y, width, height];
    if (this.w === "") {
      style.width = (0, _html_utils.measureToString)(width);
    }
    if (this.h === "") {
      style.height = (0, _html_utils.measureToString)(height);
    }
    const html = {
      name: "div",
      attributes,
      children
    };
    applyAssist(this, attributes);
    delete this[_xfa_object.$extra];
    return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
  }
}
class Execute extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "execute");
    this.connection = attributes.connection || "";
    this.executeType = (0, _utils.getStringOption)(attributes.executeType, ["import", "remerge"]);
    this.id = attributes.id || "";
    this.runAt = (0, _utils.getStringOption)(attributes.runAt, ["client", "both", "server"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Extras extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "extras", true);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.boolean = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.extras = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
  }
}
class Field extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "field", true);
    this.access = (0, _utils.getStringOption)(attributes.access, ["open", "nonInteractive", "protected", "readOnly"]);
    this.accessKey = attributes.accessKey || "";
    this.anchorType = (0, _utils.getStringOption)(attributes.anchorType, ["topLeft", "bottomCenter", "bottomLeft", "bottomRight", "middleCenter", "middleLeft", "middleRight", "topCenter", "topRight"]);
    this.colSpan = (0, _utils.getInteger)({
      data: attributes.colSpan,
      defaultValue: 1,
      validate: n => n >= 1 || n === -1
    });
    this.h = attributes.h ? (0, _utils.getMeasurement)(attributes.h) : "";
    this.hAlign = (0, _utils.getStringOption)(attributes.hAlign, ["left", "center", "justify", "justifyAll", "radix", "right"]);
    this.id = attributes.id || "";
    this.locale = attributes.locale || "";
    this.maxH = (0, _utils.getMeasurement)(attributes.maxH, "0pt");
    this.maxW = (0, _utils.getMeasurement)(attributes.maxW, "0pt");
    this.minH = (0, _utils.getMeasurement)(attributes.minH, "0pt");
    this.minW = (0, _utils.getMeasurement)(attributes.minW, "0pt");
    this.name = attributes.name || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.rotate = (0, _utils.getInteger)({
      data: attributes.rotate,
      defaultValue: 0,
      validate: x => x % 90 === 0
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.w = attributes.w ? (0, _utils.getMeasurement)(attributes.w) : "";
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.assist = null;
    this.bind = null;
    this.border = null;
    this.calculate = null;
    this.caption = null;
    this.desc = null;
    this.extras = null;
    this.font = null;
    this.format = null;
    this.items = new _xfa_object.XFAObjectArray(2);
    this.keep = null;
    this.margin = null;
    this.para = null;
    this.traversal = null;
    this.ui = null;
    this.validate = null;
    this.value = null;
    this.bindItems = new _xfa_object.XFAObjectArray();
    this.connect = new _xfa_object.XFAObjectArray();
    this.event = new _xfa_object.XFAObjectArray();
    this.setProperty = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$isBindable]() {
    return true;
  }
  [_xfa_object.$setValue](value) {
    _setValue(this, value);
  }
  [_xfa_object.$toHTML](availableSpace) {
    setTabIndex(this);
    if (!this.ui) {
      this.ui = new Ui({});
      this.ui[_xfa_object.$globalData] = this[_xfa_object.$globalData];
      this[_xfa_object.$appendChild](this.ui);
      let node;
      switch (this.items.children.length) {
        case 0:
          node = new TextEdit({});
          this.ui.textEdit = node;
          break;
        case 1:
          node = new CheckButton({});
          this.ui.checkButton = node;
          break;
        case 2:
          node = new ChoiceList({});
          this.ui.choiceList = node;
          break;
      }
      this.ui[_xfa_object.$appendChild](node);
    }
    if (!this.ui || this.presence === "hidden" || this.presence === "inactive" || this.h === 0 || this.w === 0) {
      return _utils.HTMLResult.EMPTY;
    }
    if (this.caption) {
      delete this.caption[_xfa_object.$extra];
    }
    this[_xfa_object.$pushPara]();
    const caption = this.caption ? this.caption[_xfa_object.$toHTML](availableSpace).html : null;
    const savedW = this.w;
    const savedH = this.h;
    let marginH = 0;
    let marginV = 0;
    if (this.margin) {
      marginH = this.margin.leftInset + this.margin.rightInset;
      marginV = this.margin.topInset + this.margin.bottomInset;
    }
    let borderDims = null;
    if (this.w === "" || this.h === "") {
      let width = null;
      let height = null;
      let uiW = 0;
      let uiH = 0;
      if (this.ui.checkButton) {
        uiW = uiH = this.ui.checkButton.size;
      } else {
        const {
          w,
          h
        } = (0, _html_utils.layoutNode)(this, availableSpace);
        if (w !== null) {
          uiW = w;
          uiH = h;
        } else {
          uiH = (0, _fonts.getMetrics)(this.font, true).lineNoGap;
        }
      }
      borderDims = getBorderDims(this.ui[_xfa_object.$getExtra]());
      uiW += borderDims.w;
      uiH += borderDims.h;
      if (this.caption) {
        const {
          w,
          h,
          isBroken
        } = this.caption[_xfa_object.$getExtra](availableSpace);
        if (isBroken && this[_xfa_object.$getSubformParent]()[_xfa_object.$isThereMoreWidth]()) {
          this[_xfa_object.$popPara]();
          return _utils.HTMLResult.FAILURE;
        }
        width = w;
        height = h;
        switch (this.caption.placement) {
          case "left":
          case "right":
          case "inline":
            width += uiW;
            break;
          case "top":
          case "bottom":
            height += uiH;
            break;
        }
      } else {
        width = uiW;
        height = uiH;
      }
      if (width && this.w === "") {
        width += marginH;
        this.w = Math.min(this.maxW <= 0 ? Infinity : this.maxW, this.minW + 1 < width ? width : this.minW);
      }
      if (height && this.h === "") {
        height += marginV;
        this.h = Math.min(this.maxH <= 0 ? Infinity : this.maxH, this.minH + 1 < height ? height : this.minH);
      }
    }
    this[_xfa_object.$popPara]();
    (0, _html_utils.fixDimensions)(this);
    setFirstUnsplittable(this);
    if (!(0, _layout.checkDimensions)(this, availableSpace)) {
      this.w = savedW;
      this.h = savedH;
      this[_xfa_object.$popPara]();
      return _utils.HTMLResult.FAILURE;
    }
    unsetFirstUnsplittable(this);
    const style = (0, _html_utils.toStyle)(this, "font", "dimensions", "position", "rotate", "anchorType", "presence", "margin", "hAlign");
    (0, _html_utils.setMinMaxDimensions)(this, style);
    const classNames = ["xfaField"];
    if (this.font) {
      classNames.push("xfaFont");
    }
    if ((0, _html_utils.isPrintOnly)(this)) {
      classNames.push("xfaPrintOnly");
    }
    const attributes = {
      style,
      id: this[_xfa_object.$uid],
      class: classNames
    };
    if (style.margin) {
      style.padding = style.margin;
      delete style.margin;
    }
    (0, _html_utils.setAccess)(this, classNames);
    if (this.name) {
      attributes.xfaName = this.name;
    }
    const children = [];
    const html = {
      name: "div",
      attributes,
      children
    };
    applyAssist(this, attributes);
    const borderStyle = this.border ? this.border[_xfa_object.$toStyle]() : null;
    const bbox = (0, _html_utils.computeBbox)(this, html, availableSpace);
    const ui = this.ui[_xfa_object.$toHTML]().html;
    if (!ui) {
      Object.assign(style, borderStyle);
      return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
    }
    if (this[_xfa_object.$tabIndex]) {
      if (ui.children && ui.children[0]) {
        ui.children[0].attributes.tabindex = this[_xfa_object.$tabIndex];
      } else {
        ui.attributes.tabindex = this[_xfa_object.$tabIndex];
      }
    }
    if (!ui.attributes.style) {
      ui.attributes.style = Object.create(null);
    }
    let aElement = null;
    if (this.ui.button) {
      if (ui.children.length === 1) {
        [aElement] = ui.children.splice(0, 1);
      }
      Object.assign(ui.attributes.style, borderStyle);
    } else {
      Object.assign(style, borderStyle);
    }
    children.push(ui);
    if (this.value) {
      if (this.ui.imageEdit) {
        ui.children.push(this.value[_xfa_object.$toHTML]().html);
      } else if (!this.ui.button) {
        let value = "";
        if (this.value.exData) {
          value = this.value.exData[_xfa_object.$text]();
        } else if (this.value.text) {
          value = this.value.text[_xfa_object.$getExtra]();
        } else {
          const htmlValue = this.value[_xfa_object.$toHTML]().html;
          if (htmlValue !== null) {
            value = htmlValue.children[0].value;
          }
        }
        if (this.ui.textEdit && this.value.text && this.value.text.maxChars) {
          ui.children[0].attributes.maxLength = this.value.text.maxChars;
        }
        if (value) {
          if (this.ui.numericEdit) {
            value = parseFloat(value);
            value = isNaN(value) ? "" : value.toString();
          }
          if (ui.children[0].name === "textarea") {
            ui.children[0].attributes.textContent = value;
          } else {
            ui.children[0].attributes.value = value;
          }
        }
      }
    }
    if (!this.ui.imageEdit && ui.children && ui.children[0] && this.h) {
      borderDims = borderDims || getBorderDims(this.ui[_xfa_object.$getExtra]());
      let captionHeight = 0;
      if (this.caption && ["top", "bottom"].includes(this.caption.placement)) {
        captionHeight = this.caption.reserve;
        if (captionHeight <= 0) {
          captionHeight = this.caption[_xfa_object.$getExtra](availableSpace).h;
        }
        const inputHeight = this.h - captionHeight - marginV - borderDims.h;
        ui.children[0].attributes.style.height = (0, _html_utils.measureToString)(inputHeight);
      } else {
        ui.children[0].attributes.style.height = "100%";
      }
    }
    if (aElement) {
      ui.children.push(aElement);
    }
    if (!caption) {
      if (ui.attributes.class) {
        ui.attributes.class.push("xfaLeft");
      }
      this.w = savedW;
      this.h = savedH;
      return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
    }
    if (this.ui.button) {
      if (style.padding) {
        delete style.padding;
      }
      if (caption.name === "div") {
        caption.name = "span";
      }
      ui.children.push(caption);
      return _utils.HTMLResult.success(html, bbox);
    } else if (this.ui.checkButton) {
      caption.attributes.class[0] = "xfaCaptionForCheckButton";
    }
    if (!ui.attributes.class) {
      ui.attributes.class = [];
    }
    ui.children.splice(0, 0, caption);
    switch (this.caption.placement) {
      case "left":
        ui.attributes.class.push("xfaLeft");
        break;
      case "right":
        ui.attributes.class.push("xfaRight");
        break;
      case "top":
        ui.attributes.class.push("xfaTop");
        break;
      case "bottom":
        ui.attributes.class.push("xfaBottom");
        break;
      case "inline":
        ui.attributes.class.push("xfaLeft");
        break;
    }
    this.w = savedW;
    this.h = savedH;
    return _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
  }
}
exports.Field = Field;
class Fill extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "fill", true);
    this.id = attributes.id || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
    this.linear = null;
    this.pattern = null;
    this.radial = null;
    this.solid = null;
    this.stipple = null;
  }
  [_xfa_object.$toStyle]() {
    const parent = this[_xfa_object.$getParent]();
    const grandpa = parent[_xfa_object.$getParent]();
    const ggrandpa = grandpa[_xfa_object.$getParent]();
    const style = Object.create(null);
    let propName = "color";
    let altPropName = propName;
    if (parent instanceof Border) {
      propName = "background-color";
      altPropName = "background";
      if (ggrandpa instanceof Ui) {
        style.backgroundColor = "white";
      }
    }
    if (parent instanceof Rectangle || parent instanceof Arc) {
      propName = altPropName = "fill";
      style.fill = "white";
    }
    for (const name of Object.getOwnPropertyNames(this)) {
      if (name === "extras" || name === "color") {
        continue;
      }
      const obj = this[name];
      if (!(obj instanceof _xfa_object.XFAObject)) {
        continue;
      }
      const color = obj[_xfa_object.$toStyle](this.color);
      if (color) {
        style[color.startsWith("#") ? propName : altPropName] = color;
      }
      return style;
    }
    if (this.color && this.color.value) {
      const color = this.color[_xfa_object.$toStyle]();
      style[color.startsWith("#") ? propName : altPropName] = color;
    }
    return style;
  }
}
class Filter extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "filter", true);
    this.addRevocationInfo = (0, _utils.getStringOption)(attributes.addRevocationInfo, ["", "required", "optional", "none"]);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.version = (0, _utils.getInteger)({
      data: this.version,
      defaultValue: 5,
      validate: x => x >= 1 && x <= 5
    });
    this.appearanceFilter = null;
    this.certificates = null;
    this.digestMethods = null;
    this.encodings = null;
    this.encryptionMethods = null;
    this.handler = null;
    this.lockDocument = null;
    this.mdp = null;
    this.reasons = null;
    this.timeStamp = null;
  }
}
class Float extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "float");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const number = parseFloat(this[_xfa_object.$content].trim());
    this[_xfa_object.$content] = isNaN(number) ? null : number;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] !== null ? this[_xfa_object.$content].toString() : "");
  }
}
class Font extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "font", true);
    this.baselineShift = (0, _utils.getMeasurement)(attributes.baselineShift);
    this.fontHorizontalScale = (0, _utils.getFloat)({
      data: attributes.fontHorizontalScale,
      defaultValue: 100,
      validate: x => x >= 0
    });
    this.fontVerticalScale = (0, _utils.getFloat)({
      data: attributes.fontVerticalScale,
      defaultValue: 100,
      validate: x => x >= 0
    });
    this.id = attributes.id || "";
    this.kerningMode = (0, _utils.getStringOption)(attributes.kerningMode, ["none", "pair"]);
    this.letterSpacing = (0, _utils.getMeasurement)(attributes.letterSpacing, "0");
    this.lineThrough = (0, _utils.getInteger)({
      data: attributes.lineThrough,
      defaultValue: 0,
      validate: x => x === 1 || x === 2
    });
    this.lineThroughPeriod = (0, _utils.getStringOption)(attributes.lineThroughPeriod, ["all", "word"]);
    this.overline = (0, _utils.getInteger)({
      data: attributes.overline,
      defaultValue: 0,
      validate: x => x === 1 || x === 2
    });
    this.overlinePeriod = (0, _utils.getStringOption)(attributes.overlinePeriod, ["all", "word"]);
    this.posture = (0, _utils.getStringOption)(attributes.posture, ["normal", "italic"]);
    this.size = (0, _utils.getMeasurement)(attributes.size, "10pt");
    this.typeface = attributes.typeface || "Courier";
    this.underline = (0, _utils.getInteger)({
      data: attributes.underline,
      defaultValue: 0,
      validate: x => x === 1 || x === 2
    });
    this.underlinePeriod = (0, _utils.getStringOption)(attributes.underlinePeriod, ["all", "word"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.weight = (0, _utils.getStringOption)(attributes.weight, ["normal", "bold"]);
    this.extras = null;
    this.fill = null;
  }
  [_xfa_object.$clean](builder) {
    super[_xfa_object.$clean](builder);
    this[_xfa_object.$globalData].usedTypefaces.add(this.typeface);
  }
  [_xfa_object.$toStyle]() {
    const style = (0, _html_utils.toStyle)(this, "fill");
    const color = style.color;
    if (color) {
      if (color === "#000000") {
        delete style.color;
      } else if (!color.startsWith("#")) {
        style.background = color;
        style.backgroundClip = "text";
        style.color = "transparent";
      }
    }
    if (this.baselineShift) {
      style.verticalAlign = (0, _html_utils.measureToString)(this.baselineShift);
    }
    style.fontKerning = this.kerningMode === "none" ? "none" : "normal";
    style.letterSpacing = (0, _html_utils.measureToString)(this.letterSpacing);
    if (this.lineThrough !== 0) {
      style.textDecoration = "line-through";
      if (this.lineThrough === 2) {
        style.textDecorationStyle = "double";
      }
    }
    if (this.overline !== 0) {
      style.textDecoration = "overline";
      if (this.overline === 2) {
        style.textDecorationStyle = "double";
      }
    }
    style.fontStyle = this.posture;
    style.fontSize = (0, _html_utils.measureToString)(0.99 * this.size);
    (0, _html_utils.setFontFamily)(this, this, this[_xfa_object.$globalData].fontFinder, style);
    if (this.underline !== 0) {
      style.textDecoration = "underline";
      if (this.underline === 2) {
        style.textDecorationStyle = "double";
      }
    }
    style.fontWeight = this.weight;
    return style;
  }
}
class Format extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "format", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.picture = null;
  }
}
class Handler extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "handler");
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Hyphenation extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "hyphenation");
    this.excludeAllCaps = (0, _utils.getInteger)({
      data: attributes.excludeAllCaps,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.excludeInitialCap = (0, _utils.getInteger)({
      data: attributes.excludeInitialCap,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.hyphenate = (0, _utils.getInteger)({
      data: attributes.hyphenate,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.id = attributes.id || "";
    this.pushCharacterCount = (0, _utils.getInteger)({
      data: attributes.pushCharacterCount,
      defaultValue: 3,
      validate: x => x >= 0
    });
    this.remainCharacterCount = (0, _utils.getInteger)({
      data: attributes.remainCharacterCount,
      defaultValue: 3,
      validate: x => x >= 0
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.wordCharacterCount = (0, _utils.getInteger)({
      data: attributes.wordCharacterCount,
      defaultValue: 7,
      validate: x => x >= 0
    });
  }
}
class Image extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "image");
    this.aspect = (0, _utils.getStringOption)(attributes.aspect, ["fit", "actual", "height", "none", "width"]);
    this.contentType = attributes.contentType || "";
    this.href = attributes.href || "";
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.transferEncoding = (0, _utils.getStringOption)(attributes.transferEncoding, ["base64", "none", "package"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$toHTML]() {
    if (this.contentType && !MIMES.has(this.contentType.toLowerCase())) {
      return _utils.HTMLResult.EMPTY;
    }
    let buffer = this[_xfa_object.$globalData].images && this[_xfa_object.$globalData].images.get(this.href);
    if (!buffer && (this.href || !this[_xfa_object.$content])) {
      return _utils.HTMLResult.EMPTY;
    }
    if (!buffer && this.transferEncoding === "base64") {
      buffer = (0, _util.stringToBytes)(atob(this[_xfa_object.$content]));
    }
    if (!buffer) {
      return _utils.HTMLResult.EMPTY;
    }
    if (!this.contentType) {
      for (const [header, type] of IMAGES_HEADERS) {
        if (buffer.length > header.length && header.every((x, i) => x === buffer[i])) {
          this.contentType = type;
          break;
        }
      }
      if (!this.contentType) {
        return _utils.HTMLResult.EMPTY;
      }
    }
    const blob = new Blob([buffer], {
      type: this.contentType
    });
    let style;
    switch (this.aspect) {
      case "fit":
      case "actual":
        break;
      case "height":
        style = {
          height: "100%",
          objectFit: "fill"
        };
        break;
      case "none":
        style = {
          width: "100%",
          height: "100%",
          objectFit: "fill"
        };
        break;
      case "width":
        style = {
          width: "100%",
          objectFit: "fill"
        };
        break;
    }
    const parent = this[_xfa_object.$getParent]();
    return _utils.HTMLResult.success({
      name: "img",
      attributes: {
        class: ["xfaImage"],
        style,
        src: URL.createObjectURL(blob),
        alt: parent ? ariaLabel(parent[_xfa_object.$getParent]()) : null
      }
    });
  }
}
class ImageEdit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "imageEdit", true);
    this.data = (0, _utils.getStringOption)(attributes.data, ["link", "embed"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    if (this.data === "embed") {
      return _utils.HTMLResult.success({
        name: "div",
        children: [],
        attributes: {}
      });
    }
    return _utils.HTMLResult.EMPTY;
  }
}
class Integer extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "integer");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const number = parseInt(this[_xfa_object.$content].trim(), 10);
    this[_xfa_object.$content] = isNaN(number) ? null : number;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] !== null ? this[_xfa_object.$content].toString() : "");
  }
}
class Issuers extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "issuers", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.certificate = new _xfa_object.XFAObjectArray();
  }
}
class Items extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "items", true);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.ref = attributes.ref || "";
    this.save = (0, _utils.getInteger)({
      data: attributes.save,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.boolean = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$toHTML]() {
    const output = [];
    for (const child of this[_xfa_object.$getChildren]()) {
      output.push(child[_xfa_object.$text]());
    }
    return _utils.HTMLResult.success(output);
  }
}
exports.Items = Items;
class Keep extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "keep", true);
    this.id = attributes.id || "";
    const options = ["none", "contentArea", "pageArea"];
    this.intact = (0, _utils.getStringOption)(attributes.intact, options);
    this.next = (0, _utils.getStringOption)(attributes.next, options);
    this.previous = (0, _utils.getStringOption)(attributes.previous, options);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
}
class KeyUsage extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "keyUsage");
    const options = ["", "yes", "no"];
    this.crlSign = (0, _utils.getStringOption)(attributes.crlSign, options);
    this.dataEncipherment = (0, _utils.getStringOption)(attributes.dataEncipherment, options);
    this.decipherOnly = (0, _utils.getStringOption)(attributes.decipherOnly, options);
    this.digitalSignature = (0, _utils.getStringOption)(attributes.digitalSignature, options);
    this.encipherOnly = (0, _utils.getStringOption)(attributes.encipherOnly, options);
    this.id = attributes.id || "";
    this.keyAgreement = (0, _utils.getStringOption)(attributes.keyAgreement, options);
    this.keyCertSign = (0, _utils.getStringOption)(attributes.keyCertSign, options);
    this.keyEncipherment = (0, _utils.getStringOption)(attributes.keyEncipherment, options);
    this.nonRepudiation = (0, _utils.getStringOption)(attributes.nonRepudiation, options);
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Line extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "line", true);
    this.hand = (0, _utils.getStringOption)(attributes.hand, ["even", "left", "right"]);
    this.id = attributes.id || "";
    this.slope = (0, _utils.getStringOption)(attributes.slope, ["\\", "/"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.edge = null;
  }
  [_xfa_object.$toHTML]() {
    const parent = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    const edge = this.edge || new Edge({});
    const edgeStyle = edge[_xfa_object.$toStyle]();
    const style = Object.create(null);
    const thickness = edge.presence === "visible" ? edge.thickness : 0;
    style.strokeWidth = (0, _html_utils.measureToString)(thickness);
    style.stroke = edgeStyle.color;
    let x1, y1, x2, y2;
    let width = "100%";
    let height = "100%";
    if (parent.w <= thickness) {
      [x1, y1, x2, y2] = ["50%", 0, "50%", "100%"];
      width = style.strokeWidth;
    } else if (parent.h <= thickness) {
      [x1, y1, x2, y2] = [0, "50%", "100%", "50%"];
      height = style.strokeWidth;
    } else {
      if (this.slope === "\\") {
        [x1, y1, x2, y2] = [0, 0, "100%", "100%"];
      } else {
        [x1, y1, x2, y2] = [0, "100%", "100%", 0];
      }
    }
    const line = {
      name: "line",
      attributes: {
        xmlns: SVG_NS,
        x1,
        y1,
        x2,
        y2,
        style
      }
    };
    const svg = {
      name: "svg",
      children: [line],
      attributes: {
        xmlns: SVG_NS,
        width,
        height,
        style: {
          overflow: "visible"
        }
      }
    };
    if (hasMargin(parent)) {
      return _utils.HTMLResult.success({
        name: "div",
        attributes: {
          style: {
            display: "inline",
            width: "100%",
            height: "100%"
          }
        },
        children: [svg]
      });
    }
    svg.attributes.style.position = "absolute";
    return _utils.HTMLResult.success(svg);
  }
}
class Linear extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "linear", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["toRight", "toBottom", "toLeft", "toTop"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle](startColor) {
    startColor = startColor ? startColor[_xfa_object.$toStyle]() : "#FFFFFF";
    const transf = this.type.replace(/([RBLT])/, " $1").toLowerCase();
    const endColor = this.color ? this.color[_xfa_object.$toStyle]() : "#000000";
    return `linear-gradient(${transf}, ${startColor}, ${endColor})`;
  }
}
class LockDocument extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "lockDocument");
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = (0, _utils.getStringOption)(this[_xfa_object.$content], ["auto", "0", "1"]);
  }
}
class Manifest extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "manifest", true);
    this.action = (0, _utils.getStringOption)(attributes.action, ["include", "all", "exclude"]);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.ref = new _xfa_object.XFAObjectArray();
  }
}
class Margin extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "margin", true);
    this.bottomInset = (0, _utils.getMeasurement)(attributes.bottomInset, "0");
    this.id = attributes.id || "";
    this.leftInset = (0, _utils.getMeasurement)(attributes.leftInset, "0");
    this.rightInset = (0, _utils.getMeasurement)(attributes.rightInset, "0");
    this.topInset = (0, _utils.getMeasurement)(attributes.topInset, "0");
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
  [_xfa_object.$toStyle]() {
    return {
      margin: (0, _html_utils.measureToString)(this.topInset) + " " + (0, _html_utils.measureToString)(this.rightInset) + " " + (0, _html_utils.measureToString)(this.bottomInset) + " " + (0, _html_utils.measureToString)(this.leftInset)
    };
  }
}
class Mdp extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "mdp");
    this.id = attributes.id || "";
    this.permissions = (0, _utils.getInteger)({
      data: attributes.permissions,
      defaultValue: 2,
      validate: x => x === 1 || x === 3
    });
    this.signatureType = (0, _utils.getStringOption)(attributes.signatureType, ["filler", "author"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Medium extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "medium");
    this.id = attributes.id || "";
    this.imagingBBox = (0, _utils.getBBox)(attributes.imagingBBox);
    this.long = (0, _utils.getMeasurement)(attributes.long);
    this.orientation = (0, _utils.getStringOption)(attributes.orientation, ["portrait", "landscape"]);
    this.short = (0, _utils.getMeasurement)(attributes.short);
    this.stock = attributes.stock || "";
    this.trayIn = (0, _utils.getStringOption)(attributes.trayIn, ["auto", "delegate", "pageFront"]);
    this.trayOut = (0, _utils.getStringOption)(attributes.trayOut, ["auto", "delegate"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Message extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "message", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.text = new _xfa_object.XFAObjectArray();
  }
}
class NumericEdit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "numericEdit", true);
    this.hScrollPolicy = (0, _utils.getStringOption)(attributes.hScrollPolicy, ["auto", "off", "on"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.comb = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)(this, "border", "font", "margin");
    const field = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    const html = {
      name: "input",
      attributes: {
        type: "text",
        fieldId: field[_xfa_object.$uid],
        dataId: field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid],
        class: ["xfaTextfield"],
        style,
        "aria-label": ariaLabel(field),
        "aria-required": false
      }
    };
    if (isRequired(field)) {
      html.attributes["aria-required"] = true;
      html.attributes.required = true;
    }
    return _utils.HTMLResult.success({
      name: "label",
      attributes: {
        class: ["xfaLabel"]
      },
      children: [html]
    });
  }
}
class Occur extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "occur", true);
    this.id = attributes.id || "";
    this.initial = attributes.initial !== "" ? (0, _utils.getInteger)({
      data: attributes.initial,
      defaultValue: "",
      validate: x => true
    }) : "";
    this.max = attributes.max !== "" ? (0, _utils.getInteger)({
      data: attributes.max,
      defaultValue: 1,
      validate: x => true
    }) : "";
    this.min = attributes.min !== "" ? (0, _utils.getInteger)({
      data: attributes.min,
      defaultValue: 1,
      validate: x => true
    }) : "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
  [_xfa_object.$clean]() {
    const parent = this[_xfa_object.$getParent]();
    const originalMin = this.min;
    if (this.min === "") {
      this.min = parent instanceof PageArea || parent instanceof PageSet ? 0 : 1;
    }
    if (this.max === "") {
      if (originalMin === "") {
        this.max = parent instanceof PageArea || parent instanceof PageSet ? -1 : 1;
      } else {
        this.max = this.min;
      }
    }
    if (this.max !== -1 && this.max < this.min) {
      this.max = this.min;
    }
    if (this.initial === "") {
      this.initial = parent instanceof Template ? 1 : this.min;
    }
  }
}
class Oid extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "oid");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Oids extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "oids", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.oid = new _xfa_object.XFAObjectArray();
  }
}
class Overflow extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "overflow");
    this.id = attributes.id || "";
    this.leader = attributes.leader || "";
    this.target = attributes.target || "";
    this.trailer = attributes.trailer || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$getExtra]() {
    if (!this[_xfa_object.$extra]) {
      const parent = this[_xfa_object.$getParent]();
      const root = this[_xfa_object.$getTemplateRoot]();
      const target = root[_xfa_object.$searchNode](this.target, parent);
      const leader = root[_xfa_object.$searchNode](this.leader, parent);
      const trailer = root[_xfa_object.$searchNode](this.trailer, parent);
      this[_xfa_object.$extra] = {
        target: target && target[0] || null,
        leader: leader && leader[0] || null,
        trailer: trailer && trailer[0] || null,
        addLeader: false,
        addTrailer: false
      };
    }
    return this[_xfa_object.$extra];
  }
}
class PageArea extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "pageArea", true);
    this.blankOrNotBlank = (0, _utils.getStringOption)(attributes.blankOrNotBlank, ["any", "blank", "notBlank"]);
    this.id = attributes.id || "";
    this.initialNumber = (0, _utils.getInteger)({
      data: attributes.initialNumber,
      defaultValue: 1,
      validate: x => true
    });
    this.name = attributes.name || "";
    this.numbered = (0, _utils.getInteger)({
      data: attributes.numbered,
      defaultValue: 1,
      validate: x => true
    });
    this.oddOrEven = (0, _utils.getStringOption)(attributes.oddOrEven, ["any", "even", "odd"]);
    this.pagePosition = (0, _utils.getStringOption)(attributes.pagePosition, ["any", "first", "last", "only", "rest"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.desc = null;
    this.extras = null;
    this.medium = null;
    this.occur = null;
    this.area = new _xfa_object.XFAObjectArray();
    this.contentArea = new _xfa_object.XFAObjectArray();
    this.draw = new _xfa_object.XFAObjectArray();
    this.exclGroup = new _xfa_object.XFAObjectArray();
    this.field = new _xfa_object.XFAObjectArray();
    this.subform = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$isUsable]() {
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = {
        numberOfUse: 0
      };
      return true;
    }
    return !this.occur || this.occur.max === -1 || this[_xfa_object.$extra].numberOfUse < this.occur.max;
  }
  [_xfa_object.$cleanPage]() {
    delete this[_xfa_object.$extra];
  }
  [_xfa_object.$getNextPage]() {
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = {
        numberOfUse: 0
      };
    }
    const parent = this[_xfa_object.$getParent]();
    if (parent.relation === "orderedOccurrence") {
      if (this[_xfa_object.$isUsable]()) {
        this[_xfa_object.$extra].numberOfUse += 1;
        return this;
      }
    }
    return parent[_xfa_object.$getNextPage]();
  }
  [_xfa_object.$getAvailableSpace]() {
    return this[_xfa_object.$extra].space || {
      width: 0,
      height: 0
    };
  }
  [_xfa_object.$toHTML]() {
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = {
        numberOfUse: 1
      };
    }
    const children = [];
    this[_xfa_object.$extra].children = children;
    const style = Object.create(null);
    if (this.medium && this.medium.short && this.medium.long) {
      style.width = (0, _html_utils.measureToString)(this.medium.short);
      style.height = (0, _html_utils.measureToString)(this.medium.long);
      this[_xfa_object.$extra].space = {
        width: this.medium.short,
        height: this.medium.long
      };
      if (this.medium.orientation === "landscape") {
        const x = style.width;
        style.width = style.height;
        style.height = x;
        this[_xfa_object.$extra].space = {
          width: this.medium.long,
          height: this.medium.short
        };
      }
    } else {
      (0, _util.warn)("XFA - No medium specified in pageArea: please file a bug.");
    }
    this[_xfa_object.$childrenToHTML]({
      filter: new Set(["area", "draw", "field", "subform"]),
      include: true
    });
    this[_xfa_object.$childrenToHTML]({
      filter: new Set(["contentArea"]),
      include: true
    });
    return _utils.HTMLResult.success({
      name: "div",
      children,
      attributes: {
        class: ["xfaPage"],
        id: this[_xfa_object.$uid],
        style,
        xfaName: this.name
      }
    });
  }
}
class PageSet extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "pageSet", true);
    this.duplexImposition = (0, _utils.getStringOption)(attributes.duplexImposition, ["longEdge", "shortEdge"]);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.relation = (0, _utils.getStringOption)(attributes.relation, ["orderedOccurrence", "duplexPaginated", "simplexPaginated"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.occur = null;
    this.pageArea = new _xfa_object.XFAObjectArray();
    this.pageSet = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$cleanPage]() {
    for (const page of this.pageArea.children) {
      page[_xfa_object.$cleanPage]();
    }
    for (const page of this.pageSet.children) {
      page[_xfa_object.$cleanPage]();
    }
  }
  [_xfa_object.$isUsable]() {
    return !this.occur || this.occur.max === -1 || this[_xfa_object.$extra].numberOfUse < this.occur.max;
  }
  [_xfa_object.$getNextPage]() {
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = {
        numberOfUse: 1,
        pageIndex: -1,
        pageSetIndex: -1
      };
    }
    if (this.relation === "orderedOccurrence") {
      if (this[_xfa_object.$extra].pageIndex + 1 < this.pageArea.children.length) {
        this[_xfa_object.$extra].pageIndex += 1;
        const pageArea = this.pageArea.children[this[_xfa_object.$extra].pageIndex];
        return pageArea[_xfa_object.$getNextPage]();
      }
      if (this[_xfa_object.$extra].pageSetIndex + 1 < this.pageSet.children.length) {
        this[_xfa_object.$extra].pageSetIndex += 1;
        return this.pageSet.children[this[_xfa_object.$extra].pageSetIndex][_xfa_object.$getNextPage]();
      }
      if (this[_xfa_object.$isUsable]()) {
        this[_xfa_object.$extra].numberOfUse += 1;
        this[_xfa_object.$extra].pageIndex = -1;
        this[_xfa_object.$extra].pageSetIndex = -1;
        return this[_xfa_object.$getNextPage]();
      }
      const parent = this[_xfa_object.$getParent]();
      if (parent instanceof PageSet) {
        return parent[_xfa_object.$getNextPage]();
      }
      this[_xfa_object.$cleanPage]();
      return this[_xfa_object.$getNextPage]();
    }
    const pageNumber = this[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].pageNumber;
    const parity = pageNumber % 2 === 0 ? "even" : "odd";
    const position = pageNumber === 0 ? "first" : "rest";
    let page = this.pageArea.children.find(p => p.oddOrEven === parity && p.pagePosition === position);
    if (page) {
      return page;
    }
    page = this.pageArea.children.find(p => p.oddOrEven === "any" && p.pagePosition === position);
    if (page) {
      return page;
    }
    page = this.pageArea.children.find(p => p.oddOrEven === "any" && p.pagePosition === "any");
    if (page) {
      return page;
    }
    return this.pageArea.children[0];
  }
}
class Para extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "para", true);
    this.hAlign = (0, _utils.getStringOption)(attributes.hAlign, ["left", "center", "justify", "justifyAll", "radix", "right"]);
    this.id = attributes.id || "";
    this.lineHeight = attributes.lineHeight ? (0, _utils.getMeasurement)(attributes.lineHeight, "0pt") : "";
    this.marginLeft = attributes.marginLeft ? (0, _utils.getMeasurement)(attributes.marginLeft, "0pt") : "";
    this.marginRight = attributes.marginRight ? (0, _utils.getMeasurement)(attributes.marginRight, "0pt") : "";
    this.orphans = (0, _utils.getInteger)({
      data: attributes.orphans,
      defaultValue: 0,
      validate: x => x >= 0
    });
    this.preserve = attributes.preserve || "";
    this.radixOffset = attributes.radixOffset ? (0, _utils.getMeasurement)(attributes.radixOffset, "0pt") : "";
    this.spaceAbove = attributes.spaceAbove ? (0, _utils.getMeasurement)(attributes.spaceAbove, "0pt") : "";
    this.spaceBelow = attributes.spaceBelow ? (0, _utils.getMeasurement)(attributes.spaceBelow, "0pt") : "";
    this.tabDefault = attributes.tabDefault ? (0, _utils.getMeasurement)(this.tabDefault) : "";
    this.tabStops = (attributes.tabStops || "").trim().split(/\s+/).map((x, i) => i % 2 === 1 ? (0, _utils.getMeasurement)(x) : x);
    this.textIndent = attributes.textIndent ? (0, _utils.getMeasurement)(attributes.textIndent, "0pt") : "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.vAlign = (0, _utils.getStringOption)(attributes.vAlign, ["top", "bottom", "middle"]);
    this.widows = (0, _utils.getInteger)({
      data: attributes.widows,
      defaultValue: 0,
      validate: x => x >= 0
    });
    this.hyphenation = null;
  }
  [_xfa_object.$toStyle]() {
    const style = (0, _html_utils.toStyle)(this, "hAlign");
    if (this.marginLeft !== "") {
      style.paddingLeft = (0, _html_utils.measureToString)(this.marginLeft);
    }
    if (this.marginRight !== "") {
      style.paddingight = (0, _html_utils.measureToString)(this.marginRight);
    }
    if (this.spaceAbove !== "") {
      style.paddingTop = (0, _html_utils.measureToString)(this.spaceAbove);
    }
    if (this.spaceBelow !== "") {
      style.paddingBottom = (0, _html_utils.measureToString)(this.spaceBelow);
    }
    if (this.textIndent !== "") {
      style.textIndent = (0, _html_utils.measureToString)(this.textIndent);
      (0, _html_utils.fixTextIndent)(style);
    }
    if (this.lineHeight > 0) {
      style.lineHeight = (0, _html_utils.measureToString)(this.lineHeight);
    }
    if (this.tabDefault !== "") {
      style.tabSize = (0, _html_utils.measureToString)(this.tabDefault);
    }
    if (this.tabStops.length > 0) {}
    if (this.hyphenatation) {
      Object.assign(style, this.hyphenatation[_xfa_object.$toStyle]());
    }
    return style;
  }
}
class PasswordEdit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "passwordEdit", true);
    this.hScrollPolicy = (0, _utils.getStringOption)(attributes.hScrollPolicy, ["auto", "off", "on"]);
    this.id = attributes.id || "";
    this.passwordChar = attributes.passwordChar || "*";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.extras = null;
    this.margin = null;
  }
}
class Pattern extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "pattern", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["crossHatch", "crossDiagonal", "diagonalLeft", "diagonalRight", "horizontal", "vertical"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle](startColor) {
    startColor = startColor ? startColor[_xfa_object.$toStyle]() : "#FFFFFF";
    const endColor = this.color ? this.color[_xfa_object.$toStyle]() : "#000000";
    const width = 5;
    const cmd = "repeating-linear-gradient";
    const colors = `${startColor},${startColor} ${width}px,${endColor} ${width}px,${endColor} ${2 * width}px`;
    switch (this.type) {
      case "crossHatch":
        return `${cmd}(to top,${colors}) ${cmd}(to right,${colors})`;
      case "crossDiagonal":
        return `${cmd}(45deg,${colors}) ${cmd}(-45deg,${colors})`;
      case "diagonalLeft":
        return `${cmd}(45deg,${colors})`;
      case "diagonalRight":
        return `${cmd}(-45deg,${colors})`;
      case "horizontal":
        return `${cmd}(to top,${colors})`;
      case "vertical":
        return `${cmd}(to right,${colors})`;
    }
    return "";
  }
}
class Picture extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "picture");
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Proto extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "proto", true);
    this.appearanceFilter = new _xfa_object.XFAObjectArray();
    this.arc = new _xfa_object.XFAObjectArray();
    this.area = new _xfa_object.XFAObjectArray();
    this.assist = new _xfa_object.XFAObjectArray();
    this.barcode = new _xfa_object.XFAObjectArray();
    this.bindItems = new _xfa_object.XFAObjectArray();
    this.bookend = new _xfa_object.XFAObjectArray();
    this.boolean = new _xfa_object.XFAObjectArray();
    this.border = new _xfa_object.XFAObjectArray();
    this.break = new _xfa_object.XFAObjectArray();
    this.breakAfter = new _xfa_object.XFAObjectArray();
    this.breakBefore = new _xfa_object.XFAObjectArray();
    this.button = new _xfa_object.XFAObjectArray();
    this.calculate = new _xfa_object.XFAObjectArray();
    this.caption = new _xfa_object.XFAObjectArray();
    this.certificate = new _xfa_object.XFAObjectArray();
    this.certificates = new _xfa_object.XFAObjectArray();
    this.checkButton = new _xfa_object.XFAObjectArray();
    this.choiceList = new _xfa_object.XFAObjectArray();
    this.color = new _xfa_object.XFAObjectArray();
    this.comb = new _xfa_object.XFAObjectArray();
    this.connect = new _xfa_object.XFAObjectArray();
    this.contentArea = new _xfa_object.XFAObjectArray();
    this.corner = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.dateTimeEdit = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.defaultUi = new _xfa_object.XFAObjectArray();
    this.desc = new _xfa_object.XFAObjectArray();
    this.digestMethod = new _xfa_object.XFAObjectArray();
    this.digestMethods = new _xfa_object.XFAObjectArray();
    this.draw = new _xfa_object.XFAObjectArray();
    this.edge = new _xfa_object.XFAObjectArray();
    this.encoding = new _xfa_object.XFAObjectArray();
    this.encodings = new _xfa_object.XFAObjectArray();
    this.encrypt = new _xfa_object.XFAObjectArray();
    this.encryptData = new _xfa_object.XFAObjectArray();
    this.encryption = new _xfa_object.XFAObjectArray();
    this.encryptionMethod = new _xfa_object.XFAObjectArray();
    this.encryptionMethods = new _xfa_object.XFAObjectArray();
    this.event = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.exObject = new _xfa_object.XFAObjectArray();
    this.exclGroup = new _xfa_object.XFAObjectArray();
    this.execute = new _xfa_object.XFAObjectArray();
    this.extras = new _xfa_object.XFAObjectArray();
    this.field = new _xfa_object.XFAObjectArray();
    this.fill = new _xfa_object.XFAObjectArray();
    this.filter = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.font = new _xfa_object.XFAObjectArray();
    this.format = new _xfa_object.XFAObjectArray();
    this.handler = new _xfa_object.XFAObjectArray();
    this.hyphenation = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.imageEdit = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.issuers = new _xfa_object.XFAObjectArray();
    this.items = new _xfa_object.XFAObjectArray();
    this.keep = new _xfa_object.XFAObjectArray();
    this.keyUsage = new _xfa_object.XFAObjectArray();
    this.line = new _xfa_object.XFAObjectArray();
    this.linear = new _xfa_object.XFAObjectArray();
    this.lockDocument = new _xfa_object.XFAObjectArray();
    this.manifest = new _xfa_object.XFAObjectArray();
    this.margin = new _xfa_object.XFAObjectArray();
    this.mdp = new _xfa_object.XFAObjectArray();
    this.medium = new _xfa_object.XFAObjectArray();
    this.message = new _xfa_object.XFAObjectArray();
    this.numericEdit = new _xfa_object.XFAObjectArray();
    this.occur = new _xfa_object.XFAObjectArray();
    this.oid = new _xfa_object.XFAObjectArray();
    this.oids = new _xfa_object.XFAObjectArray();
    this.overflow = new _xfa_object.XFAObjectArray();
    this.pageArea = new _xfa_object.XFAObjectArray();
    this.pageSet = new _xfa_object.XFAObjectArray();
    this.para = new _xfa_object.XFAObjectArray();
    this.passwordEdit = new _xfa_object.XFAObjectArray();
    this.pattern = new _xfa_object.XFAObjectArray();
    this.picture = new _xfa_object.XFAObjectArray();
    this.radial = new _xfa_object.XFAObjectArray();
    this.reason = new _xfa_object.XFAObjectArray();
    this.reasons = new _xfa_object.XFAObjectArray();
    this.rectangle = new _xfa_object.XFAObjectArray();
    this.ref = new _xfa_object.XFAObjectArray();
    this.script = new _xfa_object.XFAObjectArray();
    this.setProperty = new _xfa_object.XFAObjectArray();
    this.signData = new _xfa_object.XFAObjectArray();
    this.signature = new _xfa_object.XFAObjectArray();
    this.signing = new _xfa_object.XFAObjectArray();
    this.solid = new _xfa_object.XFAObjectArray();
    this.speak = new _xfa_object.XFAObjectArray();
    this.stipple = new _xfa_object.XFAObjectArray();
    this.subform = new _xfa_object.XFAObjectArray();
    this.subformSet = new _xfa_object.XFAObjectArray();
    this.subjectDN = new _xfa_object.XFAObjectArray();
    this.subjectDNs = new _xfa_object.XFAObjectArray();
    this.submit = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.textEdit = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
    this.timeStamp = new _xfa_object.XFAObjectArray();
    this.toolTip = new _xfa_object.XFAObjectArray();
    this.traversal = new _xfa_object.XFAObjectArray();
    this.traverse = new _xfa_object.XFAObjectArray();
    this.ui = new _xfa_object.XFAObjectArray();
    this.validate = new _xfa_object.XFAObjectArray();
    this.value = new _xfa_object.XFAObjectArray();
    this.variables = new _xfa_object.XFAObjectArray();
  }
}
class Radial extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "radial", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["toEdge", "toCenter"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle](startColor) {
    startColor = startColor ? startColor[_xfa_object.$toStyle]() : "#FFFFFF";
    const endColor = this.color ? this.color[_xfa_object.$toStyle]() : "#000000";
    const colors = this.type === "toEdge" ? `${startColor},${endColor}` : `${endColor},${startColor}`;
    return `radial-gradient(circle at center, ${colors})`;
  }
}
class Reason extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "reason");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Reasons extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "reasons", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.reason = new _xfa_object.XFAObjectArray();
  }
}
class Rectangle extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "rectangle", true);
    this.hand = (0, _utils.getStringOption)(attributes.hand, ["even", "left", "right"]);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.corner = new _xfa_object.XFAObjectArray(4);
    this.edge = new _xfa_object.XFAObjectArray(4);
    this.fill = null;
  }
  [_xfa_object.$toHTML]() {
    const edge = this.edge.children.length ? this.edge.children[0] : new Edge({});
    const edgeStyle = edge[_xfa_object.$toStyle]();
    const style = Object.create(null);
    if (this.fill && this.fill.presence === "visible") {
      Object.assign(style, this.fill[_xfa_object.$toStyle]());
    } else {
      style.fill = "transparent";
    }
    style.strokeWidth = (0, _html_utils.measureToString)(edge.presence === "visible" ? edge.thickness : 0);
    style.stroke = edgeStyle.color;
    const corner = this.corner.children.length ? this.corner.children[0] : new Corner({});
    const cornerStyle = corner[_xfa_object.$toStyle]();
    const rect = {
      name: "rect",
      attributes: {
        xmlns: SVG_NS,
        width: "100%",
        height: "100%",
        x: 0,
        y: 0,
        rx: cornerStyle.radius,
        ry: cornerStyle.radius,
        style
      }
    };
    const svg = {
      name: "svg",
      children: [rect],
      attributes: {
        xmlns: SVG_NS,
        style: {
          overflow: "visible"
        },
        width: "100%",
        height: "100%"
      }
    };
    const parent = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    if (hasMargin(parent)) {
      return _utils.HTMLResult.success({
        name: "div",
        attributes: {
          style: {
            display: "inline",
            width: "100%",
            height: "100%"
          }
        },
        children: [svg]
      });
    }
    svg.attributes.style.position = "absolute";
    return _utils.HTMLResult.success(svg);
  }
}
class RefElement extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "ref");
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Script extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "script");
    this.binding = attributes.binding || "";
    this.contentType = attributes.contentType || "";
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.runAt = (0, _utils.getStringOption)(attributes.runAt, ["client", "both", "server"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class SetProperty extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "setProperty");
    this.connection = attributes.connection || "";
    this.ref = attributes.ref || "";
    this.target = attributes.target || "";
  }
}
exports.SetProperty = SetProperty;
class SignData extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "signData", true);
    this.id = attributes.id || "";
    this.operation = (0, _utils.getStringOption)(attributes.operation, ["sign", "clear", "verify"]);
    this.ref = attributes.ref || "";
    this.target = attributes.target || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.filter = null;
    this.manifest = null;
  }
}
class Signature extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "signature", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["PDF1.3", "PDF1.6"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.border = null;
    this.extras = null;
    this.filter = null;
    this.manifest = null;
    this.margin = null;
  }
}
class Signing extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "signing", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.certificate = new _xfa_object.XFAObjectArray();
  }
}
class Solid extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "solid", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
  }
  [_xfa_object.$toStyle](startColor) {
    return startColor ? startColor[_xfa_object.$toStyle]() : "#FFFFFF";
  }
}
class Speak extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "speak");
    this.disable = (0, _utils.getInteger)({
      data: attributes.disable,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.id = attributes.id || "";
    this.priority = (0, _utils.getStringOption)(attributes.priority, ["custom", "caption", "name", "toolTip"]);
    this.rid = attributes.rid || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Stipple extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "stipple", true);
    this.id = attributes.id || "";
    this.rate = (0, _utils.getInteger)({
      data: attributes.rate,
      defaultValue: 50,
      validate: x => x >= 0 && x <= 100
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.color = null;
    this.extras = null;
  }
  [_xfa_object.$toStyle](bgColor) {
    const alpha = this.rate / 100;
    return _util.Util.makeHexColor(Math.round(bgColor.value.r * (1 - alpha) + this.value.r * alpha), Math.round(bgColor.value.g * (1 - alpha) + this.value.g * alpha), Math.round(bgColor.value.b * (1 - alpha) + this.value.b * alpha));
  }
}
class Subform extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "subform", true);
    this.access = (0, _utils.getStringOption)(attributes.access, ["open", "nonInteractive", "protected", "readOnly"]);
    this.allowMacro = (0, _utils.getInteger)({
      data: attributes.allowMacro,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.anchorType = (0, _utils.getStringOption)(attributes.anchorType, ["topLeft", "bottomCenter", "bottomLeft", "bottomRight", "middleCenter", "middleLeft", "middleRight", "topCenter", "topRight"]);
    this.colSpan = (0, _utils.getInteger)({
      data: attributes.colSpan,
      defaultValue: 1,
      validate: n => n >= 1 || n === -1
    });
    this.columnWidths = (attributes.columnWidths || "").trim().split(/\s+/).map(x => x === "-1" ? -1 : (0, _utils.getMeasurement)(x));
    this.h = attributes.h ? (0, _utils.getMeasurement)(attributes.h) : "";
    this.hAlign = (0, _utils.getStringOption)(attributes.hAlign, ["left", "center", "justify", "justifyAll", "radix", "right"]);
    this.id = attributes.id || "";
    this.layout = (0, _utils.getStringOption)(attributes.layout, ["position", "lr-tb", "rl-row", "rl-tb", "row", "table", "tb"]);
    this.locale = attributes.locale || "";
    this.maxH = (0, _utils.getMeasurement)(attributes.maxH, "0pt");
    this.maxW = (0, _utils.getMeasurement)(attributes.maxW, "0pt");
    this.mergeMode = (0, _utils.getStringOption)(attributes.mergeMode, ["consumeData", "matchTemplate"]);
    this.minH = (0, _utils.getMeasurement)(attributes.minH, "0pt");
    this.minW = (0, _utils.getMeasurement)(attributes.minW, "0pt");
    this.name = attributes.name || "";
    this.presence = (0, _utils.getStringOption)(attributes.presence, ["visible", "hidden", "inactive", "invisible"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.restoreState = (0, _utils.getStringOption)(attributes.restoreState, ["manual", "auto"]);
    this.scope = (0, _utils.getStringOption)(attributes.scope, ["name", "none"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.w = attributes.w ? (0, _utils.getMeasurement)(attributes.w) : "";
    this.x = (0, _utils.getMeasurement)(attributes.x, "0pt");
    this.y = (0, _utils.getMeasurement)(attributes.y, "0pt");
    this.assist = null;
    this.bind = null;
    this.bookend = null;
    this.border = null;
    this.break = null;
    this.calculate = null;
    this.desc = null;
    this.extras = null;
    this.keep = null;
    this.margin = null;
    this.occur = null;
    this.overflow = null;
    this.pageSet = null;
    this.para = null;
    this.traversal = null;
    this.validate = null;
    this.variables = null;
    this.area = new _xfa_object.XFAObjectArray();
    this.breakAfter = new _xfa_object.XFAObjectArray();
    this.breakBefore = new _xfa_object.XFAObjectArray();
    this.connect = new _xfa_object.XFAObjectArray();
    this.draw = new _xfa_object.XFAObjectArray();
    this.event = new _xfa_object.XFAObjectArray();
    this.exObject = new _xfa_object.XFAObjectArray();
    this.exclGroup = new _xfa_object.XFAObjectArray();
    this.field = new _xfa_object.XFAObjectArray();
    this.proto = new _xfa_object.XFAObjectArray();
    this.setProperty = new _xfa_object.XFAObjectArray();
    this.subform = new _xfa_object.XFAObjectArray();
    this.subformSet = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$getSubformParent]() {
    const parent = this[_xfa_object.$getParent]();
    if (parent instanceof SubformSet) {
      return parent[_xfa_object.$getSubformParent]();
    }
    return parent;
  }
  [_xfa_object.$isBindable]() {
    return true;
  }
  [_xfa_object.$isThereMoreWidth]() {
    return this.layout.endsWith("-tb") && this[_xfa_object.$extra].attempt === 0 && this[_xfa_object.$extra].numberInLine > 0 || this[_xfa_object.$getParent]()[_xfa_object.$isThereMoreWidth]();
  }
  *[_xfa_object.$getContainedChildren]() {
    yield* getContainedChildren(this);
  }
  [_xfa_object.$flushHTML]() {
    return (0, _layout.flushHTML)(this);
  }
  [_xfa_object.$addHTML](html, bbox) {
    (0, _layout.addHTML)(this, html, bbox);
  }
  [_xfa_object.$getAvailableSpace]() {
    return (0, _layout.getAvailableSpace)(this);
  }
  [_xfa_object.$isSplittable]() {
    const parent = this[_xfa_object.$getSubformParent]();
    if (!parent[_xfa_object.$isSplittable]()) {
      return false;
    }
    if (this[_xfa_object.$extra]._isSplittable !== undefined) {
      return this[_xfa_object.$extra]._isSplittable;
    }
    if (this.layout === "position" || this.layout.includes("row")) {
      this[_xfa_object.$extra]._isSplittable = false;
      return false;
    }
    if (this.keep && this.keep.intact !== "none") {
      this[_xfa_object.$extra]._isSplittable = false;
      return false;
    }
    if (parent.layout && parent.layout.endsWith("-tb") && parent[_xfa_object.$extra].numberInLine !== 0) {
      return false;
    }
    this[_xfa_object.$extra]._isSplittable = true;
    return true;
  }
  [_xfa_object.$toHTML](availableSpace) {
    setTabIndex(this);
    if (this.break) {
      if (this.break.after !== "auto" || this.break.afterTarget !== "") {
        const node = new BreakAfter({
          targetType: this.break.after,
          target: this.break.afterTarget,
          startNew: this.break.startNew.toString()
        });
        node[_xfa_object.$globalData] = this[_xfa_object.$globalData];
        this[_xfa_object.$appendChild](node);
        this.breakAfter.push(node);
      }
      if (this.break.before !== "auto" || this.break.beforeTarget !== "") {
        const node = new BreakBefore({
          targetType: this.break.before,
          target: this.break.beforeTarget,
          startNew: this.break.startNew.toString()
        });
        node[_xfa_object.$globalData] = this[_xfa_object.$globalData];
        this[_xfa_object.$appendChild](node);
        this.breakBefore.push(node);
      }
      if (this.break.overflowTarget !== "") {
        const node = new Overflow({
          target: this.break.overflowTarget,
          leader: this.break.overflowLeader,
          trailer: this.break.overflowTrailer
        });
        node[_xfa_object.$globalData] = this[_xfa_object.$globalData];
        this[_xfa_object.$appendChild](node);
        this.overflow.push(node);
      }
      this[_xfa_object.$removeChild](this.break);
      this.break = null;
    }
    if (this.presence === "hidden" || this.presence === "inactive") {
      return _utils.HTMLResult.EMPTY;
    }
    if (this.breakBefore.children.length > 1 || this.breakAfter.children.length > 1) {
      (0, _util.warn)("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");
    }
    if (this.breakBefore.children.length >= 1) {
      const breakBefore = this.breakBefore.children[0];
      if (handleBreak(breakBefore)) {
        return _utils.HTMLResult.breakNode(breakBefore);
      }
    }
    if (this[_xfa_object.$extra] && this[_xfa_object.$extra].afterBreakAfter) {
      return _utils.HTMLResult.EMPTY;
    }
    (0, _html_utils.fixDimensions)(this);
    const children = [];
    const attributes = {
      id: this[_xfa_object.$uid],
      class: []
    };
    (0, _html_utils.setAccess)(this, attributes.class);
    if (!this[_xfa_object.$extra]) {
      this[_xfa_object.$extra] = Object.create(null);
    }
    Object.assign(this[_xfa_object.$extra], {
      children,
      line: null,
      attributes,
      attempt: 0,
      numberInLine: 0,
      availableSpace: {
        width: Math.min(this.w || Infinity, availableSpace.width),
        height: Math.min(this.h || Infinity, availableSpace.height)
      },
      width: 0,
      height: 0,
      prevHeight: 0,
      currentWidth: 0
    });
    const root = this[_xfa_object.$getTemplateRoot]();
    const savedNoLayoutFailure = root[_xfa_object.$extra].noLayoutFailure;
    const isSplittable = this[_xfa_object.$isSplittable]();
    if (!isSplittable) {
      setFirstUnsplittable(this);
    }
    if (!(0, _layout.checkDimensions)(this, availableSpace)) {
      return _utils.HTMLResult.FAILURE;
    }
    const filter = new Set(["area", "draw", "exclGroup", "field", "subform", "subformSet"]);
    if (this.layout.includes("row")) {
      const columnWidths = this[_xfa_object.$getSubformParent]().columnWidths;
      if (Array.isArray(columnWidths) && columnWidths.length > 0) {
        this[_xfa_object.$extra].columnWidths = columnWidths;
        this[_xfa_object.$extra].currentColumn = 0;
      }
    }
    const style = (0, _html_utils.toStyle)(this, "anchorType", "dimensions", "position", "presence", "border", "margin", "hAlign");
    const classNames = ["xfaSubform"];
    const cl = (0, _html_utils.layoutClass)(this);
    if (cl) {
      classNames.push(cl);
    }
    attributes.style = style;
    attributes.class = classNames;
    if (this.name) {
      attributes.xfaName = this.name;
    }
    if (this.overflow) {
      const overflowExtra = this.overflow[_xfa_object.$getExtra]();
      if (overflowExtra.addLeader) {
        overflowExtra.addLeader = false;
        handleOverflow(this, overflowExtra.leader, availableSpace);
      }
    }
    this[_xfa_object.$pushPara]();
    const isLrTb = this.layout === "lr-tb" || this.layout === "rl-tb";
    const maxRun = isLrTb ? MAX_ATTEMPTS_FOR_LRTB_LAYOUT : 1;
    for (; this[_xfa_object.$extra].attempt < maxRun; this[_xfa_object.$extra].attempt++) {
      if (isLrTb && this[_xfa_object.$extra].attempt === MAX_ATTEMPTS_FOR_LRTB_LAYOUT - 1) {
        this[_xfa_object.$extra].numberInLine = 0;
      }
      const result = this[_xfa_object.$childrenToHTML]({
        filter,
        include: true
      });
      if (result.success) {
        break;
      }
      if (result.isBreak()) {
        this[_xfa_object.$popPara]();
        return result;
      }
      if (isLrTb && this[_xfa_object.$extra].attempt === 0 && this[_xfa_object.$extra].numberInLine === 0 && !root[_xfa_object.$extra].noLayoutFailure) {
        this[_xfa_object.$extra].attempt = maxRun;
        break;
      }
    }
    this[_xfa_object.$popPara]();
    if (!isSplittable) {
      unsetFirstUnsplittable(this);
    }
    root[_xfa_object.$extra].noLayoutFailure = savedNoLayoutFailure;
    if (this[_xfa_object.$extra].attempt === maxRun) {
      if (this.overflow) {
        this[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].overflowNode = this.overflow;
      }
      if (!isSplittable) {
        delete this[_xfa_object.$extra];
      }
      return _utils.HTMLResult.FAILURE;
    }
    if (this.overflow) {
      const overflowExtra = this.overflow[_xfa_object.$getExtra]();
      if (overflowExtra.addTrailer) {
        overflowExtra.addTrailer = false;
        handleOverflow(this, overflowExtra.trailer, availableSpace);
      }
    }
    let marginH = 0;
    let marginV = 0;
    if (this.margin) {
      marginH = this.margin.leftInset + this.margin.rightInset;
      marginV = this.margin.topInset + this.margin.bottomInset;
    }
    const width = Math.max(this[_xfa_object.$extra].width + marginH, this.w || 0);
    const height = Math.max(this[_xfa_object.$extra].height + marginV, this.h || 0);
    const bbox = [this.x, this.y, width, height];
    if (this.w === "") {
      style.width = (0, _html_utils.measureToString)(width);
    }
    if (this.h === "") {
      style.height = (0, _html_utils.measureToString)(height);
    }
    if ((style.width === "0px" || style.height === "0px") && children.length === 0) {
      return _utils.HTMLResult.EMPTY;
    }
    const html = {
      name: "div",
      attributes,
      children
    };
    applyAssist(this, attributes);
    const result = _utils.HTMLResult.success((0, _html_utils.createWrapper)(this, html), bbox);
    if (this.breakAfter.children.length >= 1) {
      const breakAfter = this.breakAfter.children[0];
      if (handleBreak(breakAfter)) {
        this[_xfa_object.$extra].afterBreakAfter = result;
        return _utils.HTMLResult.breakNode(breakAfter);
      }
    }
    delete this[_xfa_object.$extra];
    return result;
  }
}
class SubformSet extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "subformSet", true);
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.relation = (0, _utils.getStringOption)(attributes.relation, ["ordered", "choice", "unordered"]);
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.bookend = null;
    this.break = null;
    this.desc = null;
    this.extras = null;
    this.occur = null;
    this.overflow = null;
    this.breakAfter = new _xfa_object.XFAObjectArray();
    this.breakBefore = new _xfa_object.XFAObjectArray();
    this.subform = new _xfa_object.XFAObjectArray();
    this.subformSet = new _xfa_object.XFAObjectArray();
  }
  *[_xfa_object.$getContainedChildren]() {
    yield* getContainedChildren(this);
  }
  [_xfa_object.$getSubformParent]() {
    let parent = this[_xfa_object.$getParent]();
    while (!(parent instanceof Subform)) {
      parent = parent[_xfa_object.$getParent]();
    }
    return parent;
  }
  [_xfa_object.$isBindable]() {
    return true;
  }
}
class SubjectDN extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "subjectDN");
    this.delimiter = attributes.delimiter || ",";
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = new Map(this[_xfa_object.$content].split(this.delimiter).map(kv => {
      kv = kv.split("=", 2);
      kv[0] = kv[0].trim();
      return kv;
    }));
  }
}
class SubjectDNs extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "subjectDNs", true);
    this.id = attributes.id || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.subjectDN = new _xfa_object.XFAObjectArray();
  }
}
class Submit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "submit", true);
    this.embedPDF = (0, _utils.getInteger)({
      data: attributes.embedPDF,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.format = (0, _utils.getStringOption)(attributes.format, ["xdp", "formdata", "pdf", "urlencoded", "xfd", "xml"]);
    this.id = attributes.id || "";
    this.target = attributes.target || "";
    this.textEncoding = (0, _utils.getKeyword)({
      data: attributes.textEncoding ? attributes.textEncoding.toLowerCase() : "",
      defaultValue: "",
      validate: k => ["utf-8", "big-five", "fontspecific", "gbk", "gb-18030", "gb-2312", "ksc-5601", "none", "shift-jis", "ucs-2", "utf-16"].includes(k) || k.match(/iso-8859-\d{2}/)
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.xdpContent = attributes.xdpContent || "";
    this.encrypt = null;
    this.encryptData = new _xfa_object.XFAObjectArray();
    this.signData = new _xfa_object.XFAObjectArray();
  }
}
class Template extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "template", true);
    this.baseProfile = (0, _utils.getStringOption)(attributes.baseProfile, ["full", "interactiveForms"]);
    this.extras = null;
    this.subform = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$finalize]() {
    if (this.subform.children.length === 0) {
      (0, _util.warn)("XFA - No subforms in template node.");
    }
    if (this.subform.children.length >= 2) {
      (0, _util.warn)("XFA - Several subforms in template node: please file a bug.");
    }
    this[_xfa_object.$tabIndex] = DEFAULT_TAB_INDEX;
  }
  [_xfa_object.$isSplittable]() {
    return true;
  }
  [_xfa_object.$searchNode](expr, container) {
    if (expr.startsWith("#")) {
      return [this[_xfa_object.$ids].get(expr.slice(1))];
    }
    return (0, _som.searchNode)(this, container, expr, true, true);
  }
  *[_xfa_object.$toPages]() {
    if (!this.subform.children.length) {
      return _utils.HTMLResult.success({
        name: "div",
        children: []
      });
    }
    this[_xfa_object.$extra] = {
      overflowNode: null,
      firstUnsplittable: null,
      currentContentArea: null,
      currentPageArea: null,
      noLayoutFailure: false,
      pageNumber: 1,
      pagePosition: "first",
      oddOrEven: "odd",
      blankOrNotBlank: "nonBlank",
      paraStack: []
    };
    const root = this.subform.children[0];
    root.pageSet[_xfa_object.$cleanPage]();
    const pageAreas = root.pageSet.pageArea.children;
    const mainHtml = {
      name: "div",
      children: []
    };
    let pageArea = null;
    let breakBefore = null;
    let breakBeforeTarget = null;
    if (root.breakBefore.children.length >= 1) {
      breakBefore = root.breakBefore.children[0];
      breakBeforeTarget = breakBefore.target;
    } else if (root.subform.children.length >= 1 && root.subform.children[0].breakBefore.children.length >= 1) {
      breakBefore = root.subform.children[0].breakBefore.children[0];
      breakBeforeTarget = breakBefore.target;
    } else if (root.break && root.break.beforeTarget) {
      breakBefore = root.break;
      breakBeforeTarget = breakBefore.beforeTarget;
    } else if (root.subform.children.length >= 1 && root.subform.children[0].break && root.subform.children[0].break.beforeTarget) {
      breakBefore = root.subform.children[0].break;
      breakBeforeTarget = breakBefore.beforeTarget;
    }
    if (breakBefore) {
      const target = this[_xfa_object.$searchNode](breakBeforeTarget, breakBefore[_xfa_object.$getParent]());
      if (target instanceof PageArea) {
        pageArea = target;
        breakBefore[_xfa_object.$extra] = {};
      }
    }
    if (!pageArea) {
      pageArea = pageAreas[0];
    }
    pageArea[_xfa_object.$extra] = {
      numberOfUse: 1
    };
    const pageAreaParent = pageArea[_xfa_object.$getParent]();
    pageAreaParent[_xfa_object.$extra] = {
      numberOfUse: 1,
      pageIndex: pageAreaParent.pageArea.children.indexOf(pageArea),
      pageSetIndex: 0
    };
    let targetPageArea;
    let leader = null;
    let trailer = null;
    let hasSomething = true;
    let hasSomethingCounter = 0;
    let startIndex = 0;
    while (true) {
      if (!hasSomething) {
        mainHtml.children.pop();
        if (++hasSomethingCounter === MAX_EMPTY_PAGES) {
          (0, _util.warn)("XFA - Something goes wrong: please file a bug.");
          return mainHtml;
        }
      } else {
        hasSomethingCounter = 0;
      }
      targetPageArea = null;
      this[_xfa_object.$extra].currentPageArea = pageArea;
      const page = pageArea[_xfa_object.$toHTML]().html;
      mainHtml.children.push(page);
      if (leader) {
        this[_xfa_object.$extra].noLayoutFailure = true;
        page.children.push(leader[_xfa_object.$toHTML](pageArea[_xfa_object.$extra].space).html);
        leader = null;
      }
      if (trailer) {
        this[_xfa_object.$extra].noLayoutFailure = true;
        page.children.push(trailer[_xfa_object.$toHTML](pageArea[_xfa_object.$extra].space).html);
        trailer = null;
      }
      const contentAreas = pageArea.contentArea.children;
      const htmlContentAreas = page.children.filter(node => node.attributes.class.includes("xfaContentarea"));
      hasSomething = false;
      this[_xfa_object.$extra].firstUnsplittable = null;
      this[_xfa_object.$extra].noLayoutFailure = false;
      const flush = index => {
        const html = root[_xfa_object.$flushHTML]();
        if (html) {
          hasSomething = hasSomething || html.children && html.children.length !== 0;
          htmlContentAreas[index].children.push(html);
        }
      };
      for (let i = startIndex, ii = contentAreas.length; i < ii; i++) {
        const contentArea = this[_xfa_object.$extra].currentContentArea = contentAreas[i];
        const space = {
          width: contentArea.w,
          height: contentArea.h
        };
        startIndex = 0;
        if (leader) {
          htmlContentAreas[i].children.push(leader[_xfa_object.$toHTML](space).html);
          leader = null;
        }
        if (trailer) {
          htmlContentAreas[i].children.push(trailer[_xfa_object.$toHTML](space).html);
          trailer = null;
        }
        const html = root[_xfa_object.$toHTML](space);
        if (html.success) {
          if (html.html) {
            hasSomething = hasSomething || html.html.children && html.html.children.length !== 0;
            htmlContentAreas[i].children.push(html.html);
          } else if (!hasSomething && mainHtml.children.length > 1) {
            mainHtml.children.pop();
          }
          return mainHtml;
        }
        if (html.isBreak()) {
          const node = html.breakNode;
          flush(i);
          if (node.targetType === "auto") {
            continue;
          }
          if (node.leader) {
            leader = this[_xfa_object.$searchNode](node.leader, node[_xfa_object.$getParent]());
            leader = leader ? leader[0] : null;
          }
          if (node.trailer) {
            trailer = this[_xfa_object.$searchNode](node.trailer, node[_xfa_object.$getParent]());
            trailer = trailer ? trailer[0] : null;
          }
          if (node.targetType === "pageArea") {
            targetPageArea = node[_xfa_object.$extra].target;
            i = Infinity;
          } else if (!node[_xfa_object.$extra].target) {
            i = node[_xfa_object.$extra].index;
          } else {
            targetPageArea = node[_xfa_object.$extra].target;
            startIndex = node[_xfa_object.$extra].index + 1;
            i = Infinity;
          }
          continue;
        }
        if (this[_xfa_object.$extra].overflowNode) {
          const node = this[_xfa_object.$extra].overflowNode;
          this[_xfa_object.$extra].overflowNode = null;
          const overflowExtra = node[_xfa_object.$getExtra]();
          const target = overflowExtra.target;
          overflowExtra.addLeader = overflowExtra.leader !== null;
          overflowExtra.addTrailer = overflowExtra.trailer !== null;
          flush(i);
          const currentIndex = i;
          i = Infinity;
          if (target instanceof PageArea) {
            targetPageArea = target;
          } else if (target instanceof ContentArea) {
            const index = contentAreas.indexOf(target);
            if (index !== -1) {
              if (index > currentIndex) {
                i = index - 1;
              } else {
                startIndex = index;
              }
            } else {
              targetPageArea = target[_xfa_object.$getParent]();
              startIndex = targetPageArea.contentArea.children.indexOf(target);
            }
          }
          continue;
        }
        flush(i);
      }
      this[_xfa_object.$extra].pageNumber += 1;
      if (targetPageArea) {
        if (targetPageArea[_xfa_object.$isUsable]()) {
          targetPageArea[_xfa_object.$extra].numberOfUse += 1;
        } else {
          targetPageArea = null;
        }
      }
      pageArea = targetPageArea || pageArea[_xfa_object.$getNextPage]();
      yield null;
    }
  }
}
exports.Template = Template;
class Text extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "text");
    this.id = attributes.id || "";
    this.maxChars = (0, _utils.getInteger)({
      data: attributes.maxChars,
      defaultValue: 0,
      validate: x => x >= 0
    });
    this.name = attributes.name || "";
    this.rid = attributes.rid || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$acceptWhitespace]() {
    return true;
  }
  [_xfa_object.$onChild](child) {
    if (child[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.xhtml.id) {
      this[_xfa_object.$content] = child;
      return true;
    }
    (0, _util.warn)(`XFA - Invalid content in Text: ${child[_xfa_object.$nodeName]}.`);
    return false;
  }
  [_xfa_object.$onText](str) {
    if (this[_xfa_object.$content] instanceof _xfa_object.XFAObject) {
      return;
    }
    super[_xfa_object.$onText](str);
  }
  [_xfa_object.$finalize]() {
    if (typeof this[_xfa_object.$content] === "string") {
      this[_xfa_object.$content] = this[_xfa_object.$content].replace(/\r\n/g, "\n");
    }
  }
  [_xfa_object.$getExtra]() {
    if (typeof this[_xfa_object.$content] === "string") {
      return this[_xfa_object.$content].split(/[\u2029\u2028\n]/).reduce((acc, line) => {
        if (line) {
          acc.push(line);
        }
        return acc;
      }, []).join("\n");
    }
    return this[_xfa_object.$content][_xfa_object.$text]();
  }
  [_xfa_object.$toHTML](availableSpace) {
    if (typeof this[_xfa_object.$content] === "string") {
      const html = valueToHtml(this[_xfa_object.$content]).html;
      if (this[_xfa_object.$content].includes("\u2029")) {
        html.name = "div";
        html.children = [];
        this[_xfa_object.$content].split("\u2029").map(para => para.split(/[\u2028\n]/).reduce((acc, line) => {
          acc.push({
            name: "span",
            value: line
          }, {
            name: "br"
          });
          return acc;
        }, [])).forEach(lines => {
          html.children.push({
            name: "p",
            children: lines
          });
        });
      } else if (/[\u2028\n]/.test(this[_xfa_object.$content])) {
        html.name = "div";
        html.children = [];
        this[_xfa_object.$content].split(/[\u2028\n]/).forEach(line => {
          html.children.push({
            name: "span",
            value: line
          }, {
            name: "br"
          });
        });
      }
      return _utils.HTMLResult.success(html);
    }
    return this[_xfa_object.$content][_xfa_object.$toHTML](availableSpace);
  }
}
exports.Text = Text;
class TextEdit extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "textEdit", true);
    this.allowRichText = (0, _utils.getInteger)({
      data: attributes.allowRichText,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.hScrollPolicy = (0, _utils.getStringOption)(attributes.hScrollPolicy, ["auto", "off", "on"]);
    this.id = attributes.id || "";
    this.multiLine = (0, _utils.getInteger)({
      data: attributes.multiLine,
      defaultValue: "",
      validate: x => x === 0 || x === 1
    });
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.vScrollPolicy = (0, _utils.getStringOption)(attributes.vScrollPolicy, ["auto", "off", "on"]);
    this.border = null;
    this.comb = null;
    this.extras = null;
    this.margin = null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    const style = (0, _html_utils.toStyle)(this, "border", "font", "margin");
    let html;
    const field = this[_xfa_object.$getParent]()[_xfa_object.$getParent]();
    if (this.multiLine === "") {
      this.multiLine = field instanceof Draw ? 1 : 0;
    }
    if (this.multiLine === 1) {
      html = {
        name: "textarea",
        attributes: {
          dataId: field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid],
          fieldId: field[_xfa_object.$uid],
          class: ["xfaTextfield"],
          style,
          "aria-label": ariaLabel(field),
          "aria-required": false
        }
      };
    } else {
      html = {
        name: "input",
        attributes: {
          type: "text",
          dataId: field[_xfa_object.$data] && field[_xfa_object.$data][_xfa_object.$uid] || field[_xfa_object.$uid],
          fieldId: field[_xfa_object.$uid],
          class: ["xfaTextfield"],
          style,
          "aria-label": ariaLabel(field),
          "aria-required": false
        }
      };
    }
    if (isRequired(field)) {
      html.attributes["aria-required"] = true;
      html.attributes.required = true;
    }
    return _utils.HTMLResult.success({
      name: "label",
      attributes: {
        class: ["xfaLabel"]
      },
      children: [html]
    });
  }
}
class Time extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "time");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
  [_xfa_object.$finalize]() {
    const date = this[_xfa_object.$content].trim();
    this[_xfa_object.$content] = date ? new Date(date) : null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    return valueToHtml(this[_xfa_object.$content] ? this[_xfa_object.$content].toString() : "");
  }
}
class TimeStamp extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "timeStamp");
    this.id = attributes.id || "";
    this.server = attributes.server || "";
    this.type = (0, _utils.getStringOption)(attributes.type, ["optional", "required"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class ToolTip extends _xfa_object.StringObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "toolTip");
    this.id = attributes.id || "";
    this.rid = attributes.rid || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Traversal extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "traversal", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.traverse = new _xfa_object.XFAObjectArray();
  }
}
class Traverse extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "traverse", true);
    this.id = attributes.id || "";
    this.operation = (0, _utils.getStringOption)(attributes.operation, ["next", "back", "down", "first", "left", "right", "up"]);
    this.ref = attributes.ref || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.script = null;
  }
  get name() {
    return this.operation;
  }
  [_xfa_object.$isTransparent]() {
    return false;
  }
}
class Ui extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "ui", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.picture = null;
    this.barcode = null;
    this.button = null;
    this.checkButton = null;
    this.choiceList = null;
    this.dateTimeEdit = null;
    this.defaultUi = null;
    this.imageEdit = null;
    this.numericEdit = null;
    this.passwordEdit = null;
    this.signature = null;
    this.textEdit = null;
  }
  [_xfa_object.$getExtra]() {
    if (this[_xfa_object.$extra] === undefined) {
      for (const name of Object.getOwnPropertyNames(this)) {
        if (name === "extras" || name === "picture") {
          continue;
        }
        const obj = this[name];
        if (!(obj instanceof _xfa_object.XFAObject)) {
          continue;
        }
        this[_xfa_object.$extra] = obj;
        return obj;
      }
      this[_xfa_object.$extra] = null;
    }
    return this[_xfa_object.$extra];
  }
  [_xfa_object.$toHTML](availableSpace) {
    const obj = this[_xfa_object.$getExtra]();
    if (obj) {
      return obj[_xfa_object.$toHTML](availableSpace);
    }
    return _utils.HTMLResult.EMPTY;
  }
}
class Validate extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "validate", true);
    this.formatTest = (0, _utils.getStringOption)(attributes.formatTest, ["warning", "disabled", "error"]);
    this.id = attributes.id || "";
    this.nullTest = (0, _utils.getStringOption)(attributes.nullTest, ["disabled", "error", "warning"]);
    this.scriptTest = (0, _utils.getStringOption)(attributes.scriptTest, ["error", "disabled", "warning"]);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.extras = null;
    this.message = null;
    this.picture = null;
    this.script = null;
  }
}
class Value extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "value", true);
    this.id = attributes.id || "";
    this.override = (0, _utils.getInteger)({
      data: attributes.override,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.relevant = (0, _utils.getRelevant)(attributes.relevant);
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.arc = null;
    this.boolean = null;
    this.date = null;
    this.dateTime = null;
    this.decimal = null;
    this.exData = null;
    this.float = null;
    this.image = null;
    this.integer = null;
    this.line = null;
    this.rectangle = null;
    this.text = null;
    this.time = null;
  }
  [_xfa_object.$setValue](value) {
    const parent = this[_xfa_object.$getParent]();
    if (parent instanceof Field) {
      if (parent.ui && parent.ui.imageEdit) {
        if (!this.image) {
          this.image = new Image({});
          this[_xfa_object.$appendChild](this.image);
        }
        this.image[_xfa_object.$content] = value[_xfa_object.$content];
        return;
      }
    }
    const valueName = value[_xfa_object.$nodeName];
    if (this[valueName] !== null) {
      this[valueName][_xfa_object.$content] = value[_xfa_object.$content];
      return;
    }
    for (const name of Object.getOwnPropertyNames(this)) {
      const obj = this[name];
      if (obj instanceof _xfa_object.XFAObject) {
        this[name] = null;
        this[_xfa_object.$removeChild](obj);
      }
    }
    this[value[_xfa_object.$nodeName]] = value;
    this[_xfa_object.$appendChild](value);
  }
  [_xfa_object.$text]() {
    if (this.exData) {
      if (typeof this.exData[_xfa_object.$content] === "string") {
        return this.exData[_xfa_object.$content].trim();
      }
      return this.exData[_xfa_object.$content][_xfa_object.$text]().trim();
    }
    for (const name of Object.getOwnPropertyNames(this)) {
      if (name === "image") {
        continue;
      }
      const obj = this[name];
      if (obj instanceof _xfa_object.XFAObject) {
        return (obj[_xfa_object.$content] || "").toString().trim();
      }
    }
    return null;
  }
  [_xfa_object.$toHTML](availableSpace) {
    for (const name of Object.getOwnPropertyNames(this)) {
      const obj = this[name];
      if (!(obj instanceof _xfa_object.XFAObject)) {
        continue;
      }
      return obj[_xfa_object.$toHTML](availableSpace);
    }
    return _utils.HTMLResult.EMPTY;
  }
}
exports.Value = Value;
class Variables extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(TEMPLATE_NS_ID, "variables", true);
    this.id = attributes.id || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
    this.boolean = new _xfa_object.XFAObjectArray();
    this.date = new _xfa_object.XFAObjectArray();
    this.dateTime = new _xfa_object.XFAObjectArray();
    this.decimal = new _xfa_object.XFAObjectArray();
    this.exData = new _xfa_object.XFAObjectArray();
    this.float = new _xfa_object.XFAObjectArray();
    this.image = new _xfa_object.XFAObjectArray();
    this.integer = new _xfa_object.XFAObjectArray();
    this.manifest = new _xfa_object.XFAObjectArray();
    this.script = new _xfa_object.XFAObjectArray();
    this.text = new _xfa_object.XFAObjectArray();
    this.time = new _xfa_object.XFAObjectArray();
  }
  [_xfa_object.$isTransparent]() {
    return true;
  }
}
class TemplateNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (TemplateNamespace.hasOwnProperty(name)) {
      const node = TemplateNamespace[name](attributes);
      node[_xfa_object.$setSetAttributes](attributes);
      return node;
    }
    return undefined;
  }
  static appearanceFilter(attrs) {
    return new AppearanceFilter(attrs);
  }
  static arc(attrs) {
    return new Arc(attrs);
  }
  static area(attrs) {
    return new Area(attrs);
  }
  static assist(attrs) {
    return new Assist(attrs);
  }
  static barcode(attrs) {
    return new Barcode(attrs);
  }
  static bind(attrs) {
    return new Bind(attrs);
  }
  static bindItems(attrs) {
    return new BindItems(attrs);
  }
  static bookend(attrs) {
    return new Bookend(attrs);
  }
  static boolean(attrs) {
    return new BooleanElement(attrs);
  }
  static border(attrs) {
    return new Border(attrs);
  }
  static break(attrs) {
    return new Break(attrs);
  }
  static breakAfter(attrs) {
    return new BreakAfter(attrs);
  }
  static breakBefore(attrs) {
    return new BreakBefore(attrs);
  }
  static button(attrs) {
    return new Button(attrs);
  }
  static calculate(attrs) {
    return new Calculate(attrs);
  }
  static caption(attrs) {
    return new Caption(attrs);
  }
  static certificate(attrs) {
    return new Certificate(attrs);
  }
  static certificates(attrs) {
    return new Certificates(attrs);
  }
  static checkButton(attrs) {
    return new CheckButton(attrs);
  }
  static choiceList(attrs) {
    return new ChoiceList(attrs);
  }
  static color(attrs) {
    return new Color(attrs);
  }
  static comb(attrs) {
    return new Comb(attrs);
  }
  static connect(attrs) {
    return new Connect(attrs);
  }
  static contentArea(attrs) {
    return new ContentArea(attrs);
  }
  static corner(attrs) {
    return new Corner(attrs);
  }
  static date(attrs) {
    return new DateElement(attrs);
  }
  static dateTime(attrs) {
    return new DateTime(attrs);
  }
  static dateTimeEdit(attrs) {
    return new DateTimeEdit(attrs);
  }
  static decimal(attrs) {
    return new Decimal(attrs);
  }
  static defaultUi(attrs) {
    return new DefaultUi(attrs);
  }
  static desc(attrs) {
    return new Desc(attrs);
  }
  static digestMethod(attrs) {
    return new DigestMethod(attrs);
  }
  static digestMethods(attrs) {
    return new DigestMethods(attrs);
  }
  static draw(attrs) {
    return new Draw(attrs);
  }
  static edge(attrs) {
    return new Edge(attrs);
  }
  static encoding(attrs) {
    return new Encoding(attrs);
  }
  static encodings(attrs) {
    return new Encodings(attrs);
  }
  static encrypt(attrs) {
    return new Encrypt(attrs);
  }
  static encryptData(attrs) {
    return new EncryptData(attrs);
  }
  static encryption(attrs) {
    return new Encryption(attrs);
  }
  static encryptionMethod(attrs) {
    return new EncryptionMethod(attrs);
  }
  static encryptionMethods(attrs) {
    return new EncryptionMethods(attrs);
  }
  static event(attrs) {
    return new Event(attrs);
  }
  static exData(attrs) {
    return new ExData(attrs);
  }
  static exObject(attrs) {
    return new ExObject(attrs);
  }
  static exclGroup(attrs) {
    return new ExclGroup(attrs);
  }
  static execute(attrs) {
    return new Execute(attrs);
  }
  static extras(attrs) {
    return new Extras(attrs);
  }
  static field(attrs) {
    return new Field(attrs);
  }
  static fill(attrs) {
    return new Fill(attrs);
  }
  static filter(attrs) {
    return new Filter(attrs);
  }
  static float(attrs) {
    return new Float(attrs);
  }
  static font(attrs) {
    return new Font(attrs);
  }
  static format(attrs) {
    return new Format(attrs);
  }
  static handler(attrs) {
    return new Handler(attrs);
  }
  static hyphenation(attrs) {
    return new Hyphenation(attrs);
  }
  static image(attrs) {
    return new Image(attrs);
  }
  static imageEdit(attrs) {
    return new ImageEdit(attrs);
  }
  static integer(attrs) {
    return new Integer(attrs);
  }
  static issuers(attrs) {
    return new Issuers(attrs);
  }
  static items(attrs) {
    return new Items(attrs);
  }
  static keep(attrs) {
    return new Keep(attrs);
  }
  static keyUsage(attrs) {
    return new KeyUsage(attrs);
  }
  static line(attrs) {
    return new Line(attrs);
  }
  static linear(attrs) {
    return new Linear(attrs);
  }
  static lockDocument(attrs) {
    return new LockDocument(attrs);
  }
  static manifest(attrs) {
    return new Manifest(attrs);
  }
  static margin(attrs) {
    return new Margin(attrs);
  }
  static mdp(attrs) {
    return new Mdp(attrs);
  }
  static medium(attrs) {
    return new Medium(attrs);
  }
  static message(attrs) {
    return new Message(attrs);
  }
  static numericEdit(attrs) {
    return new NumericEdit(attrs);
  }
  static occur(attrs) {
    return new Occur(attrs);
  }
  static oid(attrs) {
    return new Oid(attrs);
  }
  static oids(attrs) {
    return new Oids(attrs);
  }
  static overflow(attrs) {
    return new Overflow(attrs);
  }
  static pageArea(attrs) {
    return new PageArea(attrs);
  }
  static pageSet(attrs) {
    return new PageSet(attrs);
  }
  static para(attrs) {
    return new Para(attrs);
  }
  static passwordEdit(attrs) {
    return new PasswordEdit(attrs);
  }
  static pattern(attrs) {
    return new Pattern(attrs);
  }
  static picture(attrs) {
    return new Picture(attrs);
  }
  static proto(attrs) {
    return new Proto(attrs);
  }
  static radial(attrs) {
    return new Radial(attrs);
  }
  static reason(attrs) {
    return new Reason(attrs);
  }
  static reasons(attrs) {
    return new Reasons(attrs);
  }
  static rectangle(attrs) {
    return new Rectangle(attrs);
  }
  static ref(attrs) {
    return new RefElement(attrs);
  }
  static script(attrs) {
    return new Script(attrs);
  }
  static setProperty(attrs) {
    return new SetProperty(attrs);
  }
  static signData(attrs) {
    return new SignData(attrs);
  }
  static signature(attrs) {
    return new Signature(attrs);
  }
  static signing(attrs) {
    return new Signing(attrs);
  }
  static solid(attrs) {
    return new Solid(attrs);
  }
  static speak(attrs) {
    return new Speak(attrs);
  }
  static stipple(attrs) {
    return new Stipple(attrs);
  }
  static subform(attrs) {
    return new Subform(attrs);
  }
  static subformSet(attrs) {
    return new SubformSet(attrs);
  }
  static subjectDN(attrs) {
    return new SubjectDN(attrs);
  }
  static subjectDNs(attrs) {
    return new SubjectDNs(attrs);
  }
  static submit(attrs) {
    return new Submit(attrs);
  }
  static template(attrs) {
    return new Template(attrs);
  }
  static text(attrs) {
    return new Text(attrs);
  }
  static textEdit(attrs) {
    return new TextEdit(attrs);
  }
  static time(attrs) {
    return new Time(attrs);
  }
  static timeStamp(attrs) {
    return new TimeStamp(attrs);
  }
  static toolTip(attrs) {
    return new ToolTip(attrs);
  }
  static traversal(attrs) {
    return new Traversal(attrs);
  }
  static traverse(attrs) {
    return new Traverse(attrs);
  }
  static ui(attrs) {
    return new Ui(attrs);
  }
  static validate(attrs) {
    return new Validate(attrs);
  }
  static value(attrs) {
    return new Value(attrs);
  }
  static variables(attrs) {
    return new Variables(attrs);
  }
}
exports.TemplateNamespace = TemplateNamespace;

/***/ }),
/* 81 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.addHTML = addHTML;
exports.checkDimensions = checkDimensions;
exports.flushHTML = flushHTML;
exports.getAvailableSpace = getAvailableSpace;
var _xfa_object = __w_pdfjs_require__(75);
var _html_utils = __w_pdfjs_require__(82);
function createLine(node, children) {
  return {
    name: "div",
    attributes: {
      class: [node.layout === "lr-tb" ? "xfaLr" : "xfaRl"]
    },
    children
  };
}
function flushHTML(node) {
  if (!node[_xfa_object.$extra]) {
    return null;
  }
  const attributes = node[_xfa_object.$extra].attributes;
  const html = {
    name: "div",
    attributes,
    children: node[_xfa_object.$extra].children
  };
  if (node[_xfa_object.$extra].failingNode) {
    const htmlFromFailing = node[_xfa_object.$extra].failingNode[_xfa_object.$flushHTML]();
    if (htmlFromFailing) {
      if (node.layout.endsWith("-tb")) {
        html.children.push(createLine(node, [htmlFromFailing]));
      } else {
        html.children.push(htmlFromFailing);
      }
    }
  }
  if (html.children.length === 0) {
    return null;
  }
  return html;
}
function addHTML(node, html, bbox) {
  const extra = node[_xfa_object.$extra];
  const availableSpace = extra.availableSpace;
  const [x, y, w, h] = bbox;
  switch (node.layout) {
    case "position":
      {
        extra.width = Math.max(extra.width, x + w);
        extra.height = Math.max(extra.height, y + h);
        extra.children.push(html);
        break;
      }
    case "lr-tb":
    case "rl-tb":
      if (!extra.line || extra.attempt === 1) {
        extra.line = createLine(node, []);
        extra.children.push(extra.line);
        extra.numberInLine = 0;
      }
      extra.numberInLine += 1;
      extra.line.children.push(html);
      if (extra.attempt === 0) {
        extra.currentWidth += w;
        extra.height = Math.max(extra.height, extra.prevHeight + h);
      } else {
        extra.currentWidth = w;
        extra.prevHeight = extra.height;
        extra.height += h;
        extra.attempt = 0;
      }
      extra.width = Math.max(extra.width, extra.currentWidth);
      break;
    case "rl-row":
    case "row":
      {
        extra.children.push(html);
        extra.width += w;
        extra.height = Math.max(extra.height, h);
        const height = (0, _html_utils.measureToString)(extra.height);
        for (const child of extra.children) {
          child.attributes.style.height = height;
        }
        break;
      }
    case "table":
      {
        extra.width = Math.min(availableSpace.width, Math.max(extra.width, w));
        extra.height += h;
        extra.children.push(html);
        break;
      }
    case "tb":
      {
        extra.width = Math.min(availableSpace.width, Math.max(extra.width, w));
        extra.height += h;
        extra.children.push(html);
        break;
      }
  }
}
function getAvailableSpace(node) {
  const availableSpace = node[_xfa_object.$extra].availableSpace;
  const marginV = node.margin ? node.margin.topInset + node.margin.bottomInset : 0;
  const marginH = node.margin ? node.margin.leftInset + node.margin.rightInset : 0;
  switch (node.layout) {
    case "lr-tb":
    case "rl-tb":
      if (node[_xfa_object.$extra].attempt === 0) {
        return {
          width: availableSpace.width - marginH - node[_xfa_object.$extra].currentWidth,
          height: availableSpace.height - marginV - node[_xfa_object.$extra].prevHeight
        };
      }
      return {
        width: availableSpace.width - marginH,
        height: availableSpace.height - marginV - node[_xfa_object.$extra].height
      };
    case "rl-row":
    case "row":
      const width = node[_xfa_object.$extra].columnWidths.slice(node[_xfa_object.$extra].currentColumn).reduce((a, x) => a + x);
      return {
        width,
        height: availableSpace.height - marginH
      };
    case "table":
    case "tb":
      return {
        width: availableSpace.width - marginH,
        height: availableSpace.height - marginV - node[_xfa_object.$extra].height
      };
    case "position":
    default:
      return availableSpace;
  }
}
function getTransformedBBox(node) {
  let w = node.w === "" ? NaN : node.w;
  let h = node.h === "" ? NaN : node.h;
  let [centerX, centerY] = [0, 0];
  switch (node.anchorType || "") {
    case "bottomCenter":
      [centerX, centerY] = [w / 2, h];
      break;
    case "bottomLeft":
      [centerX, centerY] = [0, h];
      break;
    case "bottomRight":
      [centerX, centerY] = [w, h];
      break;
    case "middleCenter":
      [centerX, centerY] = [w / 2, h / 2];
      break;
    case "middleLeft":
      [centerX, centerY] = [0, h / 2];
      break;
    case "middleRight":
      [centerX, centerY] = [w, h / 2];
      break;
    case "topCenter":
      [centerX, centerY] = [w / 2, 0];
      break;
    case "topRight":
      [centerX, centerY] = [w, 0];
      break;
  }
  let x, y;
  switch (node.rotate || 0) {
    case 0:
      [x, y] = [-centerX, -centerY];
      break;
    case 90:
      [x, y] = [-centerY, centerX];
      [w, h] = [h, -w];
      break;
    case 180:
      [x, y] = [centerX, centerY];
      [w, h] = [-w, -h];
      break;
    case 270:
      [x, y] = [centerY, -centerX];
      [w, h] = [-h, w];
      break;
  }
  return [node.x + x + Math.min(0, w), node.y + y + Math.min(0, h), Math.abs(w), Math.abs(h)];
}
function checkDimensions(node, space) {
  if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].firstUnsplittable === null) {
    return true;
  }
  if (node.w === 0 || node.h === 0) {
    return true;
  }
  const ERROR = 2;
  const parent = node[_xfa_object.$getSubformParent]();
  const attempt = parent[_xfa_object.$extra] && parent[_xfa_object.$extra].attempt || 0;
  const [, y, w, h] = getTransformedBBox(node);
  switch (parent.layout) {
    case "lr-tb":
    case "rl-tb":
      if (attempt === 0) {
        if (!node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
          if (node.h !== "" && Math.round(h - space.height) > ERROR) {
            return false;
          }
          if (node.w !== "") {
            if (Math.round(w - space.width) <= ERROR) {
              return true;
            }
            if (parent[_xfa_object.$extra].numberInLine === 0) {
              return space.height > ERROR;
            }
            return false;
          }
          return space.width > ERROR;
        }
        if (node.w !== "") {
          return Math.round(w - space.width) <= ERROR;
        }
        return space.width > ERROR;
      }
      if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
        return true;
      }
      if (node.h !== "" && Math.round(h - space.height) > ERROR) {
        return false;
      }
      if (node.w === "" || Math.round(w - space.width) <= ERROR) {
        return space.height > ERROR;
      }
      if (parent[_xfa_object.$isThereMoreWidth]()) {
        return false;
      }
      return space.height > ERROR;
    case "table":
    case "tb":
      if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
        return true;
      }
      if (node.h !== "" && !node[_xfa_object.$isSplittable]()) {
        return Math.round(h - space.height) <= ERROR;
      }
      if (node.w === "" || Math.round(w - space.width) <= ERROR) {
        return space.height > ERROR;
      }
      if (parent[_xfa_object.$isThereMoreWidth]()) {
        return false;
      }
      return space.height > ERROR;
    case "position":
      if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
        return true;
      }
      if (node.h === "" || Math.round(h + y - space.height) <= ERROR) {
        return true;
      }
      const area = node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].currentContentArea;
      return h + y > area.h;
    case "rl-row":
    case "row":
      if (node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].noLayoutFailure) {
        return true;
      }
      if (node.h !== "") {
        return Math.round(h - space.height) <= ERROR;
      }
      return true;
    default:
      return true;
  }
}

/***/ }),
/* 82 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.computeBbox = computeBbox;
exports.createWrapper = createWrapper;
exports.fixDimensions = fixDimensions;
exports.fixTextIndent = fixTextIndent;
exports.fixURL = fixURL;
exports.isPrintOnly = isPrintOnly;
exports.layoutClass = layoutClass;
exports.layoutNode = layoutNode;
exports.measureToString = measureToString;
exports.setAccess = setAccess;
exports.setFontFamily = setFontFamily;
exports.setMinMaxDimensions = setMinMaxDimensions;
exports.setPara = setPara;
exports.toStyle = toStyle;
var _xfa_object = __w_pdfjs_require__(75);
var _util = __w_pdfjs_require__(2);
var _utils = __w_pdfjs_require__(76);
var _fonts = __w_pdfjs_require__(83);
var _text = __w_pdfjs_require__(84);
function measureToString(m) {
  if (typeof m === "string") {
    return "0px";
  }
  return Number.isInteger(m) ? `${m}px` : `${m.toFixed(2)}px`;
}
const converters = {
  anchorType(node, style) {
    const parent = node[_xfa_object.$getSubformParent]();
    if (!parent || parent.layout && parent.layout !== "position") {
      return;
    }
    if (!("transform" in style)) {
      style.transform = "";
    }
    switch (node.anchorType) {
      case "bottomCenter":
        style.transform += "translate(-50%, -100%)";
        break;
      case "bottomLeft":
        style.transform += "translate(0,-100%)";
        break;
      case "bottomRight":
        style.transform += "translate(-100%,-100%)";
        break;
      case "middleCenter":
        style.transform += "translate(-50%,-50%)";
        break;
      case "middleLeft":
        style.transform += "translate(0,-50%)";
        break;
      case "middleRight":
        style.transform += "translate(-100%,-50%)";
        break;
      case "topCenter":
        style.transform += "translate(-50%,0)";
        break;
      case "topRight":
        style.transform += "translate(-100%,0)";
        break;
    }
  },
  dimensions(node, style) {
    const parent = node[_xfa_object.$getSubformParent]();
    let width = node.w;
    const height = node.h;
    if (parent.layout && parent.layout.includes("row")) {
      const extra = parent[_xfa_object.$extra];
      const colSpan = node.colSpan;
      let w;
      if (colSpan === -1) {
        w = extra.columnWidths.slice(extra.currentColumn).reduce((a, x) => a + x, 0);
        extra.currentColumn = 0;
      } else {
        w = extra.columnWidths.slice(extra.currentColumn, extra.currentColumn + colSpan).reduce((a, x) => a + x, 0);
        extra.currentColumn = (extra.currentColumn + node.colSpan) % extra.columnWidths.length;
      }
      if (!isNaN(w)) {
        width = node.w = w;
      }
    }
    if (width !== "") {
      style.width = measureToString(width);
    } else {
      style.width = "auto";
    }
    if (height !== "") {
      style.height = measureToString(height);
    } else {
      style.height = "auto";
    }
  },
  position(node, style) {
    const parent = node[_xfa_object.$getSubformParent]();
    if (parent && parent.layout && parent.layout !== "position") {
      return;
    }
    style.position = "absolute";
    style.left = measureToString(node.x);
    style.top = measureToString(node.y);
  },
  rotate(node, style) {
    if (node.rotate) {
      if (!("transform" in style)) {
        style.transform = "";
      }
      style.transform += `rotate(-${node.rotate}deg)`;
      style.transformOrigin = "top left";
    }
  },
  presence(node, style) {
    switch (node.presence) {
      case "invisible":
        style.visibility = "hidden";
        break;
      case "hidden":
      case "inactive":
        style.display = "none";
        break;
    }
  },
  hAlign(node, style) {
    if (node[_xfa_object.$nodeName] === "para") {
      switch (node.hAlign) {
        case "justifyAll":
          style.textAlign = "justify-all";
          break;
        case "radix":
          style.textAlign = "left";
          break;
        default:
          style.textAlign = node.hAlign;
      }
    } else {
      switch (node.hAlign) {
        case "left":
          style.alignSelf = "start";
          break;
        case "center":
          style.alignSelf = "center";
          break;
        case "right":
          style.alignSelf = "end";
          break;
      }
    }
  },
  margin(node, style) {
    if (node.margin) {
      style.margin = node.margin[_xfa_object.$toStyle]().margin;
    }
  }
};
function setMinMaxDimensions(node, style) {
  const parent = node[_xfa_object.$getSubformParent]();
  if (parent.layout === "position") {
    if (node.minW > 0) {
      style.minWidth = measureToString(node.minW);
    }
    if (node.maxW > 0) {
      style.maxWidth = measureToString(node.maxW);
    }
    if (node.minH > 0) {
      style.minHeight = measureToString(node.minH);
    }
    if (node.maxH > 0) {
      style.maxHeight = measureToString(node.maxH);
    }
  }
}
function layoutText(text, xfaFont, margin, lineHeight, fontFinder, width) {
  const measure = new _text.TextMeasure(xfaFont, margin, lineHeight, fontFinder);
  if (typeof text === "string") {
    measure.addString(text);
  } else {
    text[_xfa_object.$pushGlyphs](measure);
  }
  return measure.compute(width);
}
function layoutNode(node, availableSpace) {
  let height = null;
  let width = null;
  let isBroken = false;
  if ((!node.w || !node.h) && node.value) {
    let marginH = 0;
    let marginV = 0;
    if (node.margin) {
      marginH = node.margin.leftInset + node.margin.rightInset;
      marginV = node.margin.topInset + node.margin.bottomInset;
    }
    let lineHeight = null;
    let margin = null;
    if (node.para) {
      margin = Object.create(null);
      lineHeight = node.para.lineHeight === "" ? null : node.para.lineHeight;
      margin.top = node.para.spaceAbove === "" ? 0 : node.para.spaceAbove;
      margin.bottom = node.para.spaceBelow === "" ? 0 : node.para.spaceBelow;
      margin.left = node.para.marginLeft === "" ? 0 : node.para.marginLeft;
      margin.right = node.para.marginRight === "" ? 0 : node.para.marginRight;
    }
    let font = node.font;
    if (!font) {
      const root = node[_xfa_object.$getTemplateRoot]();
      let parent = node[_xfa_object.$getParent]();
      while (parent && parent !== root) {
        if (parent.font) {
          font = parent.font;
          break;
        }
        parent = parent[_xfa_object.$getParent]();
      }
    }
    const maxWidth = (node.w || availableSpace.width) - marginH;
    const fontFinder = node[_xfa_object.$globalData].fontFinder;
    if (node.value.exData && node.value.exData[_xfa_object.$content] && node.value.exData.contentType === "text/html") {
      const res = layoutText(node.value.exData[_xfa_object.$content], font, margin, lineHeight, fontFinder, maxWidth);
      width = res.width;
      height = res.height;
      isBroken = res.isBroken;
    } else {
      const text = node.value[_xfa_object.$text]();
      if (text) {
        const res = layoutText(text, font, margin, lineHeight, fontFinder, maxWidth);
        width = res.width;
        height = res.height;
        isBroken = res.isBroken;
      }
    }
    if (width !== null && !node.w) {
      width += marginH;
    }
    if (height !== null && !node.h) {
      height += marginV;
    }
  }
  return {
    w: width,
    h: height,
    isBroken
  };
}
function computeBbox(node, html, availableSpace) {
  let bbox;
  if (node.w !== "" && node.h !== "") {
    bbox = [node.x, node.y, node.w, node.h];
  } else {
    if (!availableSpace) {
      return null;
    }
    let width = node.w;
    if (width === "") {
      if (node.maxW === 0) {
        const parent = node[_xfa_object.$getSubformParent]();
        if (parent.layout === "position" && parent.w !== "") {
          width = 0;
        } else {
          width = node.minW;
        }
      } else {
        width = Math.min(node.maxW, availableSpace.width);
      }
      html.attributes.style.width = measureToString(width);
    }
    let height = node.h;
    if (height === "") {
      if (node.maxH === 0) {
        const parent = node[_xfa_object.$getSubformParent]();
        if (parent.layout === "position" && parent.h !== "") {
          height = 0;
        } else {
          height = node.minH;
        }
      } else {
        height = Math.min(node.maxH, availableSpace.height);
      }
      html.attributes.style.height = measureToString(height);
    }
    bbox = [node.x, node.y, width, height];
  }
  return bbox;
}
function fixDimensions(node) {
  const parent = node[_xfa_object.$getSubformParent]();
  if (parent.layout && parent.layout.includes("row")) {
    const extra = parent[_xfa_object.$extra];
    const colSpan = node.colSpan;
    let width;
    if (colSpan === -1) {
      width = extra.columnWidths.slice(extra.currentColumn).reduce((a, w) => a + w, 0);
    } else {
      width = extra.columnWidths.slice(extra.currentColumn, extra.currentColumn + colSpan).reduce((a, w) => a + w, 0);
    }
    if (!isNaN(width)) {
      node.w = width;
    }
  }
  if (parent.layout && parent.layout !== "position") {
    node.x = node.y = 0;
  }
  if (node.layout === "table") {
    if (node.w === "" && Array.isArray(node.columnWidths)) {
      node.w = node.columnWidths.reduce((a, x) => a + x, 0);
    }
  }
}
function layoutClass(node) {
  switch (node.layout) {
    case "position":
      return "xfaPosition";
    case "lr-tb":
      return "xfaLrTb";
    case "rl-row":
      return "xfaRlRow";
    case "rl-tb":
      return "xfaRlTb";
    case "row":
      return "xfaRow";
    case "table":
      return "xfaTable";
    case "tb":
      return "xfaTb";
    default:
      return "xfaPosition";
  }
}
function toStyle(node, ...names) {
  const style = Object.create(null);
  for (const name of names) {
    const value = node[name];
    if (value === null) {
      continue;
    }
    if (converters.hasOwnProperty(name)) {
      converters[name](node, style);
      continue;
    }
    if (value instanceof _xfa_object.XFAObject) {
      const newStyle = value[_xfa_object.$toStyle]();
      if (newStyle) {
        Object.assign(style, newStyle);
      } else {
        (0, _util.warn)(`(DEBUG) - XFA - style for ${name} not implemented yet`);
      }
    }
  }
  return style;
}
function createWrapper(node, html) {
  const {
    attributes
  } = html;
  const {
    style
  } = attributes;
  const wrapper = {
    name: "div",
    attributes: {
      class: ["xfaWrapper"],
      style: Object.create(null)
    },
    children: []
  };
  attributes.class.push("xfaWrapped");
  if (node.border) {
    const {
      widths,
      insets
    } = node.border[_xfa_object.$extra];
    let width, height;
    let top = insets[0];
    let left = insets[3];
    const insetsH = insets[0] + insets[2];
    const insetsW = insets[1] + insets[3];
    switch (node.border.hand) {
      case "even":
        top -= widths[0] / 2;
        left -= widths[3] / 2;
        width = `calc(100% + ${(widths[1] + widths[3]) / 2 - insetsW}px)`;
        height = `calc(100% + ${(widths[0] + widths[2]) / 2 - insetsH}px)`;
        break;
      case "left":
        top -= widths[0];
        left -= widths[3];
        width = `calc(100% + ${widths[1] + widths[3] - insetsW}px)`;
        height = `calc(100% + ${widths[0] + widths[2] - insetsH}px)`;
        break;
      case "right":
        width = insetsW ? `calc(100% - ${insetsW}px)` : "100%";
        height = insetsH ? `calc(100% - ${insetsH}px)` : "100%";
        break;
    }
    const classNames = ["xfaBorder"];
    if (isPrintOnly(node.border)) {
      classNames.push("xfaPrintOnly");
    }
    const border = {
      name: "div",
      attributes: {
        class: classNames,
        style: {
          top: `${top}px`,
          left: `${left}px`,
          width,
          height
        }
      },
      children: []
    };
    for (const key of ["border", "borderWidth", "borderColor", "borderRadius", "borderStyle"]) {
      if (style[key] !== undefined) {
        border.attributes.style[key] = style[key];
        delete style[key];
      }
    }
    wrapper.children.push(border, html);
  } else {
    wrapper.children.push(html);
  }
  for (const key of ["background", "backgroundClip", "top", "left", "width", "height", "minWidth", "minHeight", "maxWidth", "maxHeight", "transform", "transformOrigin", "visibility"]) {
    if (style[key] !== undefined) {
      wrapper.attributes.style[key] = style[key];
      delete style[key];
    }
  }
  if (style.position === "absolute") {
    wrapper.attributes.style.position = "absolute";
  } else {
    wrapper.attributes.style.position = "relative";
  }
  delete style.position;
  if (style.alignSelf) {
    wrapper.attributes.style.alignSelf = style.alignSelf;
    delete style.alignSelf;
  }
  return wrapper;
}
function fixTextIndent(styles) {
  const indent = (0, _utils.getMeasurement)(styles.textIndent, "0px");
  if (indent >= 0) {
    return;
  }
  const align = styles.textAlign === "right" ? "right" : "left";
  const name = "padding" + (align === "left" ? "Left" : "Right");
  const padding = (0, _utils.getMeasurement)(styles[name], "0px");
  styles[name] = `${padding - indent}px`;
}
function setAccess(node, classNames) {
  switch (node.access) {
    case "nonInteractive":
      classNames.push("xfaNonInteractive");
      break;
    case "readOnly":
      classNames.push("xfaReadOnly");
      break;
    case "protected":
      classNames.push("xfaDisabled");
      break;
  }
}
function isPrintOnly(node) {
  return node.relevant.length > 0 && !node.relevant[0].excluded && node.relevant[0].viewname === "print";
}
function getCurrentPara(node) {
  const stack = node[_xfa_object.$getTemplateRoot]()[_xfa_object.$extra].paraStack;
  return stack.length ? stack.at(-1) : null;
}
function setPara(node, nodeStyle, value) {
  if (value.attributes.class && value.attributes.class.includes("xfaRich")) {
    if (nodeStyle) {
      if (node.h === "") {
        nodeStyle.height = "auto";
      }
      if (node.w === "") {
        nodeStyle.width = "auto";
      }
    }
    const para = getCurrentPara(node);
    if (para) {
      const valueStyle = value.attributes.style;
      valueStyle.display = "flex";
      valueStyle.flexDirection = "column";
      switch (para.vAlign) {
        case "top":
          valueStyle.justifyContent = "start";
          break;
        case "bottom":
          valueStyle.justifyContent = "end";
          break;
        case "middle":
          valueStyle.justifyContent = "center";
          break;
      }
      const paraStyle = para[_xfa_object.$toStyle]();
      for (const [key, val] of Object.entries(paraStyle)) {
        if (!(key in valueStyle)) {
          valueStyle[key] = val;
        }
      }
    }
  }
}
function setFontFamily(xfaFont, node, fontFinder, style) {
  if (!fontFinder) {
    delete style.fontFamily;
    return;
  }
  const name = (0, _utils.stripQuotes)(xfaFont.typeface);
  style.fontFamily = `"${name}"`;
  const typeface = fontFinder.find(name);
  if (typeface) {
    const {
      fontFamily
    } = typeface.regular.cssFontInfo;
    if (fontFamily !== name) {
      style.fontFamily = `"${fontFamily}"`;
    }
    const para = getCurrentPara(node);
    if (para && para.lineHeight !== "") {
      return;
    }
    if (style.lineHeight) {
      return;
    }
    const pdfFont = (0, _fonts.selectFont)(xfaFont, typeface);
    if (pdfFont) {
      style.lineHeight = Math.max(1.2, pdfFont.lineHeight);
    }
  }
}
function fixURL(str) {
  const absoluteUrl = (0, _util.createValidAbsoluteUrl)(str, null, {
    addDefaultProtocol: true,
    tryConvertEncoding: true
  });
  return absoluteUrl ? absoluteUrl.href : null;
}

/***/ }),
/* 83 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.FontFinder = void 0;
exports.getMetrics = getMetrics;
exports.selectFont = selectFont;
var _xfa_object = __w_pdfjs_require__(75);
var _utils = __w_pdfjs_require__(76);
var _util = __w_pdfjs_require__(2);
class FontFinder {
  constructor(pdfFonts) {
    this.fonts = new Map();
    this.cache = new Map();
    this.warned = new Set();
    this.defaultFont = null;
    this.add(pdfFonts);
  }
  add(pdfFonts, reallyMissingFonts = null) {
    for (const pdfFont of pdfFonts) {
      this.addPdfFont(pdfFont);
    }
    for (const pdfFont of this.fonts.values()) {
      if (!pdfFont.regular) {
        pdfFont.regular = pdfFont.italic || pdfFont.bold || pdfFont.bolditalic;
      }
    }
    if (!reallyMissingFonts || reallyMissingFonts.size === 0) {
      return;
    }
    const myriad = this.fonts.get("PdfJS-Fallback-PdfJS-XFA");
    for (const missing of reallyMissingFonts) {
      this.fonts.set(missing, myriad);
    }
  }
  addPdfFont(pdfFont) {
    const cssFontInfo = pdfFont.cssFontInfo;
    const name = cssFontInfo.fontFamily;
    let font = this.fonts.get(name);
    if (!font) {
      font = Object.create(null);
      this.fonts.set(name, font);
      if (!this.defaultFont) {
        this.defaultFont = font;
      }
    }
    let property = "";
    const fontWeight = parseFloat(cssFontInfo.fontWeight);
    if (parseFloat(cssFontInfo.italicAngle) !== 0) {
      property = fontWeight >= 700 ? "bolditalic" : "italic";
    } else if (fontWeight >= 700) {
      property = "bold";
    }
    if (!property) {
      if (pdfFont.name.includes("Bold") || pdfFont.psName && pdfFont.psName.includes("Bold")) {
        property = "bold";
      }
      if (pdfFont.name.includes("Italic") || pdfFont.name.endsWith("It") || pdfFont.psName && (pdfFont.psName.includes("Italic") || pdfFont.psName.endsWith("It"))) {
        property += "italic";
      }
    }
    if (!property) {
      property = "regular";
    }
    font[property] = pdfFont;
  }
  getDefault() {
    return this.defaultFont;
  }
  find(fontName, mustWarn = true) {
    let font = this.fonts.get(fontName) || this.cache.get(fontName);
    if (font) {
      return font;
    }
    const pattern = /,|-|_| |bolditalic|bold|italic|regular|it/gi;
    let name = fontName.replace(pattern, "");
    font = this.fonts.get(name);
    if (font) {
      this.cache.set(fontName, font);
      return font;
    }
    name = name.toLowerCase();
    const maybe = [];
    for (const [family, pdfFont] of this.fonts.entries()) {
      if (family.replace(pattern, "").toLowerCase().startsWith(name)) {
        maybe.push(pdfFont);
      }
    }
    if (maybe.length === 0) {
      for (const [, pdfFont] of this.fonts.entries()) {
        if (pdfFont.regular.name && pdfFont.regular.name.replace(pattern, "").toLowerCase().startsWith(name)) {
          maybe.push(pdfFont);
        }
      }
    }
    if (maybe.length === 0) {
      name = name.replace(/psmt|mt/gi, "");
      for (const [family, pdfFont] of this.fonts.entries()) {
        if (family.replace(pattern, "").toLowerCase().startsWith(name)) {
          maybe.push(pdfFont);
        }
      }
    }
    if (maybe.length === 0) {
      for (const pdfFont of this.fonts.values()) {
        if (pdfFont.regular.name && pdfFont.regular.name.replace(pattern, "").toLowerCase().startsWith(name)) {
          maybe.push(pdfFont);
        }
      }
    }
    if (maybe.length >= 1) {
      if (maybe.length !== 1 && mustWarn) {
        (0, _util.warn)(`XFA - Too many choices to guess the correct font: ${fontName}`);
      }
      this.cache.set(fontName, maybe[0]);
      return maybe[0];
    }
    if (mustWarn && !this.warned.has(fontName)) {
      this.warned.add(fontName);
      (0, _util.warn)(`XFA - Cannot find the font: ${fontName}`);
    }
    return null;
  }
}
exports.FontFinder = FontFinder;
function selectFont(xfaFont, typeface) {
  if (xfaFont.posture === "italic") {
    if (xfaFont.weight === "bold") {
      return typeface.bolditalic;
    }
    return typeface.italic;
  } else if (xfaFont.weight === "bold") {
    return typeface.bold;
  }
  return typeface.regular;
}
function getMetrics(xfaFont, real = false) {
  let pdfFont = null;
  if (xfaFont) {
    const name = (0, _utils.stripQuotes)(xfaFont.typeface);
    const typeface = xfaFont[_xfa_object.$globalData].fontFinder.find(name);
    pdfFont = selectFont(xfaFont, typeface);
  }
  if (!pdfFont) {
    return {
      lineHeight: 12,
      lineGap: 2,
      lineNoGap: 10
    };
  }
  const size = xfaFont.size || 10;
  const lineHeight = pdfFont.lineHeight ? Math.max(real ? 0 : 1.2, pdfFont.lineHeight) : 1.2;
  const lineGap = pdfFont.lineGap === undefined ? 0.2 : pdfFont.lineGap;
  return {
    lineHeight: lineHeight * size,
    lineGap: lineGap * size,
    lineNoGap: Math.max(1, lineHeight - lineGap) * size
  };
}

/***/ }),
/* 84 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.TextMeasure = void 0;
var _fonts = __w_pdfjs_require__(83);
const WIDTH_FACTOR = 1.02;
class FontInfo {
  constructor(xfaFont, margin, lineHeight, fontFinder) {
    this.lineHeight = lineHeight;
    this.paraMargin = margin || {
      top: 0,
      bottom: 0,
      left: 0,
      right: 0
    };
    if (!xfaFont) {
      [this.pdfFont, this.xfaFont] = this.defaultFont(fontFinder);
      return;
    }
    this.xfaFont = {
      typeface: xfaFont.typeface,
      posture: xfaFont.posture,
      weight: xfaFont.weight,
      size: xfaFont.size,
      letterSpacing: xfaFont.letterSpacing
    };
    const typeface = fontFinder.find(xfaFont.typeface);
    if (!typeface) {
      [this.pdfFont, this.xfaFont] = this.defaultFont(fontFinder);
      return;
    }
    this.pdfFont = (0, _fonts.selectFont)(xfaFont, typeface);
    if (!this.pdfFont) {
      [this.pdfFont, this.xfaFont] = this.defaultFont(fontFinder);
    }
  }
  defaultFont(fontFinder) {
    const font = fontFinder.find("Helvetica", false) || fontFinder.find("Myriad Pro", false) || fontFinder.find("Arial", false) || fontFinder.getDefault();
    if (font && font.regular) {
      const pdfFont = font.regular;
      const info = pdfFont.cssFontInfo;
      const xfaFont = {
        typeface: info.fontFamily,
        posture: "normal",
        weight: "normal",
        size: 10,
        letterSpacing: 0
      };
      return [pdfFont, xfaFont];
    }
    const xfaFont = {
      typeface: "Courier",
      posture: "normal",
      weight: "normal",
      size: 10,
      letterSpacing: 0
    };
    return [null, xfaFont];
  }
}
class FontSelector {
  constructor(defaultXfaFont, defaultParaMargin, defaultLineHeight, fontFinder) {
    this.fontFinder = fontFinder;
    this.stack = [new FontInfo(defaultXfaFont, defaultParaMargin, defaultLineHeight, fontFinder)];
  }
  pushData(xfaFont, margin, lineHeight) {
    const lastFont = this.stack.at(-1);
    for (const name of ["typeface", "posture", "weight", "size", "letterSpacing"]) {
      if (!xfaFont[name]) {
        xfaFont[name] = lastFont.xfaFont[name];
      }
    }
    for (const name of ["top", "bottom", "left", "right"]) {
      if (isNaN(margin[name])) {
        margin[name] = lastFont.paraMargin[name];
      }
    }
    const fontInfo = new FontInfo(xfaFont, margin, lineHeight || lastFont.lineHeight, this.fontFinder);
    if (!fontInfo.pdfFont) {
      fontInfo.pdfFont = lastFont.pdfFont;
    }
    this.stack.push(fontInfo);
  }
  popFont() {
    this.stack.pop();
  }
  topFont() {
    return this.stack.at(-1);
  }
}
class TextMeasure {
  constructor(defaultXfaFont, defaultParaMargin, defaultLineHeight, fonts) {
    this.glyphs = [];
    this.fontSelector = new FontSelector(defaultXfaFont, defaultParaMargin, defaultLineHeight, fonts);
    this.extraHeight = 0;
  }
  pushData(xfaFont, margin, lineHeight) {
    this.fontSelector.pushData(xfaFont, margin, lineHeight);
  }
  popFont(xfaFont) {
    return this.fontSelector.popFont();
  }
  addPara() {
    const lastFont = this.fontSelector.topFont();
    this.extraHeight += lastFont.paraMargin.top + lastFont.paraMargin.bottom;
  }
  addString(str) {
    if (!str) {
      return;
    }
    const lastFont = this.fontSelector.topFont();
    const fontSize = lastFont.xfaFont.size;
    if (lastFont.pdfFont) {
      const letterSpacing = lastFont.xfaFont.letterSpacing;
      const pdfFont = lastFont.pdfFont;
      const fontLineHeight = pdfFont.lineHeight || 1.2;
      const lineHeight = lastFont.lineHeight || Math.max(1.2, fontLineHeight) * fontSize;
      const lineGap = pdfFont.lineGap === undefined ? 0.2 : pdfFont.lineGap;
      const noGap = fontLineHeight - lineGap;
      const firstLineHeight = Math.max(1, noGap) * fontSize;
      const scale = fontSize / 1000;
      const fallbackWidth = pdfFont.defaultWidth || pdfFont.charsToGlyphs(" ")[0].width;
      for (const line of str.split(/[\u2029\n]/)) {
        const encodedLine = pdfFont.encodeString(line).join("");
        const glyphs = pdfFont.charsToGlyphs(encodedLine);
        for (const glyph of glyphs) {
          const width = glyph.width || fallbackWidth;
          this.glyphs.push([width * scale + letterSpacing, lineHeight, firstLineHeight, glyph.unicode, false]);
        }
        this.glyphs.push([0, 0, 0, "\n", true]);
      }
      this.glyphs.pop();
      return;
    }
    for (const line of str.split(/[\u2029\n]/)) {
      for (const char of line.split("")) {
        this.glyphs.push([fontSize, 1.2 * fontSize, fontSize, char, false]);
      }
      this.glyphs.push([0, 0, 0, "\n", true]);
    }
    this.glyphs.pop();
  }
  compute(maxWidth) {
    let lastSpacePos = -1,
      lastSpaceWidth = 0,
      width = 0,
      height = 0,
      currentLineWidth = 0,
      currentLineHeight = 0;
    let isBroken = false;
    let isFirstLine = true;
    for (let i = 0, ii = this.glyphs.length; i < ii; i++) {
      const [glyphWidth, lineHeight, firstLineHeight, char, isEOL] = this.glyphs[i];
      const isSpace = char === " ";
      const glyphHeight = isFirstLine ? firstLineHeight : lineHeight;
      if (isEOL) {
        width = Math.max(width, currentLineWidth);
        currentLineWidth = 0;
        height += currentLineHeight;
        currentLineHeight = glyphHeight;
        lastSpacePos = -1;
        lastSpaceWidth = 0;
        isFirstLine = false;
        continue;
      }
      if (isSpace) {
        if (currentLineWidth + glyphWidth > maxWidth) {
          width = Math.max(width, currentLineWidth);
          currentLineWidth = 0;
          height += currentLineHeight;
          currentLineHeight = glyphHeight;
          lastSpacePos = -1;
          lastSpaceWidth = 0;
          isBroken = true;
          isFirstLine = false;
        } else {
          currentLineHeight = Math.max(glyphHeight, currentLineHeight);
          lastSpaceWidth = currentLineWidth;
          currentLineWidth += glyphWidth;
          lastSpacePos = i;
        }
        continue;
      }
      if (currentLineWidth + glyphWidth > maxWidth) {
        height += currentLineHeight;
        currentLineHeight = glyphHeight;
        if (lastSpacePos !== -1) {
          i = lastSpacePos;
          width = Math.max(width, lastSpaceWidth);
          currentLineWidth = 0;
          lastSpacePos = -1;
          lastSpaceWidth = 0;
        } else {
          width = Math.max(width, currentLineWidth);
          currentLineWidth = glyphWidth;
        }
        isBroken = true;
        isFirstLine = false;
        continue;
      }
      currentLineWidth += glyphWidth;
      currentLineHeight = Math.max(glyphHeight, currentLineHeight);
    }
    width = Math.max(width, currentLineWidth);
    height += currentLineHeight + this.extraHeight;
    return {
      width: WIDTH_FACTOR * width,
      height,
      isBroken
    };
  }
}
exports.TextMeasure = TextMeasure;

/***/ }),
/* 85 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.DataHandler = void 0;
var _xfa_object = __w_pdfjs_require__(75);
class DataHandler {
  constructor(root, data) {
    this.data = data;
    this.dataset = root.datasets || null;
  }
  serialize(storage) {
    const stack = [[-1, this.data[_xfa_object.$getChildren]()]];
    while (stack.length > 0) {
      const last = stack.at(-1);
      const [i, children] = last;
      if (i + 1 === children.length) {
        stack.pop();
        continue;
      }
      const child = children[++last[0]];
      const storageEntry = storage.get(child[_xfa_object.$uid]);
      if (storageEntry) {
        child[_xfa_object.$setValue](storageEntry);
      } else {
        const attributes = child[_xfa_object.$getAttributes]();
        for (const value of attributes.values()) {
          const entry = storage.get(value[_xfa_object.$uid]);
          if (entry) {
            value[_xfa_object.$setValue](entry);
            break;
          }
        }
      }
      const nodes = child[_xfa_object.$getChildren]();
      if (nodes.length > 0) {
        stack.push([-1, nodes]);
      }
    }
    const buf = [`<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">`];
    if (this.dataset) {
      for (const child of this.dataset[_xfa_object.$getChildren]()) {
        if (child[_xfa_object.$nodeName] !== "data") {
          child[_xfa_object.$toString](buf);
        }
      }
    }
    this.data[_xfa_object.$toString](buf);
    buf.push("</xfa:datasets>");
    return buf.join("");
  }
}
exports.DataHandler = DataHandler;

/***/ }),
/* 86 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XFAParser = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _xml_parser = __w_pdfjs_require__(64);
var _builder = __w_pdfjs_require__(87);
var _util = __w_pdfjs_require__(2);
class XFAParser extends _xml_parser.XMLParserBase {
  constructor(rootNameSpace = null, richText = false) {
    super();
    this._builder = new _builder.Builder(rootNameSpace);
    this._stack = [];
    this._globalData = {
      usedTypefaces: new Set()
    };
    this._ids = new Map();
    this._current = this._builder.buildRoot(this._ids);
    this._errorCode = _xml_parser.XMLParserErrorCode.NoError;
    this._whiteRegex = /^\s+$/;
    this._nbsps = /\xa0+/g;
    this._richText = richText;
  }
  parse(data) {
    this.parseXml(data);
    if (this._errorCode !== _xml_parser.XMLParserErrorCode.NoError) {
      return undefined;
    }
    this._current[_xfa_object.$finalize]();
    return this._current.element;
  }
  onText(text) {
    text = text.replace(this._nbsps, match => match.slice(1) + " ");
    if (this._richText || this._current[_xfa_object.$acceptWhitespace]()) {
      this._current[_xfa_object.$onText](text, this._richText);
      return;
    }
    if (this._whiteRegex.test(text)) {
      return;
    }
    this._current[_xfa_object.$onText](text.trim());
  }
  onCdata(text) {
    this._current[_xfa_object.$onText](text);
  }
  _mkAttributes(attributes, tagName) {
    let namespace = null;
    let prefixes = null;
    const attributeObj = Object.create({});
    for (const {
      name,
      value
    } of attributes) {
      if (name === "xmlns") {
        if (!namespace) {
          namespace = value;
        } else {
          (0, _util.warn)(`XFA - multiple namespace definition in <${tagName}>`);
        }
      } else if (name.startsWith("xmlns:")) {
        const prefix = name.substring("xmlns:".length);
        if (!prefixes) {
          prefixes = [];
        }
        prefixes.push({
          prefix,
          value
        });
      } else {
        const i = name.indexOf(":");
        if (i === -1) {
          attributeObj[name] = value;
        } else {
          let nsAttrs = attributeObj[_xfa_object.$nsAttributes];
          if (!nsAttrs) {
            nsAttrs = attributeObj[_xfa_object.$nsAttributes] = Object.create(null);
          }
          const [ns, attrName] = [name.slice(0, i), name.slice(i + 1)];
          let attrs = nsAttrs[ns];
          if (!attrs) {
            attrs = nsAttrs[ns] = Object.create(null);
          }
          attrs[attrName] = value;
        }
      }
    }
    return [namespace, prefixes, attributeObj];
  }
  _getNameAndPrefix(name, nsAgnostic) {
    const i = name.indexOf(":");
    if (i === -1) {
      return [name, null];
    }
    return [name.substring(i + 1), nsAgnostic ? "" : name.substring(0, i)];
  }
  onBeginElement(tagName, attributes, isEmpty) {
    const [namespace, prefixes, attributesObj] = this._mkAttributes(attributes, tagName);
    const [name, nsPrefix] = this._getNameAndPrefix(tagName, this._builder.isNsAgnostic());
    const node = this._builder.build({
      nsPrefix,
      name,
      attributes: attributesObj,
      namespace,
      prefixes
    });
    node[_xfa_object.$globalData] = this._globalData;
    if (isEmpty) {
      node[_xfa_object.$finalize]();
      if (this._current[_xfa_object.$onChild](node)) {
        node[_xfa_object.$setId](this._ids);
      }
      node[_xfa_object.$clean](this._builder);
      return;
    }
    this._stack.push(this._current);
    this._current = node;
  }
  onEndElement(name) {
    const node = this._current;
    if (node[_xfa_object.$isCDATAXml]() && typeof node[_xfa_object.$content] === "string") {
      const parser = new XFAParser();
      parser._globalData = this._globalData;
      const root = parser.parse(node[_xfa_object.$content]);
      node[_xfa_object.$content] = null;
      node[_xfa_object.$onChild](root);
    }
    node[_xfa_object.$finalize]();
    this._current = this._stack.pop();
    if (this._current[_xfa_object.$onChild](node)) {
      node[_xfa_object.$setId](this._ids);
    }
    node[_xfa_object.$clean](this._builder);
  }
  onError(code) {
    this._errorCode = code;
  }
}
exports.XFAParser = XFAParser;

/***/ }),
/* 87 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.Builder = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
var _setup = __w_pdfjs_require__(88);
var _template = __w_pdfjs_require__(80);
var _unknown = __w_pdfjs_require__(97);
var _util = __w_pdfjs_require__(2);
class Root extends _xfa_object.XFAObject {
  constructor(ids) {
    super(-1, "root", Object.create(null));
    this.element = null;
    this[_xfa_object.$ids] = ids;
  }
  [_xfa_object.$onChild](child) {
    this.element = child;
    return true;
  }
  [_xfa_object.$finalize]() {
    super[_xfa_object.$finalize]();
    if (this.element.template instanceof _template.Template) {
      this[_xfa_object.$ids].set(_xfa_object.$root, this.element);
      this.element.template[_xfa_object.$resolvePrototypes](this[_xfa_object.$ids]);
      this.element.template[_xfa_object.$ids] = this[_xfa_object.$ids];
    }
  }
}
class Empty extends _xfa_object.XFAObject {
  constructor() {
    super(-1, "", Object.create(null));
  }
  [_xfa_object.$onChild](_) {
    return false;
  }
}
class Builder {
  constructor(rootNameSpace = null) {
    this._namespaceStack = [];
    this._nsAgnosticLevel = 0;
    this._namespacePrefixes = new Map();
    this._namespaces = new Map();
    this._nextNsId = Math.max(...Object.values(_namespaces.NamespaceIds).map(({
      id
    }) => id));
    this._currentNamespace = rootNameSpace || new _unknown.UnknownNamespace(++this._nextNsId);
  }
  buildRoot(ids) {
    return new Root(ids);
  }
  build({
    nsPrefix,
    name,
    attributes,
    namespace,
    prefixes
  }) {
    const hasNamespaceDef = namespace !== null;
    if (hasNamespaceDef) {
      this._namespaceStack.push(this._currentNamespace);
      this._currentNamespace = this._searchNamespace(namespace);
    }
    if (prefixes) {
      this._addNamespacePrefix(prefixes);
    }
    if (attributes.hasOwnProperty(_xfa_object.$nsAttributes)) {
      const dataTemplate = _setup.NamespaceSetUp.datasets;
      const nsAttrs = attributes[_xfa_object.$nsAttributes];
      let xfaAttrs = null;
      for (const [ns, attrs] of Object.entries(nsAttrs)) {
        const nsToUse = this._getNamespaceToUse(ns);
        if (nsToUse === dataTemplate) {
          xfaAttrs = {
            xfa: attrs
          };
          break;
        }
      }
      if (xfaAttrs) {
        attributes[_xfa_object.$nsAttributes] = xfaAttrs;
      } else {
        delete attributes[_xfa_object.$nsAttributes];
      }
    }
    const namespaceToUse = this._getNamespaceToUse(nsPrefix);
    const node = namespaceToUse && namespaceToUse[_namespaces.$buildXFAObject](name, attributes) || new Empty();
    if (node[_xfa_object.$isNsAgnostic]()) {
      this._nsAgnosticLevel++;
    }
    if (hasNamespaceDef || prefixes || node[_xfa_object.$isNsAgnostic]()) {
      node[_xfa_object.$cleanup] = {
        hasNamespace: hasNamespaceDef,
        prefixes,
        nsAgnostic: node[_xfa_object.$isNsAgnostic]()
      };
    }
    return node;
  }
  isNsAgnostic() {
    return this._nsAgnosticLevel > 0;
  }
  _searchNamespace(nsName) {
    let ns = this._namespaces.get(nsName);
    if (ns) {
      return ns;
    }
    for (const [name, {
      check
    }] of Object.entries(_namespaces.NamespaceIds)) {
      if (check(nsName)) {
        ns = _setup.NamespaceSetUp[name];
        if (ns) {
          this._namespaces.set(nsName, ns);
          return ns;
        }
        break;
      }
    }
    ns = new _unknown.UnknownNamespace(++this._nextNsId);
    this._namespaces.set(nsName, ns);
    return ns;
  }
  _addNamespacePrefix(prefixes) {
    for (const {
      prefix,
      value
    } of prefixes) {
      const namespace = this._searchNamespace(value);
      let prefixStack = this._namespacePrefixes.get(prefix);
      if (!prefixStack) {
        prefixStack = [];
        this._namespacePrefixes.set(prefix, prefixStack);
      }
      prefixStack.push(namespace);
    }
  }
  _getNamespaceToUse(prefix) {
    if (!prefix) {
      return this._currentNamespace;
    }
    const prefixStack = this._namespacePrefixes.get(prefix);
    if (prefixStack && prefixStack.length > 0) {
      return prefixStack.at(-1);
    }
    (0, _util.warn)(`Unknown namespace prefix: ${prefix}.`);
    return null;
  }
  clean(data) {
    const {
      hasNamespace,
      prefixes,
      nsAgnostic
    } = data;
    if (hasNamespace) {
      this._currentNamespace = this._namespaceStack.pop();
    }
    if (prefixes) {
      prefixes.forEach(({
        prefix
      }) => {
        this._namespacePrefixes.get(prefix).pop();
      });
    }
    if (nsAgnostic) {
      this._nsAgnosticLevel--;
    }
  }
}
exports.Builder = Builder;

/***/ }),
/* 88 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.NamespaceSetUp = void 0;
var _config = __w_pdfjs_require__(89);
var _connection_set = __w_pdfjs_require__(90);
var _datasets = __w_pdfjs_require__(91);
var _locale_set = __w_pdfjs_require__(92);
var _signature = __w_pdfjs_require__(93);
var _stylesheet = __w_pdfjs_require__(94);
var _template = __w_pdfjs_require__(80);
var _xdp = __w_pdfjs_require__(95);
var _xhtml = __w_pdfjs_require__(96);
const NamespaceSetUp = {
  config: _config.ConfigNamespace,
  connection: _connection_set.ConnectionSetNamespace,
  datasets: _datasets.DatasetsNamespace,
  localeSet: _locale_set.LocaleSetNamespace,
  signature: _signature.SignatureNamespace,
  stylesheet: _stylesheet.StylesheetNamespace,
  template: _template.TemplateNamespace,
  xdp: _xdp.XdpNamespace,
  xhtml: _xhtml.XhtmlNamespace
};
exports.NamespaceSetUp = NamespaceSetUp;

/***/ }),
/* 89 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ConfigNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
var _utils = __w_pdfjs_require__(76);
var _util = __w_pdfjs_require__(2);
const CONFIG_NS_ID = _namespaces.NamespaceIds.config.id;
class Acrobat extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "acrobat", true);
    this.acrobat7 = null;
    this.autoSave = null;
    this.common = null;
    this.validate = null;
    this.validateApprovalSignatures = null;
    this.submitUrl = new _xfa_object.XFAObjectArray();
  }
}
class Acrobat7 extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "acrobat7", true);
    this.dynamicRender = null;
  }
}
class ADBE_JSConsole extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "ADBE_JSConsole", ["delegate", "Enable", "Disable"]);
  }
}
class ADBE_JSDebugger extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "ADBE_JSDebugger", ["delegate", "Enable", "Disable"]);
  }
}
class AddSilentPrint extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "addSilentPrint");
  }
}
class AddViewerPreferences extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "addViewerPreferences");
  }
}
class AdjustData extends _xfa_object.Option10 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "adjustData");
  }
}
class AdobeExtensionLevel extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "adobeExtensionLevel", 0, n => n >= 1 && n <= 8);
  }
}
class Agent extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "agent", true);
    this.name = attributes.name ? attributes.name.trim() : "";
    this.common = new _xfa_object.XFAObjectArray();
  }
}
class AlwaysEmbed extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "alwaysEmbed");
  }
}
class Amd extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "amd");
  }
}
class Area extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "area");
    this.level = (0, _utils.getInteger)({
      data: attributes.level,
      defaultValue: 0,
      validate: n => n >= 1 && n <= 3
    });
    this.name = (0, _utils.getStringOption)(attributes.name, ["", "barcode", "coreinit", "deviceDriver", "font", "general", "layout", "merge", "script", "signature", "sourceSet", "templateCache"]);
  }
}
class Attributes extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "attributes", ["preserve", "delegate", "ignore"]);
  }
}
class AutoSave extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "autoSave", ["disabled", "enabled"]);
  }
}
class Base extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "base");
  }
}
class BatchOutput extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "batchOutput");
    this.format = (0, _utils.getStringOption)(attributes.format, ["none", "concat", "zip", "zipCompress"]);
  }
}
class BehaviorOverride extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "behaviorOverride");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = new Map(this[_xfa_object.$content].trim().split(/\s+/).filter(x => x.includes(":")).map(x => x.split(":", 2)));
  }
}
class Cache extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "cache", true);
    this.templateCache = null;
  }
}
class Change extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "change");
  }
}
class Common extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "common", true);
    this.data = null;
    this.locale = null;
    this.localeSet = null;
    this.messaging = null;
    this.suppressBanner = null;
    this.template = null;
    this.validationMessaging = null;
    this.versionControl = null;
    this.log = new _xfa_object.XFAObjectArray();
  }
}
class Compress extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "compress");
    this.scope = (0, _utils.getStringOption)(attributes.scope, ["imageOnly", "document"]);
  }
}
class CompressLogicalStructure extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "compressLogicalStructure");
  }
}
class CompressObjectStream extends _xfa_object.Option10 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "compressObjectStream");
  }
}
class Compression extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "compression", true);
    this.compressLogicalStructure = null;
    this.compressObjectStream = null;
    this.level = null;
    this.type = null;
  }
}
class Config extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "config", true);
    this.acrobat = null;
    this.present = null;
    this.trace = null;
    this.agent = new _xfa_object.XFAObjectArray();
  }
}
class Conformance extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "conformance", ["A", "B"]);
  }
}
class ContentCopy extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "contentCopy");
  }
}
class Copies extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "copies", 1, n => n >= 1);
  }
}
class Creator extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "creator");
  }
}
class CurrentPage extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "currentPage", 0, n => n >= 0);
  }
}
class Data extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "data", true);
    this.adjustData = null;
    this.attributes = null;
    this.incrementalLoad = null;
    this.outputXSL = null;
    this.range = null;
    this.record = null;
    this.startNode = null;
    this.uri = null;
    this.window = null;
    this.xsl = null;
    this.excludeNS = new _xfa_object.XFAObjectArray();
    this.transform = new _xfa_object.XFAObjectArray();
  }
}
class Debug extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "debug", true);
    this.uri = null;
  }
}
class DefaultTypeface extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "defaultTypeface");
    this.writingScript = (0, _utils.getStringOption)(attributes.writingScript, ["*", "Arabic", "Cyrillic", "EastEuropeanRoman", "Greek", "Hebrew", "Japanese", "Korean", "Roman", "SimplifiedChinese", "Thai", "TraditionalChinese", "Vietnamese"]);
  }
}
class Destination extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "destination", ["pdf", "pcl", "ps", "webClient", "zpl"]);
  }
}
class DocumentAssembly extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "documentAssembly");
  }
}
class Driver extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "driver", true);
    this.name = attributes.name ? attributes.name.trim() : "";
    this.fontInfo = null;
    this.xdc = null;
  }
}
class DuplexOption extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "duplexOption", ["simplex", "duplexFlipLongEdge", "duplexFlipShortEdge"]);
  }
}
class DynamicRender extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "dynamicRender", ["forbidden", "required"]);
  }
}
class Embed extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "embed");
  }
}
class Encrypt extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "encrypt");
  }
}
class Encryption extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "encryption", true);
    this.encrypt = null;
    this.encryptionLevel = null;
    this.permissions = null;
  }
}
class EncryptionLevel extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "encryptionLevel", ["40bit", "128bit"]);
  }
}
class Enforce extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "enforce");
  }
}
class Equate extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "equate");
    this.force = (0, _utils.getInteger)({
      data: attributes.force,
      defaultValue: 1,
      validate: n => n === 0
    });
    this.from = attributes.from || "";
    this.to = attributes.to || "";
  }
}
class EquateRange extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "equateRange");
    this.from = attributes.from || "";
    this.to = attributes.to || "";
    this._unicodeRange = attributes.unicodeRange || "";
  }
  get unicodeRange() {
    const ranges = [];
    const unicodeRegex = /U\+([0-9a-fA-F]+)/;
    const unicodeRange = this._unicodeRange;
    for (let range of unicodeRange.split(",").map(x => x.trim()).filter(x => !!x)) {
      range = range.split("-", 2).map(x => {
        const found = x.match(unicodeRegex);
        if (!found) {
          return 0;
        }
        return parseInt(found[1], 16);
      });
      if (range.length === 1) {
        range.push(range[0]);
      }
      ranges.push(range);
    }
    return (0, _util.shadow)(this, "unicodeRange", ranges);
  }
}
class Exclude extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "exclude");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim().split(/\s+/).filter(x => x && ["calculate", "close", "enter", "exit", "initialize", "ready", "validate"].includes(x));
  }
}
class ExcludeNS extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "excludeNS");
  }
}
class FlipLabel extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "flipLabel", ["usePrinterSetting", "on", "off"]);
  }
}
class FontInfo extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "fontInfo", true);
    this.embed = null;
    this.map = null;
    this.subsetBelow = null;
    this.alwaysEmbed = new _xfa_object.XFAObjectArray();
    this.defaultTypeface = new _xfa_object.XFAObjectArray();
    this.neverEmbed = new _xfa_object.XFAObjectArray();
  }
}
class FormFieldFilling extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "formFieldFilling");
  }
}
class GroupParent extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "groupParent");
  }
}
class IfEmpty extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "ifEmpty", ["dataValue", "dataGroup", "ignore", "remove"]);
  }
}
class IncludeXDPContent extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "includeXDPContent");
  }
}
class IncrementalLoad extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "incrementalLoad", ["none", "forwardOnly"]);
  }
}
class IncrementalMerge extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "incrementalMerge");
  }
}
class Interactive extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "interactive");
  }
}
class Jog extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "jog", ["usePrinterSetting", "none", "pageSet"]);
  }
}
class LabelPrinter extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "labelPrinter", true);
    this.name = (0, _utils.getStringOption)(attributes.name, ["zpl", "dpl", "ipl", "tcpl"]);
    this.batchOutput = null;
    this.flipLabel = null;
    this.fontInfo = null;
    this.xdc = null;
  }
}
class Layout extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "layout", ["paginate", "panel"]);
  }
}
class Level extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "level", 0, n => n > 0);
  }
}
class Linearized extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "linearized");
  }
}
class Locale extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "locale");
  }
}
class LocaleSet extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "localeSet");
  }
}
class Log extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "log", true);
    this.mode = null;
    this.threshold = null;
    this.to = null;
    this.uri = null;
  }
}
class MapElement extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "map", true);
    this.equate = new _xfa_object.XFAObjectArray();
    this.equateRange = new _xfa_object.XFAObjectArray();
  }
}
class MediumInfo extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "mediumInfo", true);
    this.map = null;
  }
}
class Message extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "message", true);
    this.msgId = null;
    this.severity = null;
  }
}
class Messaging extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "messaging", true);
    this.message = new _xfa_object.XFAObjectArray();
  }
}
class Mode extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "mode", ["append", "overwrite"]);
  }
}
class ModifyAnnots extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "modifyAnnots");
  }
}
class MsgId extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "msgId", 1, n => n >= 1);
  }
}
class NameAttr extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "nameAttr");
  }
}
class NeverEmbed extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "neverEmbed");
  }
}
class NumberOfCopies extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "numberOfCopies", null, n => n >= 2 && n <= 5);
  }
}
class OpenAction extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "openAction", true);
    this.destination = null;
  }
}
class Output extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "output", true);
    this.to = null;
    this.type = null;
    this.uri = null;
  }
}
class OutputBin extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "outputBin");
  }
}
class OutputXSL extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "outputXSL", true);
    this.uri = null;
  }
}
class Overprint extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "overprint", ["none", "both", "draw", "field"]);
  }
}
class Packets extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "packets");
  }
  [_xfa_object.$finalize]() {
    if (this[_xfa_object.$content] === "*") {
      return;
    }
    this[_xfa_object.$content] = this[_xfa_object.$content].trim().split(/\s+/).filter(x => ["config", "datasets", "template", "xfdf", "xslt"].includes(x));
  }
}
class PageOffset extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pageOffset");
    this.x = (0, _utils.getInteger)({
      data: attributes.x,
      defaultValue: "useXDCSetting",
      validate: n => true
    });
    this.y = (0, _utils.getInteger)({
      data: attributes.y,
      defaultValue: "useXDCSetting",
      validate: n => true
    });
  }
}
class PageRange extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pageRange");
  }
  [_xfa_object.$finalize]() {
    const numbers = this[_xfa_object.$content].trim().split(/\s+/).map(x => parseInt(x, 10));
    const ranges = [];
    for (let i = 0, ii = numbers.length; i < ii; i += 2) {
      ranges.push(numbers.slice(i, i + 2));
    }
    this[_xfa_object.$content] = ranges;
  }
}
class Pagination extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pagination", ["simplex", "duplexShortEdge", "duplexLongEdge"]);
  }
}
class PaginationOverride extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "paginationOverride", ["none", "forceDuplex", "forceDuplexLongEdge", "forceDuplexShortEdge", "forceSimplex"]);
  }
}
class Part extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "part", 1, n => false);
  }
}
class Pcl extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pcl", true);
    this.name = attributes.name || "";
    this.batchOutput = null;
    this.fontInfo = null;
    this.jog = null;
    this.mediumInfo = null;
    this.outputBin = null;
    this.pageOffset = null;
    this.staple = null;
    this.xdc = null;
  }
}
class Pdf extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pdf", true);
    this.name = attributes.name || "";
    this.adobeExtensionLevel = null;
    this.batchOutput = null;
    this.compression = null;
    this.creator = null;
    this.encryption = null;
    this.fontInfo = null;
    this.interactive = null;
    this.linearized = null;
    this.openAction = null;
    this.pdfa = null;
    this.producer = null;
    this.renderPolicy = null;
    this.scriptModel = null;
    this.silentPrint = null;
    this.submitFormat = null;
    this.tagged = null;
    this.version = null;
    this.viewerPreferences = null;
    this.xdc = null;
  }
}
class Pdfa extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pdfa", true);
    this.amd = null;
    this.conformance = null;
    this.includeXDPContent = null;
    this.part = null;
  }
}
class Permissions extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "permissions", true);
    this.accessibleContent = null;
    this.change = null;
    this.contentCopy = null;
    this.documentAssembly = null;
    this.formFieldFilling = null;
    this.modifyAnnots = null;
    this.plaintextMetadata = null;
    this.print = null;
    this.printHighQuality = null;
  }
}
class PickTrayByPDFSize extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "pickTrayByPDFSize");
  }
}
class Picture extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "picture");
  }
}
class PlaintextMetadata extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "plaintextMetadata");
  }
}
class Presence extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "presence", ["preserve", "dissolve", "dissolveStructure", "ignore", "remove"]);
  }
}
class Present extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "present", true);
    this.behaviorOverride = null;
    this.cache = null;
    this.common = null;
    this.copies = null;
    this.destination = null;
    this.incrementalMerge = null;
    this.layout = null;
    this.output = null;
    this.overprint = null;
    this.pagination = null;
    this.paginationOverride = null;
    this.script = null;
    this.validate = null;
    this.xdp = null;
    this.driver = new _xfa_object.XFAObjectArray();
    this.labelPrinter = new _xfa_object.XFAObjectArray();
    this.pcl = new _xfa_object.XFAObjectArray();
    this.pdf = new _xfa_object.XFAObjectArray();
    this.ps = new _xfa_object.XFAObjectArray();
    this.submitUrl = new _xfa_object.XFAObjectArray();
    this.webClient = new _xfa_object.XFAObjectArray();
    this.zpl = new _xfa_object.XFAObjectArray();
  }
}
class Print extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "print");
  }
}
class PrintHighQuality extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "printHighQuality");
  }
}
class PrintScaling extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "printScaling", ["appdefault", "noScaling"]);
  }
}
class PrinterName extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "printerName");
  }
}
class Producer extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "producer");
  }
}
class Ps extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "ps", true);
    this.name = attributes.name || "";
    this.batchOutput = null;
    this.fontInfo = null;
    this.jog = null;
    this.mediumInfo = null;
    this.outputBin = null;
    this.staple = null;
    this.xdc = null;
  }
}
class Range extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "range");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim().split(/\s*,\s*/, 2).map(range => range.split("-").map(x => parseInt(x.trim(), 10))).filter(range => range.every(x => !isNaN(x))).map(range => {
      if (range.length === 1) {
        range.push(range[0]);
      }
      return range;
    });
  }
}
class Record extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "record");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim();
    const n = parseInt(this[_xfa_object.$content], 10);
    if (!isNaN(n) && n >= 0) {
      this[_xfa_object.$content] = n;
    }
  }
}
class Relevant extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "relevant");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim().split(/\s+/);
  }
}
class Rename extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "rename");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim();
    if (this[_xfa_object.$content].toLowerCase().startsWith("xml") || new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*", "u").test(this[_xfa_object.$content])) {
      (0, _util.warn)("XFA - Rename: invalid XFA name");
    }
  }
}
class RenderPolicy extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "renderPolicy", ["server", "client"]);
  }
}
class RunScripts extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "runScripts", ["both", "client", "none", "server"]);
  }
}
class Script extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "script", true);
    this.currentPage = null;
    this.exclude = null;
    this.runScripts = null;
  }
}
class ScriptModel extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "scriptModel", ["XFA", "none"]);
  }
}
class Severity extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "severity", ["ignore", "error", "information", "trace", "warning"]);
  }
}
class SilentPrint extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "silentPrint", true);
    this.addSilentPrint = null;
    this.printerName = null;
  }
}
class Staple extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "staple");
    this.mode = (0, _utils.getStringOption)(attributes.mode, ["usePrinterSetting", "on", "off"]);
  }
}
class StartNode extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "startNode");
  }
}
class StartPage extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "startPage", 0, n => true);
  }
}
class SubmitFormat extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "submitFormat", ["html", "delegate", "fdf", "xml", "pdf"]);
  }
}
class SubmitUrl extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "submitUrl");
  }
}
class SubsetBelow extends _xfa_object.IntegerObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "subsetBelow", 100, n => n >= 0 && n <= 100);
  }
}
class SuppressBanner extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "suppressBanner");
  }
}
class Tagged extends _xfa_object.Option01 {
  constructor(attributes) {
    super(CONFIG_NS_ID, "tagged");
  }
}
class Template extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "template", true);
    this.base = null;
    this.relevant = null;
    this.startPage = null;
    this.uri = null;
    this.xsl = null;
  }
}
class Threshold extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "threshold", ["trace", "error", "information", "warning"]);
  }
}
class To extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "to", ["null", "memory", "stderr", "stdout", "system", "uri"]);
  }
}
class TemplateCache extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "templateCache");
    this.maxEntries = (0, _utils.getInteger)({
      data: attributes.maxEntries,
      defaultValue: 5,
      validate: n => n >= 0
    });
  }
}
class Trace extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "trace", true);
    this.area = new _xfa_object.XFAObjectArray();
  }
}
class Transform extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "transform", true);
    this.groupParent = null;
    this.ifEmpty = null;
    this.nameAttr = null;
    this.picture = null;
    this.presence = null;
    this.rename = null;
    this.whitespace = null;
  }
}
class Type extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "type", ["none", "ascii85", "asciiHex", "ccittfax", "flate", "lzw", "runLength", "native", "xdp", "mergedXDP"]);
  }
}
class Uri extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "uri");
  }
}
class Validate extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "validate", ["preSubmit", "prePrint", "preExecute", "preSave"]);
  }
}
class ValidateApprovalSignatures extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "validateApprovalSignatures");
  }
  [_xfa_object.$finalize]() {
    this[_xfa_object.$content] = this[_xfa_object.$content].trim().split(/\s+/).filter(x => ["docReady", "postSign"].includes(x));
  }
}
class ValidationMessaging extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "validationMessaging", ["allMessagesIndividually", "allMessagesTogether", "firstMessageOnly", "noMessages"]);
  }
}
class Version extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "version", ["1.7", "1.6", "1.5", "1.4", "1.3", "1.2"]);
  }
}
class VersionControl extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "VersionControl");
    this.outputBelow = (0, _utils.getStringOption)(attributes.outputBelow, ["warn", "error", "update"]);
    this.sourceAbove = (0, _utils.getStringOption)(attributes.sourceAbove, ["warn", "error"]);
    this.sourceBelow = (0, _utils.getStringOption)(attributes.sourceBelow, ["update", "maintain"]);
  }
}
class ViewerPreferences extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "viewerPreferences", true);
    this.ADBE_JSConsole = null;
    this.ADBE_JSDebugger = null;
    this.addViewerPreferences = null;
    this.duplexOption = null;
    this.enforce = null;
    this.numberOfCopies = null;
    this.pageRange = null;
    this.pickTrayByPDFSize = null;
    this.printScaling = null;
  }
}
class WebClient extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "webClient", true);
    this.name = attributes.name ? attributes.name.trim() : "";
    this.fontInfo = null;
    this.xdc = null;
  }
}
class Whitespace extends _xfa_object.OptionObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "whitespace", ["preserve", "ltrim", "normalize", "rtrim", "trim"]);
  }
}
class Window extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "window");
  }
  [_xfa_object.$finalize]() {
    const pair = this[_xfa_object.$content].trim().split(/\s*,\s*/, 2).map(x => parseInt(x, 10));
    if (pair.some(x => isNaN(x))) {
      this[_xfa_object.$content] = [0, 0];
      return;
    }
    if (pair.length === 1) {
      pair.push(pair[0]);
    }
    this[_xfa_object.$content] = pair;
  }
}
class Xdc extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "xdc", true);
    this.uri = new _xfa_object.XFAObjectArray();
    this.xsl = new _xfa_object.XFAObjectArray();
  }
}
class Xdp extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "xdp", true);
    this.packets = null;
  }
}
class Xsl extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "xsl", true);
    this.debug = null;
    this.uri = null;
  }
}
class Zpl extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONFIG_NS_ID, "zpl", true);
    this.name = attributes.name ? attributes.name.trim() : "";
    this.batchOutput = null;
    this.flipLabel = null;
    this.fontInfo = null;
    this.xdc = null;
  }
}
class ConfigNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (ConfigNamespace.hasOwnProperty(name)) {
      return ConfigNamespace[name](attributes);
    }
    return undefined;
  }
  static acrobat(attrs) {
    return new Acrobat(attrs);
  }
  static acrobat7(attrs) {
    return new Acrobat7(attrs);
  }
  static ADBE_JSConsole(attrs) {
    return new ADBE_JSConsole(attrs);
  }
  static ADBE_JSDebugger(attrs) {
    return new ADBE_JSDebugger(attrs);
  }
  static addSilentPrint(attrs) {
    return new AddSilentPrint(attrs);
  }
  static addViewerPreferences(attrs) {
    return new AddViewerPreferences(attrs);
  }
  static adjustData(attrs) {
    return new AdjustData(attrs);
  }
  static adobeExtensionLevel(attrs) {
    return new AdobeExtensionLevel(attrs);
  }
  static agent(attrs) {
    return new Agent(attrs);
  }
  static alwaysEmbed(attrs) {
    return new AlwaysEmbed(attrs);
  }
  static amd(attrs) {
    return new Amd(attrs);
  }
  static area(attrs) {
    return new Area(attrs);
  }
  static attributes(attrs) {
    return new Attributes(attrs);
  }
  static autoSave(attrs) {
    return new AutoSave(attrs);
  }
  static base(attrs) {
    return new Base(attrs);
  }
  static batchOutput(attrs) {
    return new BatchOutput(attrs);
  }
  static behaviorOverride(attrs) {
    return new BehaviorOverride(attrs);
  }
  static cache(attrs) {
    return new Cache(attrs);
  }
  static change(attrs) {
    return new Change(attrs);
  }
  static common(attrs) {
    return new Common(attrs);
  }
  static compress(attrs) {
    return new Compress(attrs);
  }
  static compressLogicalStructure(attrs) {
    return new CompressLogicalStructure(attrs);
  }
  static compressObjectStream(attrs) {
    return new CompressObjectStream(attrs);
  }
  static compression(attrs) {
    return new Compression(attrs);
  }
  static config(attrs) {
    return new Config(attrs);
  }
  static conformance(attrs) {
    return new Conformance(attrs);
  }
  static contentCopy(attrs) {
    return new ContentCopy(attrs);
  }
  static copies(attrs) {
    return new Copies(attrs);
  }
  static creator(attrs) {
    return new Creator(attrs);
  }
  static currentPage(attrs) {
    return new CurrentPage(attrs);
  }
  static data(attrs) {
    return new Data(attrs);
  }
  static debug(attrs) {
    return new Debug(attrs);
  }
  static defaultTypeface(attrs) {
    return new DefaultTypeface(attrs);
  }
  static destination(attrs) {
    return new Destination(attrs);
  }
  static documentAssembly(attrs) {
    return new DocumentAssembly(attrs);
  }
  static driver(attrs) {
    return new Driver(attrs);
  }
  static duplexOption(attrs) {
    return new DuplexOption(attrs);
  }
  static dynamicRender(attrs) {
    return new DynamicRender(attrs);
  }
  static embed(attrs) {
    return new Embed(attrs);
  }
  static encrypt(attrs) {
    return new Encrypt(attrs);
  }
  static encryption(attrs) {
    return new Encryption(attrs);
  }
  static encryptionLevel(attrs) {
    return new EncryptionLevel(attrs);
  }
  static enforce(attrs) {
    return new Enforce(attrs);
  }
  static equate(attrs) {
    return new Equate(attrs);
  }
  static equateRange(attrs) {
    return new EquateRange(attrs);
  }
  static exclude(attrs) {
    return new Exclude(attrs);
  }
  static excludeNS(attrs) {
    return new ExcludeNS(attrs);
  }
  static flipLabel(attrs) {
    return new FlipLabel(attrs);
  }
  static fontInfo(attrs) {
    return new FontInfo(attrs);
  }
  static formFieldFilling(attrs) {
    return new FormFieldFilling(attrs);
  }
  static groupParent(attrs) {
    return new GroupParent(attrs);
  }
  static ifEmpty(attrs) {
    return new IfEmpty(attrs);
  }
  static includeXDPContent(attrs) {
    return new IncludeXDPContent(attrs);
  }
  static incrementalLoad(attrs) {
    return new IncrementalLoad(attrs);
  }
  static incrementalMerge(attrs) {
    return new IncrementalMerge(attrs);
  }
  static interactive(attrs) {
    return new Interactive(attrs);
  }
  static jog(attrs) {
    return new Jog(attrs);
  }
  static labelPrinter(attrs) {
    return new LabelPrinter(attrs);
  }
  static layout(attrs) {
    return new Layout(attrs);
  }
  static level(attrs) {
    return new Level(attrs);
  }
  static linearized(attrs) {
    return new Linearized(attrs);
  }
  static locale(attrs) {
    return new Locale(attrs);
  }
  static localeSet(attrs) {
    return new LocaleSet(attrs);
  }
  static log(attrs) {
    return new Log(attrs);
  }
  static map(attrs) {
    return new MapElement(attrs);
  }
  static mediumInfo(attrs) {
    return new MediumInfo(attrs);
  }
  static message(attrs) {
    return new Message(attrs);
  }
  static messaging(attrs) {
    return new Messaging(attrs);
  }
  static mode(attrs) {
    return new Mode(attrs);
  }
  static modifyAnnots(attrs) {
    return new ModifyAnnots(attrs);
  }
  static msgId(attrs) {
    return new MsgId(attrs);
  }
  static nameAttr(attrs) {
    return new NameAttr(attrs);
  }
  static neverEmbed(attrs) {
    return new NeverEmbed(attrs);
  }
  static numberOfCopies(attrs) {
    return new NumberOfCopies(attrs);
  }
  static openAction(attrs) {
    return new OpenAction(attrs);
  }
  static output(attrs) {
    return new Output(attrs);
  }
  static outputBin(attrs) {
    return new OutputBin(attrs);
  }
  static outputXSL(attrs) {
    return new OutputXSL(attrs);
  }
  static overprint(attrs) {
    return new Overprint(attrs);
  }
  static packets(attrs) {
    return new Packets(attrs);
  }
  static pageOffset(attrs) {
    return new PageOffset(attrs);
  }
  static pageRange(attrs) {
    return new PageRange(attrs);
  }
  static pagination(attrs) {
    return new Pagination(attrs);
  }
  static paginationOverride(attrs) {
    return new PaginationOverride(attrs);
  }
  static part(attrs) {
    return new Part(attrs);
  }
  static pcl(attrs) {
    return new Pcl(attrs);
  }
  static pdf(attrs) {
    return new Pdf(attrs);
  }
  static pdfa(attrs) {
    return new Pdfa(attrs);
  }
  static permissions(attrs) {
    return new Permissions(attrs);
  }
  static pickTrayByPDFSize(attrs) {
    return new PickTrayByPDFSize(attrs);
  }
  static picture(attrs) {
    return new Picture(attrs);
  }
  static plaintextMetadata(attrs) {
    return new PlaintextMetadata(attrs);
  }
  static presence(attrs) {
    return new Presence(attrs);
  }
  static present(attrs) {
    return new Present(attrs);
  }
  static print(attrs) {
    return new Print(attrs);
  }
  static printHighQuality(attrs) {
    return new PrintHighQuality(attrs);
  }
  static printScaling(attrs) {
    return new PrintScaling(attrs);
  }
  static printerName(attrs) {
    return new PrinterName(attrs);
  }
  static producer(attrs) {
    return new Producer(attrs);
  }
  static ps(attrs) {
    return new Ps(attrs);
  }
  static range(attrs) {
    return new Range(attrs);
  }
  static record(attrs) {
    return new Record(attrs);
  }
  static relevant(attrs) {
    return new Relevant(attrs);
  }
  static rename(attrs) {
    return new Rename(attrs);
  }
  static renderPolicy(attrs) {
    return new RenderPolicy(attrs);
  }
  static runScripts(attrs) {
    return new RunScripts(attrs);
  }
  static script(attrs) {
    return new Script(attrs);
  }
  static scriptModel(attrs) {
    return new ScriptModel(attrs);
  }
  static severity(attrs) {
    return new Severity(attrs);
  }
  static silentPrint(attrs) {
    return new SilentPrint(attrs);
  }
  static staple(attrs) {
    return new Staple(attrs);
  }
  static startNode(attrs) {
    return new StartNode(attrs);
  }
  static startPage(attrs) {
    return new StartPage(attrs);
  }
  static submitFormat(attrs) {
    return new SubmitFormat(attrs);
  }
  static submitUrl(attrs) {
    return new SubmitUrl(attrs);
  }
  static subsetBelow(attrs) {
    return new SubsetBelow(attrs);
  }
  static suppressBanner(attrs) {
    return new SuppressBanner(attrs);
  }
  static tagged(attrs) {
    return new Tagged(attrs);
  }
  static template(attrs) {
    return new Template(attrs);
  }
  static templateCache(attrs) {
    return new TemplateCache(attrs);
  }
  static threshold(attrs) {
    return new Threshold(attrs);
  }
  static to(attrs) {
    return new To(attrs);
  }
  static trace(attrs) {
    return new Trace(attrs);
  }
  static transform(attrs) {
    return new Transform(attrs);
  }
  static type(attrs) {
    return new Type(attrs);
  }
  static uri(attrs) {
    return new Uri(attrs);
  }
  static validate(attrs) {
    return new Validate(attrs);
  }
  static validateApprovalSignatures(attrs) {
    return new ValidateApprovalSignatures(attrs);
  }
  static validationMessaging(attrs) {
    return new ValidationMessaging(attrs);
  }
  static version(attrs) {
    return new Version(attrs);
  }
  static versionControl(attrs) {
    return new VersionControl(attrs);
  }
  static viewerPreferences(attrs) {
    return new ViewerPreferences(attrs);
  }
  static webClient(attrs) {
    return new WebClient(attrs);
  }
  static whitespace(attrs) {
    return new Whitespace(attrs);
  }
  static window(attrs) {
    return new Window(attrs);
  }
  static xdc(attrs) {
    return new Xdc(attrs);
  }
  static xdp(attrs) {
    return new Xdp(attrs);
  }
  static xsl(attrs) {
    return new Xsl(attrs);
  }
  static zpl(attrs) {
    return new Zpl(attrs);
  }
}
exports.ConfigNamespace = ConfigNamespace;

/***/ }),
/* 90 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.ConnectionSetNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
const CONNECTION_SET_NS_ID = _namespaces.NamespaceIds.connectionSet.id;
class ConnectionSet extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "connectionSet", true);
    this.wsdlConnection = new _xfa_object.XFAObjectArray();
    this.xmlConnection = new _xfa_object.XFAObjectArray();
    this.xsdConnection = new _xfa_object.XFAObjectArray();
  }
}
class EffectiveInputPolicy extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "effectiveInputPolicy");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class EffectiveOutputPolicy extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "effectiveOutputPolicy");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Operation extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "operation");
    this.id = attributes.id || "";
    this.input = attributes.input || "";
    this.name = attributes.name || "";
    this.output = attributes.output || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class RootElement extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "rootElement");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class SoapAction extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "soapAction");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class SoapAddress extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "soapAddress");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class Uri extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "uri");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class WsdlAddress extends _xfa_object.StringObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "wsdlAddress");
    this.id = attributes.id || "";
    this.name = attributes.name || "";
    this.use = attributes.use || "";
    this.usehref = attributes.usehref || "";
  }
}
class WsdlConnection extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "wsdlConnection", true);
    this.dataDescription = attributes.dataDescription || "";
    this.name = attributes.name || "";
    this.effectiveInputPolicy = null;
    this.effectiveOutputPolicy = null;
    this.operation = null;
    this.soapAction = null;
    this.soapAddress = null;
    this.wsdlAddress = null;
  }
}
class XmlConnection extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "xmlConnection", true);
    this.dataDescription = attributes.dataDescription || "";
    this.name = attributes.name || "";
    this.uri = null;
  }
}
class XsdConnection extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(CONNECTION_SET_NS_ID, "xsdConnection", true);
    this.dataDescription = attributes.dataDescription || "";
    this.name = attributes.name || "";
    this.rootElement = null;
    this.uri = null;
  }
}
class ConnectionSetNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (ConnectionSetNamespace.hasOwnProperty(name)) {
      return ConnectionSetNamespace[name](attributes);
    }
    return undefined;
  }
  static connectionSet(attrs) {
    return new ConnectionSet(attrs);
  }
  static effectiveInputPolicy(attrs) {
    return new EffectiveInputPolicy(attrs);
  }
  static effectiveOutputPolicy(attrs) {
    return new EffectiveOutputPolicy(attrs);
  }
  static operation(attrs) {
    return new Operation(attrs);
  }
  static rootElement(attrs) {
    return new RootElement(attrs);
  }
  static soapAction(attrs) {
    return new SoapAction(attrs);
  }
  static soapAddress(attrs) {
    return new SoapAddress(attrs);
  }
  static uri(attrs) {
    return new Uri(attrs);
  }
  static wsdlAddress(attrs) {
    return new WsdlAddress(attrs);
  }
  static wsdlConnection(attrs) {
    return new WsdlConnection(attrs);
  }
  static xmlConnection(attrs) {
    return new XmlConnection(attrs);
  }
  static xsdConnection(attrs) {
    return new XsdConnection(attrs);
  }
}
exports.ConnectionSetNamespace = ConnectionSetNamespace;

/***/ }),
/* 91 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.DatasetsNamespace = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _namespaces = __w_pdfjs_require__(77);
const DATASETS_NS_ID = _namespaces.NamespaceIds.datasets.id;
class Data extends _xfa_object.XmlObject {
  constructor(attributes) {
    super(DATASETS_NS_ID, "data", attributes);
  }
  [_xfa_object.$isNsAgnostic]() {
    return true;
  }
}
class Datasets extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(DATASETS_NS_ID, "datasets", true);
    this.data = null;
    this.Signature = null;
  }
  [_xfa_object.$onChild](child) {
    const name = child[_xfa_object.$nodeName];
    if (name === "data" && child[_xfa_object.$namespaceId] === DATASETS_NS_ID || name === "Signature" && child[_xfa_object.$namespaceId] === _namespaces.NamespaceIds.signature.id) {
      this[name] = child;
    }
    this[_xfa_object.$appendChild](child);
  }
}
class DatasetsNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (DatasetsNamespace.hasOwnProperty(name)) {
      return DatasetsNamespace[name](attributes);
    }
    return undefined;
  }
  static datasets(attributes) {
    return new Datasets(attributes);
  }
  static data(attributes) {
    return new Data(attributes);
  }
}
exports.DatasetsNamespace = DatasetsNamespace;

/***/ }),
/* 92 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.LocaleSetNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
var _utils = __w_pdfjs_require__(76);
const LOCALE_SET_NS_ID = _namespaces.NamespaceIds.localeSet.id;
class CalendarSymbols extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "calendarSymbols", true);
    this.name = "gregorian";
    this.dayNames = new _xfa_object.XFAObjectArray(2);
    this.eraNames = null;
    this.meridiemNames = null;
    this.monthNames = new _xfa_object.XFAObjectArray(2);
  }
}
class CurrencySymbol extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "currencySymbol");
    this.name = (0, _utils.getStringOption)(attributes.name, ["symbol", "isoname", "decimal"]);
  }
}
class CurrencySymbols extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "currencySymbols", true);
    this.currencySymbol = new _xfa_object.XFAObjectArray(3);
  }
}
class DatePattern extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "datePattern");
    this.name = (0, _utils.getStringOption)(attributes.name, ["full", "long", "med", "short"]);
  }
}
class DatePatterns extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "datePatterns", true);
    this.datePattern = new _xfa_object.XFAObjectArray(4);
  }
}
class DateTimeSymbols extends _xfa_object.ContentObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "dateTimeSymbols");
  }
}
class Day extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "day");
  }
}
class DayNames extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "dayNames", true);
    this.abbr = (0, _utils.getInteger)({
      data: attributes.abbr,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.day = new _xfa_object.XFAObjectArray(7);
  }
}
class Era extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "era");
  }
}
class EraNames extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "eraNames", true);
    this.era = new _xfa_object.XFAObjectArray(2);
  }
}
class Locale extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "locale", true);
    this.desc = attributes.desc || "";
    this.name = "isoname";
    this.calendarSymbols = null;
    this.currencySymbols = null;
    this.datePatterns = null;
    this.dateTimeSymbols = null;
    this.numberPatterns = null;
    this.numberSymbols = null;
    this.timePatterns = null;
    this.typeFaces = null;
  }
}
class LocaleSet extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "localeSet", true);
    this.locale = new _xfa_object.XFAObjectArray();
  }
}
class Meridiem extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "meridiem");
  }
}
class MeridiemNames extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "meridiemNames", true);
    this.meridiem = new _xfa_object.XFAObjectArray(2);
  }
}
class Month extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "month");
  }
}
class MonthNames extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "monthNames", true);
    this.abbr = (0, _utils.getInteger)({
      data: attributes.abbr,
      defaultValue: 0,
      validate: x => x === 1
    });
    this.month = new _xfa_object.XFAObjectArray(12);
  }
}
class NumberPattern extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "numberPattern");
    this.name = (0, _utils.getStringOption)(attributes.name, ["full", "long", "med", "short"]);
  }
}
class NumberPatterns extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "numberPatterns", true);
    this.numberPattern = new _xfa_object.XFAObjectArray(4);
  }
}
class NumberSymbol extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "numberSymbol");
    this.name = (0, _utils.getStringOption)(attributes.name, ["decimal", "grouping", "percent", "minus", "zero"]);
  }
}
class NumberSymbols extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "numberSymbols", true);
    this.numberSymbol = new _xfa_object.XFAObjectArray(5);
  }
}
class TimePattern extends _xfa_object.StringObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "timePattern");
    this.name = (0, _utils.getStringOption)(attributes.name, ["full", "long", "med", "short"]);
  }
}
class TimePatterns extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "timePatterns", true);
    this.timePattern = new _xfa_object.XFAObjectArray(4);
  }
}
class TypeFace extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "typeFace", true);
    this.name = attributes.name | "";
  }
}
class TypeFaces extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(LOCALE_SET_NS_ID, "typeFaces", true);
    this.typeFace = new _xfa_object.XFAObjectArray();
  }
}
class LocaleSetNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (LocaleSetNamespace.hasOwnProperty(name)) {
      return LocaleSetNamespace[name](attributes);
    }
    return undefined;
  }
  static calendarSymbols(attrs) {
    return new CalendarSymbols(attrs);
  }
  static currencySymbol(attrs) {
    return new CurrencySymbol(attrs);
  }
  static currencySymbols(attrs) {
    return new CurrencySymbols(attrs);
  }
  static datePattern(attrs) {
    return new DatePattern(attrs);
  }
  static datePatterns(attrs) {
    return new DatePatterns(attrs);
  }
  static dateTimeSymbols(attrs) {
    return new DateTimeSymbols(attrs);
  }
  static day(attrs) {
    return new Day(attrs);
  }
  static dayNames(attrs) {
    return new DayNames(attrs);
  }
  static era(attrs) {
    return new Era(attrs);
  }
  static eraNames(attrs) {
    return new EraNames(attrs);
  }
  static locale(attrs) {
    return new Locale(attrs);
  }
  static localeSet(attrs) {
    return new LocaleSet(attrs);
  }
  static meridiem(attrs) {
    return new Meridiem(attrs);
  }
  static meridiemNames(attrs) {
    return new MeridiemNames(attrs);
  }
  static month(attrs) {
    return new Month(attrs);
  }
  static monthNames(attrs) {
    return new MonthNames(attrs);
  }
  static numberPattern(attrs) {
    return new NumberPattern(attrs);
  }
  static numberPatterns(attrs) {
    return new NumberPatterns(attrs);
  }
  static numberSymbol(attrs) {
    return new NumberSymbol(attrs);
  }
  static numberSymbols(attrs) {
    return new NumberSymbols(attrs);
  }
  static timePattern(attrs) {
    return new TimePattern(attrs);
  }
  static timePatterns(attrs) {
    return new TimePatterns(attrs);
  }
  static typeFace(attrs) {
    return new TypeFace(attrs);
  }
  static typeFaces(attrs) {
    return new TypeFaces(attrs);
  }
}
exports.LocaleSetNamespace = LocaleSetNamespace;

/***/ }),
/* 93 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.SignatureNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
const SIGNATURE_NS_ID = _namespaces.NamespaceIds.signature.id;
class Signature extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(SIGNATURE_NS_ID, "signature", true);
  }
}
class SignatureNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (SignatureNamespace.hasOwnProperty(name)) {
      return SignatureNamespace[name](attributes);
    }
    return undefined;
  }
  static signature(attributes) {
    return new Signature(attributes);
  }
}
exports.SignatureNamespace = SignatureNamespace;

/***/ }),
/* 94 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.StylesheetNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
const STYLESHEET_NS_ID = _namespaces.NamespaceIds.stylesheet.id;
class Stylesheet extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(STYLESHEET_NS_ID, "stylesheet", true);
  }
}
class StylesheetNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (StylesheetNamespace.hasOwnProperty(name)) {
      return StylesheetNamespace[name](attributes);
    }
    return undefined;
  }
  static stylesheet(attributes) {
    return new Stylesheet(attributes);
  }
}
exports.StylesheetNamespace = StylesheetNamespace;

/***/ }),
/* 95 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XdpNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
const XDP_NS_ID = _namespaces.NamespaceIds.xdp.id;
class Xdp extends _xfa_object.XFAObject {
  constructor(attributes) {
    super(XDP_NS_ID, "xdp", true);
    this.uuid = attributes.uuid || "";
    this.timeStamp = attributes.timeStamp || "";
    this.config = null;
    this.connectionSet = null;
    this.datasets = null;
    this.localeSet = null;
    this.stylesheet = new _xfa_object.XFAObjectArray();
    this.template = null;
  }
  [_xfa_object.$onChildCheck](child) {
    const ns = _namespaces.NamespaceIds[child[_xfa_object.$nodeName]];
    return ns && child[_xfa_object.$namespaceId] === ns.id;
  }
}
class XdpNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (XdpNamespace.hasOwnProperty(name)) {
      return XdpNamespace[name](attributes);
    }
    return undefined;
  }
  static xdp(attributes) {
    return new Xdp(attributes);
  }
}
exports.XdpNamespace = XdpNamespace;

/***/ }),
/* 96 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XhtmlNamespace = void 0;
var _xfa_object = __w_pdfjs_require__(75);
var _namespaces = __w_pdfjs_require__(77);
var _html_utils = __w_pdfjs_require__(82);
var _utils = __w_pdfjs_require__(76);
const XHTML_NS_ID = _namespaces.NamespaceIds.xhtml.id;
const $richText = Symbol();
const VALID_STYLES = new Set(["color", "font", "font-family", "font-size", "font-stretch", "font-style", "font-weight", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "letter-spacing", "line-height", "orphans", "page-break-after", "page-break-before", "page-break-inside", "tab-interval", "tab-stop", "text-align", "text-decoration", "text-indent", "vertical-align", "widows", "kerning-mode", "xfa-font-horizontal-scale", "xfa-font-vertical-scale", "xfa-spacerun", "xfa-tab-stops"]);
const StyleMapping = new Map([["page-break-after", "breakAfter"], ["page-break-before", "breakBefore"], ["page-break-inside", "breakInside"], ["kerning-mode", value => value === "none" ? "none" : "normal"], ["xfa-font-horizontal-scale", value => `scaleX(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-font-vertical-scale", value => `scaleY(${Math.max(0, Math.min(parseInt(value) / 100)).toFixed(2)})`], ["xfa-spacerun", ""], ["xfa-tab-stops", ""], ["font-size", (value, original) => {
  value = original.fontSize = (0, _utils.getMeasurement)(value);
  return (0, _html_utils.measureToString)(0.99 * value);
}], ["letter-spacing", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["line-height", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-bottom", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-left", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-right", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["margin-top", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["text-indent", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))], ["font-family", value => value], ["vertical-align", value => (0, _html_utils.measureToString)((0, _utils.getMeasurement)(value))]]);
const spacesRegExp = /\s+/g;
const crlfRegExp = /[\r\n]+/g;
const crlfForRichTextRegExp = /\r\n?/g;
function mapStyle(styleStr, node, richText) {
  const style = Object.create(null);
  if (!styleStr) {
    return style;
  }
  const original = Object.create(null);
  for (const [key, value] of styleStr.split(";").map(s => s.split(":", 2))) {
    const mapping = StyleMapping.get(key);
    if (mapping === "") {
      continue;
    }
    let newValue = value;
    if (mapping) {
      if (typeof mapping === "string") {
        newValue = mapping;
      } else {
        newValue = mapping(value, original);
      }
    }
    if (key.endsWith("scale")) {
      if (style.transform) {
        style.transform = `${style[key]} ${newValue}`;
      } else {
        style.transform = newValue;
      }
    } else {
      style[key.replaceAll(/-([a-zA-Z])/g, (_, x) => x.toUpperCase())] = newValue;
    }
  }
  if (style.fontFamily) {
    (0, _html_utils.setFontFamily)({
      typeface: style.fontFamily,
      weight: style.fontWeight || "normal",
      posture: style.fontStyle || "normal",
      size: original.fontSize || 0
    }, node, node[_xfa_object.$globalData].fontFinder, style);
  }
  if (richText && style.verticalAlign && style.verticalAlign !== "0px" && style.fontSize) {
    const SUB_SUPER_SCRIPT_FACTOR = 0.583;
    const VERTICAL_FACTOR = 0.333;
    const fontSize = (0, _utils.getMeasurement)(style.fontSize);
    style.fontSize = (0, _html_utils.measureToString)(fontSize * SUB_SUPER_SCRIPT_FACTOR);
    style.verticalAlign = (0, _html_utils.measureToString)(Math.sign((0, _utils.getMeasurement)(style.verticalAlign)) * fontSize * VERTICAL_FACTOR);
  }
  if (richText && style.fontSize) {
    style.fontSize = `calc(${style.fontSize} * var(--scale-factor))`;
  }
  (0, _html_utils.fixTextIndent)(style);
  return style;
}
function checkStyle(node) {
  if (!node.style) {
    return "";
  }
  return node.style.trim().split(/\s*;\s*/).filter(s => !!s).map(s => s.split(/\s*:\s*/, 2)).filter(([key, value]) => {
    if (key === "font-family") {
      node[_xfa_object.$globalData].usedTypefaces.add(value);
    }
    return VALID_STYLES.has(key);
  }).map(kv => kv.join(":")).join(";");
}
const NoWhites = new Set(["body", "html"]);
class XhtmlObject extends _xfa_object.XmlObject {
  constructor(attributes, name) {
    super(XHTML_NS_ID, name);
    this[$richText] = false;
    this.style = attributes.style || "";
  }
  [_xfa_object.$clean](builder) {
    super[_xfa_object.$clean](builder);
    this.style = checkStyle(this);
  }
  [_xfa_object.$acceptWhitespace]() {
    return !NoWhites.has(this[_xfa_object.$nodeName]);
  }
  [_xfa_object.$onText](str, richText = false) {
    if (!richText) {
      str = str.replace(crlfRegExp, "");
      if (!this.style.includes("xfa-spacerun:yes")) {
        str = str.replace(spacesRegExp, " ");
      }
    } else {
      this[$richText] = true;
    }
    if (str) {
      this[_xfa_object.$content] += str;
    }
  }
  [_xfa_object.$pushGlyphs](measure, mustPop = true) {
    const xfaFont = Object.create(null);
    const margin = {
      top: NaN,
      bottom: NaN,
      left: NaN,
      right: NaN
    };
    let lineHeight = null;
    for (const [key, value] of this.style.split(";").map(s => s.split(":", 2))) {
      switch (key) {
        case "font-family":
          xfaFont.typeface = (0, _utils.stripQuotes)(value);
          break;
        case "font-size":
          xfaFont.size = (0, _utils.getMeasurement)(value);
          break;
        case "font-weight":
          xfaFont.weight = value;
          break;
        case "font-style":
          xfaFont.posture = value;
          break;
        case "letter-spacing":
          xfaFont.letterSpacing = (0, _utils.getMeasurement)(value);
          break;
        case "margin":
          const values = value.split(/ \t/).map(x => (0, _utils.getMeasurement)(x));
          switch (values.length) {
            case 1:
              margin.top = margin.bottom = margin.left = margin.right = values[0];
              break;
            case 2:
              margin.top = margin.bottom = values[0];
              margin.left = margin.right = values[1];
              break;
            case 3:
              margin.top = values[0];
              margin.bottom = values[2];
              margin.left = margin.right = values[1];
              break;
            case 4:
              margin.top = values[0];
              margin.left = values[1];
              margin.bottom = values[2];
              margin.right = values[3];
              break;
          }
          break;
        case "margin-top":
          margin.top = (0, _utils.getMeasurement)(value);
          break;
        case "margin-bottom":
          margin.bottom = (0, _utils.getMeasurement)(value);
          break;
        case "margin-left":
          margin.left = (0, _utils.getMeasurement)(value);
          break;
        case "margin-right":
          margin.right = (0, _utils.getMeasurement)(value);
          break;
        case "line-height":
          lineHeight = (0, _utils.getMeasurement)(value);
          break;
      }
    }
    measure.pushData(xfaFont, margin, lineHeight);
    if (this[_xfa_object.$content]) {
      measure.addString(this[_xfa_object.$content]);
    } else {
      for (const child of this[_xfa_object.$getChildren]()) {
        if (child[_xfa_object.$nodeName] === "#text") {
          measure.addString(child[_xfa_object.$content]);
          continue;
        }
        child[_xfa_object.$pushGlyphs](measure);
      }
    }
    if (mustPop) {
      measure.popFont();
    }
  }
  [_xfa_object.$toHTML](availableSpace) {
    const children = [];
    this[_xfa_object.$extra] = {
      children
    };
    this[_xfa_object.$childrenToHTML]({});
    if (children.length === 0 && !this[_xfa_object.$content]) {
      return _utils.HTMLResult.EMPTY;
    }
    let value;
    if (this[$richText]) {
      value = this[_xfa_object.$content] ? this[_xfa_object.$content].replace(crlfForRichTextRegExp, "\n") : undefined;
    } else {
      value = this[_xfa_object.$content] || undefined;
    }
    return _utils.HTMLResult.success({
      name: this[_xfa_object.$nodeName],
      attributes: {
        href: this.href,
        style: mapStyle(this.style, this, this[$richText])
      },
      children,
      value
    });
  }
}
class A extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "a");
    this.href = (0, _html_utils.fixURL)(attributes.href) || "";
  }
}
class B extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "b");
  }
  [_xfa_object.$pushGlyphs](measure) {
    measure.pushFont({
      weight: "bold"
    });
    super[_xfa_object.$pushGlyphs](measure);
    measure.popFont();
  }
}
class Body extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "body");
  }
  [_xfa_object.$toHTML](availableSpace) {
    const res = super[_xfa_object.$toHTML](availableSpace);
    const {
      html
    } = res;
    if (!html) {
      return _utils.HTMLResult.EMPTY;
    }
    html.name = "div";
    html.attributes.class = ["xfaRich"];
    return res;
  }
}
class Br extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "br");
  }
  [_xfa_object.$text]() {
    return "\n";
  }
  [_xfa_object.$pushGlyphs](measure) {
    measure.addString("\n");
  }
  [_xfa_object.$toHTML](availableSpace) {
    return _utils.HTMLResult.success({
      name: "br"
    });
  }
}
class Html extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "html");
  }
  [_xfa_object.$toHTML](availableSpace) {
    const children = [];
    this[_xfa_object.$extra] = {
      children
    };
    this[_xfa_object.$childrenToHTML]({});
    if (children.length === 0) {
      return _utils.HTMLResult.success({
        name: "div",
        attributes: {
          class: ["xfaRich"],
          style: {}
        },
        value: this[_xfa_object.$content] || ""
      });
    }
    if (children.length === 1) {
      const child = children[0];
      if (child.attributes && child.attributes.class.includes("xfaRich")) {
        return _utils.HTMLResult.success(child);
      }
    }
    return _utils.HTMLResult.success({
      name: "div",
      attributes: {
        class: ["xfaRich"],
        style: {}
      },
      children
    });
  }
}
class I extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "i");
  }
  [_xfa_object.$pushGlyphs](measure) {
    measure.pushFont({
      posture: "italic"
    });
    super[_xfa_object.$pushGlyphs](measure);
    measure.popFont();
  }
}
class Li extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "li");
  }
}
class Ol extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "ol");
  }
}
class P extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "p");
  }
  [_xfa_object.$pushGlyphs](measure) {
    super[_xfa_object.$pushGlyphs](measure, false);
    measure.addString("\n");
    measure.addPara();
    measure.popFont();
  }
  [_xfa_object.$text]() {
    const siblings = this[_xfa_object.$getParent]()[_xfa_object.$getChildren]();
    if (siblings.at(-1) === this) {
      return super[_xfa_object.$text]();
    }
    return super[_xfa_object.$text]() + "\n";
  }
}
class Span extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "span");
  }
}
class Sub extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "sub");
  }
}
class Sup extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "sup");
  }
}
class Ul extends XhtmlObject {
  constructor(attributes) {
    super(attributes, "ul");
  }
}
class XhtmlNamespace {
  static [_namespaces.$buildXFAObject](name, attributes) {
    if (XhtmlNamespace.hasOwnProperty(name)) {
      return XhtmlNamespace[name](attributes);
    }
    return undefined;
  }
  static a(attributes) {
    return new A(attributes);
  }
  static b(attributes) {
    return new B(attributes);
  }
  static body(attributes) {
    return new Body(attributes);
  }
  static br(attributes) {
    return new Br(attributes);
  }
  static html(attributes) {
    return new Html(attributes);
  }
  static i(attributes) {
    return new I(attributes);
  }
  static li(attributes) {
    return new Li(attributes);
  }
  static ol(attributes) {
    return new Ol(attributes);
  }
  static p(attributes) {
    return new P(attributes);
  }
  static span(attributes) {
    return new Span(attributes);
  }
  static sub(attributes) {
    return new Sub(attributes);
  }
  static sup(attributes) {
    return new Sup(attributes);
  }
  static ul(attributes) {
    return new Ul(attributes);
  }
}
exports.XhtmlNamespace = XhtmlNamespace;

/***/ }),
/* 97 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.UnknownNamespace = void 0;
var _namespaces = __w_pdfjs_require__(77);
var _xfa_object = __w_pdfjs_require__(75);
class UnknownNamespace {
  constructor(nsId) {
    this.namespaceId = nsId;
  }
  [_namespaces.$buildXFAObject](name, attributes) {
    return new _xfa_object.XmlObject(this.namespaceId, name, attributes);
  }
}
exports.UnknownNamespace = UnknownNamespace;

/***/ }),
/* 98 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.DatasetReader = void 0;
var _util = __w_pdfjs_require__(2);
var _core_utils = __w_pdfjs_require__(4);
var _xml_parser = __w_pdfjs_require__(64);
function decodeString(str) {
  try {
    return (0, _util.stringToUTF8String)(str);
  } catch (ex) {
    (0, _util.warn)(`UTF-8 decoding failed: "${ex}".`);
    return str;
  }
}
class DatasetXMLParser extends _xml_parser.SimpleXMLParser {
  constructor(options) {
    super(options);
    this.node = null;
  }
  onEndElement(name) {
    const node = super.onEndElement(name);
    if (node && name === "xfa:datasets") {
      this.node = node;
      throw new Error("Aborting DatasetXMLParser.");
    }
  }
}
class DatasetReader {
  constructor(data) {
    if (data.datasets) {
      this.node = new _xml_parser.SimpleXMLParser({
        hasAttributes: true
      }).parseFromString(data.datasets).documentElement;
    } else {
      const parser = new DatasetXMLParser({
        hasAttributes: true
      });
      try {
        parser.parseFromString(data["xdp:xdp"]);
      } catch (_) {}
      this.node = parser.node;
    }
  }
  getValue(path) {
    if (!this.node || !path) {
      return "";
    }
    const node = this.node.searchNode((0, _core_utils.parseXFAPath)(path), 0);
    if (!node) {
      return "";
    }
    const first = node.firstChild;
    if (first && first.nodeName === "value") {
      return node.children.map(child => decodeString(child.textContent));
    }
    return decodeString(node.textContent);
  }
}
exports.DatasetReader = DatasetReader;

/***/ }),
/* 99 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.XRef = void 0;
var _util = __w_pdfjs_require__(2);
var _primitives = __w_pdfjs_require__(3);
var _parser = __w_pdfjs_require__(15);
var _core_utils = __w_pdfjs_require__(4);
var _base_stream = __w_pdfjs_require__(5);
var _crypto = __w_pdfjs_require__(65);
class XRef {
  constructor(stream, pdfManager) {
    this.stream = stream;
    this.pdfManager = pdfManager;
    this.entries = [];
    this.xrefstms = Object.create(null);
    this._cacheMap = new Map();
    this._pendingRefs = new _primitives.RefSet();
    this._newPersistentRefNum = null;
    this._newTemporaryRefNum = null;
  }
  getNewPersistentRef(obj) {
    if (this._newPersistentRefNum === null) {
      this._newPersistentRefNum = this.entries.length || 1;
    }
    const num = this._newPersistentRefNum++;
    this._cacheMap.set(num, obj);
    return _primitives.Ref.get(num, 0);
  }
  getNewTemporaryRef() {
    if (this._newTemporaryRefNum === null) {
      this._newTemporaryRefNum = this.entries.length || 1;
    }
    return _primitives.Ref.get(this._newTemporaryRefNum++, 0);
  }
  resetNewTemporaryRef() {
    this._newTemporaryRefNum = null;
  }
  setStartXRef(startXRef) {
    this.startXRefQueue = [startXRef];
  }
  parse(recoveryMode = false) {
    let trailerDict;
    if (!recoveryMode) {
      trailerDict = this.readXRef();
    } else {
      (0, _util.warn)("Indexing all PDF objects");
      trailerDict = this.indexObjects();
    }
    trailerDict.assignXref(this);
    this.trailer = trailerDict;
    let encrypt;
    try {
      encrypt = trailerDict.get("Encrypt");
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`XRef.parse - Invalid "Encrypt" reference: "${ex}".`);
    }
    if (encrypt instanceof _primitives.Dict) {
      const ids = trailerDict.get("ID");
      const fileId = ids && ids.length ? ids[0] : "";
      encrypt.suppressEncryption = true;
      this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
    }
    let root;
    try {
      root = trailerDict.get("Root");
    } catch (ex) {
      if (ex instanceof _core_utils.MissingDataException) {
        throw ex;
      }
      (0, _util.warn)(`XRef.parse - Invalid "Root" reference: "${ex}".`);
    }
    if (root instanceof _primitives.Dict) {
      try {
        const pages = root.get("Pages");
        if (pages instanceof _primitives.Dict) {
          this.root = root;
          return;
        }
      } catch (ex) {
        if (ex instanceof _core_utils.MissingDataException) {
          throw ex;
        }
        (0, _util.warn)(`XRef.parse - Invalid "Pages" reference: "${ex}".`);
      }
    }
    if (!recoveryMode) {
      throw new _core_utils.XRefParseException();
    }
    throw new _util.InvalidPDFException("Invalid Root reference.");
  }
  processXRefTable(parser) {
    if (!("tableState" in this)) {
      this.tableState = {
        entryNum: 0,
        streamPos: parser.lexer.stream.pos,
        parserBuf1: parser.buf1,
        parserBuf2: parser.buf2
      };
    }
    const obj = this.readXRefTable(parser);
    if (!(0, _primitives.isCmd)(obj, "trailer")) {
      throw new _util.FormatError("Invalid XRef table: could not find trailer dictionary");
    }
    let dict = parser.getObj();
    if (!(dict instanceof _primitives.Dict) && dict.dict) {
      dict = dict.dict;
    }
    if (!(dict instanceof _primitives.Dict)) {
      throw new _util.FormatError("Invalid XRef table: could not parse trailer dictionary");
    }
    delete this.tableState;
    return dict;
  }
  readXRefTable(parser) {
    const stream = parser.lexer.stream;
    const tableState = this.tableState;
    stream.pos = tableState.streamPos;
    parser.buf1 = tableState.parserBuf1;
    parser.buf2 = tableState.parserBuf2;
    let obj;
    while (true) {
      if (!("firstEntryNum" in tableState) || !("entryCount" in tableState)) {
        if ((0, _primitives.isCmd)(obj = parser.getObj(), "trailer")) {
          break;
        }
        tableState.firstEntryNum = obj;
        tableState.entryCount = parser.getObj();
      }
      let first = tableState.firstEntryNum;
      const count = tableState.entryCount;
      if (!Number.isInteger(first) || !Number.isInteger(count)) {
        throw new _util.FormatError("Invalid XRef table: wrong types in subsection header");
      }
      for (let i = tableState.entryNum; i < count; i++) {
        tableState.streamPos = stream.pos;
        tableState.entryNum = i;
        tableState.parserBuf1 = parser.buf1;
        tableState.parserBuf2 = parser.buf2;
        const entry = {};
        entry.offset = parser.getObj();
        entry.gen = parser.getObj();
        const type = parser.getObj();
        if (type instanceof _primitives.Cmd) {
          switch (type.cmd) {
            case "f":
              entry.free = true;
              break;
            case "n":
              entry.uncompressed = true;
              break;
          }
        }
        if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
          throw new _util.FormatError(`Invalid entry in XRef subsection: ${first}, ${count}`);
        }
        if (i === 0 && entry.free && first === 1) {
          first = 0;
        }
        if (!this.entries[i + first]) {
          this.entries[i + first] = entry;
        }
      }
      tableState.entryNum = 0;
      tableState.streamPos = stream.pos;
      tableState.parserBuf1 = parser.buf1;
      tableState.parserBuf2 = parser.buf2;
      delete tableState.firstEntryNum;
      delete tableState.entryCount;
    }
    if (this.entries[0] && !this.entries[0].free) {
      throw new _util.FormatError("Invalid XRef table: unexpected first object");
    }
    return obj;
  }
  processXRefStream(stream) {
    if (!("streamState" in this)) {
      const streamParameters = stream.dict;
      const byteWidths = streamParameters.get("W");
      let range = streamParameters.get("Index");
      if (!range) {
        range = [0, streamParameters.get("Size")];
      }
      this.streamState = {
        entryRanges: range,
        byteWidths,
        entryNum: 0,
        streamPos: stream.pos
      };
    }
    this.readXRefStream(stream);
    delete this.streamState;
    return stream.dict;
  }
  readXRefStream(stream) {
    const streamState = this.streamState;
    stream.pos = streamState.streamPos;
    const [typeFieldWidth, offsetFieldWidth, generationFieldWidth] = streamState.byteWidths;
    const entryRanges = streamState.entryRanges;
    while (entryRanges.length > 0) {
      const [first, n] = entryRanges;
      if (!Number.isInteger(first) || !Number.isInteger(n)) {
        throw new _util.FormatError(`Invalid XRef range fields: ${first}, ${n}`);
      }
      if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
        throw new _util.FormatError(`Invalid XRef entry fields length: ${first}, ${n}`);
      }
      for (let i = streamState.entryNum; i < n; ++i) {
        streamState.entryNum = i;
        streamState.streamPos = stream.pos;
        let type = 0,
          offset = 0,
          generation = 0;
        for (let j = 0; j < typeFieldWidth; ++j) {
          const typeByte = stream.getByte();
          if (typeByte === -1) {
            throw new _util.FormatError("Invalid XRef byteWidths 'type'.");
          }
          type = type << 8 | typeByte;
        }
        if (typeFieldWidth === 0) {
          type = 1;
        }
        for (let j = 0; j < offsetFieldWidth; ++j) {
          const offsetByte = stream.getByte();
          if (offsetByte === -1) {
            throw new _util.FormatError("Invalid XRef byteWidths 'offset'.");
          }
          offset = offset << 8 | offsetByte;
        }
        for (let j = 0; j < generationFieldWidth; ++j) {
          const generationByte = stream.getByte();
          if (generationByte === -1) {
            throw new _util.FormatError("Invalid XRef byteWidths 'generation'.");
          }
          generation = generation << 8 | generationByte;
        }
        const entry = {};
        entry.offset = offset;
        entry.gen = generation;
        switch (type) {
          case 0:
            entry.free = true;
            break;
          case 1:
            entry.uncompressed = true;
            break;
          case 2:
            break;
          default:
            throw new _util.FormatError(`Invalid XRef entry type: ${type}`);
        }
        if (!this.entries[first + i]) {
          this.entries[first + i] = entry;
        }
      }
      streamState.entryNum = 0;
      streamState.streamPos = stream.pos;
      entryRanges.splice(0, 2);
    }
  }
  indexObjects() {
    const TAB = 0x9,
      LF = 0xa,
      CR = 0xd,
      SPACE = 0x20;
    const PERCENT = 0x25,
      LT = 0x3c;
    function readToken(data, offset) {
      let token = "",
        ch = data[offset];
      while (ch !== LF && ch !== CR && ch !== LT) {
        if (++offset >= data.length) {
          break;
        }
        token += String.fromCharCode(ch);
        ch = data[offset];
      }
      return token;
    }
    function skipUntil(data, offset, what) {
      const length = what.length,
        dataLength = data.length;
      let skipped = 0;
      while (offset < dataLength) {
        let i = 0;
        while (i < length && data[offset + i] === what[i]) {
          ++i;
        }
        if (i >= length) {
          break;
        }
        offset++;
        skipped++;
      }
      return skipped;
    }
    const gEndobjRegExp = /\b(endobj|\d+\s+\d+\s+obj|xref|trailer)\b/g;
    const gStartxrefRegExp = /\b(startxref|\d+\s+\d+\s+obj)\b/g;
    const objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
    const trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
    const startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
    const xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
    this.entries.length = 0;
    this._cacheMap.clear();
    const stream = this.stream;
    stream.pos = 0;
    const buffer = stream.getBytes(),
      bufferStr = (0, _util.bytesToString)(buffer),
      length = buffer.length;
    let position = stream.start;
    const trailers = [],
      xrefStms = [];
    while (position < length) {
      let ch = buffer[position];
      if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
        ++position;
        continue;
      }
      if (ch === PERCENT) {
        do {
          ++position;
          if (position >= length) {
            break;
          }
          ch = buffer[position];
        } while (ch !== LF && ch !== CR);
        continue;
      }
      const token = readToken(buffer, position);
      let m;
      if (token.startsWith("xref") && (token.length === 4 || /\s/.test(token[4]))) {
        position += skipUntil(buffer, position, trailerBytes);
        trailers.push(position);
        position += skipUntil(buffer, position, startxrefBytes);
      } else if (m = objRegExp.exec(token)) {
        const num = m[1] | 0,
          gen = m[2] | 0;
        const startPos = position + token.length;
        let contentLength,
          updateEntries = false;
        if (!this.entries[num]) {
          updateEntries = true;
        } else if (this.entries[num].gen === gen) {
          try {
            const parser = new _parser.Parser({
              lexer: new _parser.Lexer(stream.makeSubStream(startPos))
            });
            parser.getObj();
            updateEntries = true;
          } catch (ex) {
            if (ex instanceof _core_utils.ParserEOFException) {
              (0, _util.warn)(`indexObjects -- checking object (${token}): "${ex}".`);
            } else {
              updateEntries = true;
            }
          }
        }
        if (updateEntries) {
          this.entries[num] = {
            offset: position - stream.start,
            gen,
            uncompressed: true
          };
        }
        gEndobjRegExp.lastIndex = startPos;
        const match = gEndobjRegExp.exec(bufferStr);
        if (match) {
          const endPos = gEndobjRegExp.lastIndex + 1;
          contentLength = endPos - position;
          if (match[1] !== "endobj") {
            (0, _util.warn)(`indexObjects: Found "${match[1]}" inside of another "obj", ` + 'caused by missing "endobj" -- trying to recover.');
            contentLength -= match[1].length + 1;
          }
        } else {
          contentLength = length - position;
        }
        const content = buffer.subarray(position, position + contentLength);
        const xrefTagOffset = skipUntil(content, 0, xrefBytes);
        if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
          xrefStms.push(position - stream.start);
          this.xrefstms[position - stream.start] = 1;
        }
        position += contentLength;
      } else if (token.startsWith("trailer") && (token.length === 7 || /\s/.test(token[7]))) {
        trailers.push(position);
        const startPos = position + token.length;
        let contentLength;
        gStartxrefRegExp.lastIndex = startPos;
        const match = gStartxrefRegExp.exec(bufferStr);
        if (match) {
          const endPos = gStartxrefRegExp.lastIndex + 1;
          contentLength = endPos - position;
          if (match[1] !== "startxref") {
            (0, _util.warn)(`indexObjects: Found "${match[1]}" after "trailer", ` + 'caused by missing "startxref" -- trying to recover.');
            contentLength -= match[1].length + 1;
          }
        } else {
          contentLength = length - position;
        }
        position += contentLength;
      } else {
        position += token.length + 1;
      }
    }
    for (const xrefStm of xrefStms) {
      this.startXRefQueue.push(xrefStm);
      this.readXRef(true);
    }
    const trailerDicts = [];
    let isEncrypted = false;
    for (const trailer of trailers) {
      stream.pos = trailer;
      const parser = new _parser.Parser({
        lexer: new _parser.Lexer(stream),
        xref: this,
        allowStreams: true,
        recoveryMode: true
      });
      const obj = parser.getObj();
      if (!(0, _primitives.isCmd)(obj, "trailer")) {
        continue;
      }
      const dict = parser.getObj();
      if (!(dict instanceof _primitives.Dict)) {
        continue;
      }
      trailerDicts.push(dict);
      if (dict.has("Encrypt")) {
        isEncrypted = true;
      }
    }
    let trailerDict, trailerError;
    for (const dict of [...trailerDicts, "genFallback", ...trailerDicts]) {
      if (dict === "genFallback") {
        if (!trailerError) {
          break;
        }
        this._generationFallback = true;
        continue;
      }
      let validPagesDict = false;
      try {
        const rootDict = dict.get("Root");
        if (!(rootDict instanceof _primitives.Dict)) {
          continue;
        }
        const pagesDict = rootDict.get("Pages");
        if (!(pagesDict instanceof _primitives.Dict)) {
          continue;
        }
        const pagesCount = pagesDict.get("Count");
        if (Number.isInteger(pagesCount)) {
          validPagesDict = true;
        }
      } catch (ex) {
        trailerError = ex;
        continue;
      }
      if (validPagesDict && (!isEncrypted || dict.has("Encrypt")) && dict.has("ID")) {
        return dict;
      }
      trailerDict = dict;
    }
    if (trailerDict) {
      return trailerDict;
    }
    if (this.topDict) {
      return this.topDict;
    }
    throw new _util.InvalidPDFException("Invalid PDF structure.");
  }
  readXRef(recoveryMode = false) {
    const stream = this.stream;
    const startXRefParsedCache = new Set();
    while (this.startXRefQueue.length) {
      try {
        const startXRef = this.startXRefQueue[0];
        if (startXRefParsedCache.has(startXRef)) {
          (0, _util.warn)("readXRef - skipping XRef table since it was already parsed.");
          this.startXRefQueue.shift();
          continue;
        }
        startXRefParsedCache.add(startXRef);
        stream.pos = startXRef + stream.start;
        const parser = new _parser.Parser({
          lexer: new _parser.Lexer(stream),
          xref: this,
          allowStreams: true
        });
        let obj = parser.getObj();
        let dict;
        if ((0, _primitives.isCmd)(obj, "xref")) {
          dict = this.processXRefTable(parser);
          if (!this.topDict) {
            this.topDict = dict;
          }
          obj = dict.get("XRefStm");
          if (Number.isInteger(obj)) {
            const pos = obj;
            if (!(pos in this.xrefstms)) {
              this.xrefstms[pos] = 1;
              this.startXRefQueue.push(pos);
            }
          }
        } else if (Number.isInteger(obj)) {
          if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), "obj") || !((obj = parser.getObj()) instanceof _base_stream.BaseStream)) {
            throw new _util.FormatError("Invalid XRef stream");
          }
          dict = this.processXRefStream(obj);
          if (!this.topDict) {
            this.topDict = dict;
          }
          if (!dict) {
            throw new _util.FormatError("Failed to read XRef stream");
          }
        } else {
          throw new _util.FormatError("Invalid XRef stream header");
        }
        obj = dict.get("Prev");
        if (Number.isInteger(obj)) {
          this.startXRefQueue.push(obj);
        } else if (obj instanceof _primitives.Ref) {
          this.startXRefQueue.push(obj.num);
        }
      } catch (e) {
        if (e instanceof _core_utils.MissingDataException) {
          throw e;
        }
        (0, _util.info)("(while reading XRef): " + e);
      }
      this.startXRefQueue.shift();
    }
    if (this.topDict) {
      return this.topDict;
    }
    if (recoveryMode) {
      return undefined;
    }
    throw new _core_utils.XRefParseException();
  }
  getEntry(i) {
    const xrefEntry = this.entries[i];
    if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
      return xrefEntry;
    }
    return null;
  }
  fetchIfRef(obj, suppressEncryption = false) {
    if (obj instanceof _primitives.Ref) {
      return this.fetch(obj, suppressEncryption);
    }
    return obj;
  }
  fetch(ref, suppressEncryption = false) {
    if (!(ref instanceof _primitives.Ref)) {
      throw new Error("ref object is not a reference");
    }
    const num = ref.num;
    const cacheEntry = this._cacheMap.get(num);
    if (cacheEntry !== undefined) {
      if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
        cacheEntry.objId = ref.toString();
      }
      return cacheEntry;
    }
    let xrefEntry = this.getEntry(num);
    if (xrefEntry === null) {
      this._cacheMap.set(num, xrefEntry);
      return xrefEntry;
    }
    if (this._pendingRefs.has(ref)) {
      this._pendingRefs.remove(ref);
      (0, _util.warn)(`Ignoring circular reference: ${ref}.`);
      return _primitives.CIRCULAR_REF;
    }
    this._pendingRefs.put(ref);
    try {
      if (xrefEntry.uncompressed) {
        xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
      } else {
        xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
      }
      this._pendingRefs.remove(ref);
    } catch (ex) {
      this._pendingRefs.remove(ref);
      throw ex;
    }
    if (xrefEntry instanceof _primitives.Dict) {
      xrefEntry.objId = ref.toString();
    } else if (xrefEntry instanceof _base_stream.BaseStream) {
      xrefEntry.dict.objId = ref.toString();
    }
    return xrefEntry;
  }
  fetchUncompressed(ref, xrefEntry, suppressEncryption = false) {
    const gen = ref.gen;
    let num = ref.num;
    if (xrefEntry.gen !== gen) {
      const msg = `Inconsistent generation in XRef: ${ref}`;
      if (this._generationFallback && xrefEntry.gen < gen) {
        (0, _util.warn)(msg);
        return this.fetchUncompressed(_primitives.Ref.get(num, xrefEntry.gen), xrefEntry, suppressEncryption);
      }
      throw new _core_utils.XRefEntryException(msg);
    }
    const stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
    const parser = new _parser.Parser({
      lexer: new _parser.Lexer(stream),
      xref: this,
      allowStreams: true
    });
    const obj1 = parser.getObj();
    const obj2 = parser.getObj();
    const obj3 = parser.getObj();
    if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
      throw new _core_utils.XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
    }
    if (obj3.cmd !== "obj") {
      if (obj3.cmd.startsWith("obj")) {
        num = parseInt(obj3.cmd.substring(3), 10);
        if (!Number.isNaN(num)) {
          return num;
        }
      }
      throw new _core_utils.XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
    }
    if (this.encrypt && !suppressEncryption) {
      xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
    } else {
      xrefEntry = parser.getObj();
    }
    if (!(xrefEntry instanceof _base_stream.BaseStream)) {
      this._cacheMap.set(num, xrefEntry);
    }
    return xrefEntry;
  }
  fetchCompressed(ref, xrefEntry, suppressEncryption = false) {
    const tableOffset = xrefEntry.offset;
    const stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
    if (!(stream instanceof _base_stream.BaseStream)) {
      throw new _util.FormatError("bad ObjStm stream");
    }
    const first = stream.dict.get("First");
    const n = stream.dict.get("N");
    if (!Number.isInteger(first) || !Number.isInteger(n)) {
      throw new _util.FormatError("invalid first and n parameters for ObjStm stream");
    }
    let parser = new _parser.Parser({
      lexer: new _parser.Lexer(stream),
      xref: this,
      allowStreams: true
    });
    const nums = new Array(n);
    const offsets = new Array(n);
    for (let i = 0; i < n; ++i) {
      const num = parser.getObj();
      if (!Number.isInteger(num)) {
        throw new _util.FormatError(`invalid object number in the ObjStm stream: ${num}`);
      }
      const offset = parser.getObj();
      if (!Number.isInteger(offset)) {
        throw new _util.FormatError(`invalid object offset in the ObjStm stream: ${offset}`);
      }
      nums[i] = num;
      offsets[i] = offset;
    }
    const start = (stream.start || 0) + first;
    const entries = new Array(n);
    for (let i = 0; i < n; ++i) {
      const length = i < n - 1 ? offsets[i + 1] - offsets[i] : undefined;
      if (length < 0) {
        throw new _util.FormatError("Invalid offset in the ObjStm stream.");
      }
      parser = new _parser.Parser({
        lexer: new _parser.Lexer(stream.makeSubStream(start + offsets[i], length, stream.dict)),
        xref: this,
        allowStreams: true
      });
      const obj = parser.getObj();
      entries[i] = obj;
      if (obj instanceof _base_stream.BaseStream) {
        continue;
      }
      const num = nums[i],
        entry = this.entries[num];
      if (entry && entry.offset === tableOffset && entry.gen === i) {
        this._cacheMap.set(num, obj);
      }
    }
    xrefEntry = entries[xrefEntry.gen];
    if (xrefEntry === undefined) {
      throw new _core_utils.XRefEntryException(`Bad (compressed) XRef entry: ${ref}`);
    }
    return xrefEntry;
  }
  async fetchIfRefAsync(obj, suppressEncryption) {
    if (obj instanceof _primitives.Ref) {
      return this.fetchAsync(obj, suppressEncryption);
    }
    return obj;
  }
  async fetchAsync(ref, suppressEncryption) {
    try {
      return this.fetch(ref, suppressEncryption);
    } catch (ex) {
      if (!(ex instanceof _core_utils.MissingDataException)) {
        throw ex;
      }
      await this.pdfManager.requestRange(ex.begin, ex.end);
      return this.fetchAsync(ref, suppressEncryption);
    }
  }
  getCatalogObj() {
    return this.root;
  }
}
exports.XRef = XRef;

/***/ }),
/* 100 */
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.isNodeJS = void 0;
const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
exports.isNodeJS = isNodeJS;

/***/ }),
/* 101 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.MessageHandler = void 0;
var _util = __w_pdfjs_require__(2);
const CallbackKind = {
  UNKNOWN: 0,
  DATA: 1,
  ERROR: 2
};
const StreamKind = {
  UNKNOWN: 0,
  CANCEL: 1,
  CANCEL_COMPLETE: 2,
  CLOSE: 3,
  ENQUEUE: 4,
  ERROR: 5,
  PULL: 6,
  PULL_COMPLETE: 7,
  START_COMPLETE: 8
};
function wrapReason(reason) {
  if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
    (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
  }
  switch (reason.name) {
    case "AbortException":
      return new _util.AbortException(reason.message);
    case "MissingPDFException":
      return new _util.MissingPDFException(reason.message);
    case "PasswordException":
      return new _util.PasswordException(reason.message, reason.code);
    case "UnexpectedResponseException":
      return new _util.UnexpectedResponseException(reason.message, reason.status);
    case "UnknownErrorException":
      return new _util.UnknownErrorException(reason.message, reason.details);
    default:
      return new _util.UnknownErrorException(reason.message, reason.toString());
  }
}
class MessageHandler {
  constructor(sourceName, targetName, comObj) {
    this.sourceName = sourceName;
    this.targetName = targetName;
    this.comObj = comObj;
    this.callbackId = 1;
    this.streamId = 1;
    this.streamSinks = Object.create(null);
    this.streamControllers = Object.create(null);
    this.callbackCapabilities = Object.create(null);
    this.actionHandler = Object.create(null);
    this._onComObjOnMessage = event => {
      const data = event.data;
      if (data.targetName !== this.sourceName) {
        return;
      }
      if (data.stream) {
        this._processStreamMessage(data);
        return;
      }
      if (data.callback) {
        const callbackId = data.callbackId;
        const capability = this.callbackCapabilities[callbackId];
        if (!capability) {
          throw new Error(`Cannot resolve callback ${callbackId}`);
        }
        delete this.callbackCapabilities[callbackId];
        if (data.callback === CallbackKind.DATA) {
          capability.resolve(data.data);
        } else if (data.callback === CallbackKind.ERROR) {
          capability.reject(wrapReason(data.reason));
        } else {
          throw new Error("Unexpected callback case");
        }
        return;
      }
      const action = this.actionHandler[data.action];
      if (!action) {
        throw new Error(`Unknown action from worker: ${data.action}`);
      }
      if (data.callbackId) {
        const cbSourceName = this.sourceName;
        const cbTargetName = data.sourceName;
        new Promise(function (resolve) {
          resolve(action(data.data));
        }).then(function (result) {
          comObj.postMessage({
            sourceName: cbSourceName,
            targetName: cbTargetName,
            callback: CallbackKind.DATA,
            callbackId: data.callbackId,
            data: result
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName: cbSourceName,
            targetName: cbTargetName,
            callback: CallbackKind.ERROR,
            callbackId: data.callbackId,
            reason: wrapReason(reason)
          });
        });
        return;
      }
      if (data.streamId) {
        this._createStreamSink(data);
        return;
      }
      action(data.data);
    };
    comObj.addEventListener("message", this._onComObjOnMessage);
  }
  on(actionName, handler) {
    const ah = this.actionHandler;
    if (ah[actionName]) {
      throw new Error(`There is already an actionName called "${actionName}"`);
    }
    ah[actionName] = handler;
  }
  send(actionName, data, transfers) {
    this.comObj.postMessage({
      sourceName: this.sourceName,
      targetName: this.targetName,
      action: actionName,
      data
    }, transfers);
  }
  sendWithPromise(actionName, data, transfers) {
    const callbackId = this.callbackId++;
    const capability = (0, _util.createPromiseCapability)();
    this.callbackCapabilities[callbackId] = capability;
    try {
      this.comObj.postMessage({
        sourceName: this.sourceName,
        targetName: this.targetName,
        action: actionName,
        callbackId,
        data
      }, transfers);
    } catch (ex) {
      capability.reject(ex);
    }
    return capability.promise;
  }
  sendWithStream(actionName, data, queueingStrategy, transfers) {
    const streamId = this.streamId++,
      sourceName = this.sourceName,
      targetName = this.targetName,
      comObj = this.comObj;
    return new ReadableStream({
      start: controller => {
        const startCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId] = {
          controller,
          startCall: startCapability,
          pullCall: null,
          cancelCall: null,
          isClosed: false
        };
        comObj.postMessage({
          sourceName,
          targetName,
          action: actionName,
          streamId,
          data,
          desiredSize: controller.desiredSize
        }, transfers);
        return startCapability.promise;
      },
      pull: controller => {
        const pullCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId].pullCall = pullCapability;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.PULL,
          streamId,
          desiredSize: controller.desiredSize
        });
        return pullCapability.promise;
      },
      cancel: reason => {
        (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
        const cancelCapability = (0, _util.createPromiseCapability)();
        this.streamControllers[streamId].cancelCall = cancelCapability;
        this.streamControllers[streamId].isClosed = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CANCEL,
          streamId,
          reason: wrapReason(reason)
        });
        return cancelCapability.promise;
      }
    }, queueingStrategy);
  }
  _createStreamSink(data) {
    const streamId = data.streamId,
      sourceName = this.sourceName,
      targetName = data.sourceName,
      comObj = this.comObj;
    const self = this,
      action = this.actionHandler[data.action];
    const streamSink = {
      enqueue(chunk, size = 1, transfers) {
        if (this.isCancelled) {
          return;
        }
        const lastDesiredSize = this.desiredSize;
        this.desiredSize -= size;
        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
          this.sinkCapability = (0, _util.createPromiseCapability)();
          this.ready = this.sinkCapability.promise;
        }
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ENQUEUE,
          streamId,
          chunk
        }, transfers);
      },
      close() {
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.CLOSE,
          streamId
        });
        delete self.streamSinks[streamId];
      },
      error(reason) {
        (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
        if (this.isCancelled) {
          return;
        }
        this.isCancelled = true;
        comObj.postMessage({
          sourceName,
          targetName,
          stream: StreamKind.ERROR,
          streamId,
          reason: wrapReason(reason)
        });
      },
      sinkCapability: (0, _util.createPromiseCapability)(),
      onPull: null,
      onCancel: null,
      isCancelled: false,
      desiredSize: data.desiredSize,
      ready: null
    };
    streamSink.sinkCapability.resolve();
    streamSink.ready = streamSink.sinkCapability.promise;
    this.streamSinks[streamId] = streamSink;
    new Promise(function (resolve) {
      resolve(action(data.data, streamSink));
    }).then(function () {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        success: true
      });
    }, function (reason) {
      comObj.postMessage({
        sourceName,
        targetName,
        stream: StreamKind.START_COMPLETE,
        streamId,
        reason: wrapReason(reason)
      });
    });
  }
  _processStreamMessage(data) {
    const streamId = data.streamId,
      sourceName = this.sourceName,
      targetName = data.sourceName,
      comObj = this.comObj;
    const streamController = this.streamControllers[streamId],
      streamSink = this.streamSinks[streamId];
    switch (data.stream) {
      case StreamKind.START_COMPLETE:
        if (data.success) {
          streamController.startCall.resolve();
        } else {
          streamController.startCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL_COMPLETE:
        if (data.success) {
          streamController.pullCall.resolve();
        } else {
          streamController.pullCall.reject(wrapReason(data.reason));
        }
        break;
      case StreamKind.PULL:
        if (!streamSink) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
          break;
        }
        if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
          streamSink.sinkCapability.resolve();
        }
        streamSink.desiredSize = data.desiredSize;
        new Promise(function (resolve) {
          resolve(streamSink.onPull && streamSink.onPull());
        }).then(function () {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            success: true
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.PULL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        break;
      case StreamKind.ENQUEUE:
        (0, _util.assert)(streamController, "enqueue should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.controller.enqueue(data.chunk);
        break;
      case StreamKind.CLOSE:
        (0, _util.assert)(streamController, "close should have stream controller");
        if (streamController.isClosed) {
          break;
        }
        streamController.isClosed = true;
        streamController.controller.close();
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.ERROR:
        (0, _util.assert)(streamController, "error should have stream controller");
        streamController.controller.error(wrapReason(data.reason));
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL_COMPLETE:
        if (data.success) {
          streamController.cancelCall.resolve();
        } else {
          streamController.cancelCall.reject(wrapReason(data.reason));
        }
        this._deleteStreamController(streamController, streamId);
        break;
      case StreamKind.CANCEL:
        if (!streamSink) {
          break;
        }
        new Promise(function (resolve) {
          resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
        }).then(function () {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            success: true
          });
        }, function (reason) {
          comObj.postMessage({
            sourceName,
            targetName,
            stream: StreamKind.CANCEL_COMPLETE,
            streamId,
            reason: wrapReason(reason)
          });
        });
        streamSink.sinkCapability.reject(wrapReason(data.reason));
        streamSink.isCancelled = true;
        delete this.streamSinks[streamId];
        break;
      default:
        throw new Error("Unexpected stream case");
    }
  }
  async _deleteStreamController(streamController, streamId) {
    await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
    delete this.streamControllers[streamId];
  }
  destroy() {
    this.comObj.removeEventListener("message", this._onComObjOnMessage);
  }
}
exports.MessageHandler = MessageHandler;

/***/ }),
/* 102 */
/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.PDFWorkerStream = void 0;
var _util = __w_pdfjs_require__(2);
class PDFWorkerStream {
  constructor(msgHandler) {
    this._msgHandler = msgHandler;
    this._contentLength = null;
    this._fullRequestReader = null;
    this._rangeRequestReaders = [];
  }
  getFullReader() {
    (0, _util.assert)(!this._fullRequestReader, "PDFWorkerStream.getFullReader can only be called once.");
    this._fullRequestReader = new PDFWorkerStreamReader(this._msgHandler);
    return this._fullRequestReader;
  }
  getRangeReader(begin, end) {
    const reader = new PDFWorkerStreamRangeReader(begin, end, this._msgHandler);
    this._rangeRequestReaders.push(reader);
    return reader;
  }
  cancelAllRequests(reason) {
    if (this._fullRequestReader) {
      this._fullRequestReader.cancel(reason);
    }
    for (const reader of this._rangeRequestReaders.slice(0)) {
      reader.cancel(reason);
    }
  }
}
exports.PDFWorkerStream = PDFWorkerStream;
class PDFWorkerStreamReader {
  constructor(msgHandler) {
    this._msgHandler = msgHandler;
    this.onProgress = null;
    this._contentLength = null;
    this._isRangeSupported = false;
    this._isStreamingSupported = false;
    const readableStream = this._msgHandler.sendWithStream("GetReader");
    this._reader = readableStream.getReader();
    this._headersReady = this._msgHandler.sendWithPromise("ReaderHeadersReady").then(data => {
      this._isStreamingSupported = data.isStreamingSupported;
      this._isRangeSupported = data.isRangeSupported;
      this._contentLength = data.contentLength;
    });
  }
  get headersReady() {
    return this._headersReady;
  }
  get contentLength() {
    return this._contentLength;
  }
  get isStreamingSupported() {
    return this._isStreamingSupported;
  }
  get isRangeSupported() {
    return this._isRangeSupported;
  }
  async read() {
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value: undefined,
        done: true
      };
    }
    return {
      value: value.buffer,
      done: false
    };
  }
  cancel(reason) {
    this._reader.cancel(reason);
  }
}
class PDFWorkerStreamRangeReader {
  constructor(begin, end, msgHandler) {
    this._msgHandler = msgHandler;
    this.onProgress = null;
    const readableStream = this._msgHandler.sendWithStream("GetRangeReader", {
      begin,
      end
    });
    this._reader = readableStream.getReader();
  }
  get isStreamingSupported() {
    return false;
  }
  async read() {
    const {
      value,
      done
    } = await this._reader.read();
    if (done) {
      return {
        value: undefined,
        done: true
      };
    }
    return {
      value: value.buffer,
      done: false
    };
  }
  cancel(reason) {
    this._reader.cancel(reason);
  }
}

/***/ })
/******/ 	]);
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __w_pdfjs_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__w_pdfjs_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__w_pdfjs_require__.o(definition, key) && !__w_pdfjs_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__w_pdfjs_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__w_pdfjs_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
var exports = __webpack_exports__;


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
Object.defineProperty(exports, "WorkerMessageHandler", ({
  enumerable: true,
  get: function () {
    return _worker.WorkerMessageHandler;
  }
}));
var _worker = __w_pdfjs_require__(1);
const pdfjsVersion = '3.4.50';
const pdfjsBuild = '00560ed83';
})();

/******/ 	return __webpack_exports__;
/******/ })()
;
});

function makeGrid (attachablesGridData) {
  // Variables ----------------------------------------------------------------
  var $grid = $('#' + attachablesGridData.gridId );
  var $gridTable;
  var gridAsClass = '.' + attachablesGridData.gridId;
  var gridAsId = '#' + attachablesGridData.gridId;
  var docBlockId = attachablesGridData.gridId;
  var investmentId = attachablesGridData.investmentId;
  var createdAtMin = attachablesGridData.createdAtMin;
  var createdAtMax = attachablesGridData.createdAtMax;
  var selectAllJsonUrl = attachablesGridData.selectAllJsonUrl;
  var gridRows;
  var gridRow;
  var gridRowId;

  var gridEl = document.getElementById(attachablesGridData.gridId);
  var gridHeaderEl = gridEl.querySelector('.multiple-download-header');
  var headerInfoEl = gridEl.querySelector('.multiple-download-info');
  var headerInfoMaxEl = gridEl.querySelector('.multiple-download-max');
  var selectAllBtnEl = gridEl.querySelector('.select-all-button');
  var deselectAllBtnEl = gridEl.querySelector('.deselect-all-button');
  var downloadBtnEl = gridEl.querySelector('.multiple-download-button');
  var highlightedEls = gridEl.querySelectorAll('.ui-state-highlight');
  var selectionEl = gridEl.querySelector('.multiple-download-selection');
  var modalEl;
  var modalHeaderEl;
  var modaltitleEl;
  var modalSubtitleEl;
  var modalBodyEl;
  var modalBodyMessageEl;
  var modalBtnCancelEl;
  var modalBtnCloseEl;
  var $checkboxAllEl;
  var gridFormEl;
  var formButtonEls;
  var standardSelectionEl;
  var viewOnlyLinkEls;
  var viewOnlyRowEls;

  var downloadMaxLimitTag = document.querySelector('meta[name="owner-max-mdd-limit"]');
  var downloadMaxLimitNum = Number(downloadMaxLimitTag.getAttribute('content'));
  var hideMddHeaderTag = document.querySelector('meta[name="owner-hide-mdd-header"]');
  var hideMddHeader = hideMddHeaderTag.getAttribute('content');
  var shiftSelectionActive = false;
  var cmdSelectionActive = false;
  var selectedIdsArray = [];
  var selectionExists = false;

  var downloadMultipleDocuments;
  var totalRecordsFromGrid;
  var singleDownloadLinkEls;
  var cBoxEls;
  var customCheckboxEls;
  var tableCBoxEls;
  var startRow;
  var endRow;
  var iStart;
  var iEnd;

  // Functions ----------------------------------------------------------------
  function insertMaxLimitInHeader() {
    // Change text within headerInfoMaxEl to be the downloadMaxLimitNum
    headerInfoMaxEl.textContent = downloadMaxLimitNum;
  }

  function createModal() {
    var modalExists = document.getElementsByClassName('modal-container');

    if (0 === modalExists.length) {
      // Create modal structure
      var newModalContainer = document.createElement('div');
      var newModal = document.createElement('aside');
      var newModalHeader = document.createElement('div');
      var newModalTitle = document.createElement('div');
      var newModalSubitle = document.createElement('div');
      var newModalBody = document.createElement('div');
      var newModalMessage = document.createElement('div');
      var newModalFooter = document.createElement('div');
      var newModalCancelBtn = document.createElement('a');
      var newModalCloseBtn = document.createElement('a');

      // Add proper classes to new elements
      newModalContainer.classList.add('modal-container');
      newModal.classList.add('modal');
      newModal.setAttribute('id', 'modal');
      newModalHeader.classList.add('modal-header');
      newModalTitle.classList.add('modal-header-title');
      newModalSubitle.classList.add('modal-header-subtitle');
      newModalBody.classList.add('modal-body');
      newModalMessage.classList.add('modal-body-message');
      newModalFooter.classList.add('modal-footer');
      newModalCancelBtn.classList.add('btn');
      newModalCancelBtn.classList.add('btn-flat');
      newModalCancelBtn.classList.add('modal-btn-cancel');
      newModalCancelBtn.setAttribute('href', '#');
      newModalCancelBtn.textContent = 'Cancel Download';
      newModalCloseBtn.classList.add('btn');
      newModalCloseBtn.classList.add('btn-ghost');
      newModalCloseBtn.classList.add('btn-hide');
      newModalCloseBtn.classList.add('modal-btn-close');
      newModalCloseBtn.setAttribute('href', '#');
      newModalCloseBtn.textContent = 'Close';

      // Add elements together in proper order
      newModalContainer.appendChild(newModal);
      newModal.appendChild(newModalHeader);
      newModalHeader.appendChild(newModalTitle);
      newModalHeader.appendChild(newModalSubitle);
      newModal.appendChild(newModalBody);
      newModalBody.appendChild(newModalMessage);
      newModalBody.appendChild(newModalFooter);
      newModalFooter.appendChild(newModalCancelBtn);
      newModalFooter.appendChild(newModalCloseBtn);

      // Add newModal to <body>
      document.body.appendChild(newModalContainer);
    }

    // Set element variables to newly created elements
    modalEl = document.getElementById('modal');
    modalHeaderEl = document.querySelector('.modal-header');
    modaltitleEl = document.querySelector('.modal-header-title');
    modalSubtitleEl = document.querySelector('.modal-header-subtitle');
    modalBodyEl = document.querySelector('.modal-body');
    modalBodyMessageEl = document.querySelector('.modal-body-message');
    modalBtnCancelEl = document.querySelector('.modal-btn-cancel');
    modalBtnCloseEl = document.querySelector('.modal-btn-close');

    // Event Listeners to elements associated with the modal
    modalBtnCancelEl.addEventListener('click', function(event) {
      event.preventDefault();
      downloadMultipleDocuments.cancel();
      cancelModalState();
      closeModalState();
    }, false);
  }

  function activateModalState() {
    $.fancybox(
      {
        'transitionIn':           'fade',
        'transitionOut':          'fade',
        'speedIn':                '300',
        'speedOut':               '300',
        'autoDimensions':         false,
        'width':                  420,
        'height':                 'auto',
        'hideOnOverlayClick':     false,
        'showCloseButton':        false,
        'href':                   '#modal'
      }
    );
  }

  function defaultModalState() {
    modaltitleEl.textContent = 'Your document download has started';
    modalSubtitleEl.textContent = 'Please wait as we prepare your file';
    modalBodyMessageEl.innerHTML = '<img class="modal-body-loading-img" alt="Loading gif" src="/assets/controlpanel/loading_small-91c44f75cb490a62448400482f83f9956ae1aa06528065fc86e1ebba2cf22eee.gif" /> Zipping documents';
    if ( modalHeaderEl.classList.contains('modal-header-error') ) {
      modalHeaderEl.classList.remove('modal-header-error');
    }

    if ( modalBodyEl.classList.contains('modal-body-error') ) {
      modalBodyEl.classList.remove('modal-body-error');
    }

    if ( modalBtnCancelEl.classList.contains('btn-hide') ) {
      modalBtnCancelEl.classList.remove('btn-hide');
    }

    if ( !modalBtnCloseEl.classList.contains('btn-hide') ) {
      modalBtnCloseEl.classList.add('btn-hide');
    }
  }

  function cancelModalState() {
    modaltitleEl.textContent = 'Your document download has been cancelled';
    modalSubtitleEl.textContent = 'No documents have been downloaded';
    modalBodyMessageEl.innerHTML = 'You have cancelled the document download';
    modalBtnCancelEl.classList.add('btn-hide');
    modalBtnCloseEl.classList.remove('btn-hide');
  }

  function completeModalState(fileName) {
    modaltitleEl.textContent = 'Your document download has completed';

    if ( 1 === selectedIdsArray.length ) {
      modalSubtitleEl.textContent = selectedIdsArray.length + ' Document was zipped';
    } else {
      modalSubtitleEl.textContent = selectedIdsArray.length + ' Documents were zipped';
    }

    modalBodyMessageEl.innerHTML = 'Look for this zip file in your downloads folder:<br>' +
    '<span class="modal-body-filename">' + fileName + '</span>';
    modalBtnCancelEl.classList.add('btn-hide');
    modalBtnCloseEl.classList.remove('btn-hide');
  }

  function errorModalState(errorMessage) {
    modaltitleEl.textContent = 'Unable to download documents';
    modalSubtitleEl.textContent = 'No documents have been downloaded';
    modalBodyMessageEl.innerHTML = 'There is a problem with at least one of the documents you are trying ' +
    'to download. Please download documents individually.<br><br>' + errorMessage;
    modalHeaderEl.classList.add('modal-header-error');
    modalBodyEl.classList.add('modal-body-error');
    modalBtnCancelEl.classList.add('btn-hide');
    modalBtnCloseEl.classList.remove('btn-hide');
  }

  function maxLimitPassedModalState() {
    modaltitleEl.textContent = 'You have reached the maximum number of documents that can be downloaded at once';
    modalSubtitleEl.textContent = 'You may download ' + downloadMaxLimitNum + ' documents at a time';
    modalBodyMessageEl.innerHTML = 'You are trying to download more documents<br> than you may download at one time';
    modalHeaderEl.classList.add('modal-header-error');
    modalBodyEl.classList.add('modal-body-error');
    modalBtnCancelEl.classList.add('btn-hide');
    modalBtnCloseEl.classList.remove('btn-hide');
  }

  function closeModalState() {
    var autoCloseDelay = setTimeout(function() {
      $.fancybox.close();
    }, 10000);

    modalBtnCloseEl.addEventListener('click', function(event) {
      event.preventDefault();
      clearTimeout(autoCloseDelay);
      $.fancybox.close();
    });
  }

  function changeTitleCellAttribute() {
    var titleCellEls = gridEl.querySelectorAll('[aria-describedby="attachables_grid_title"]');
    var compareDownload = 'Download';
    var compareViewDownload = 'View | Download';
    var cleanCellTitleAttr;

    for (var i = 0; i < titleCellEls.length; i++) {
      var titleCellEl = titleCellEls[i];
      var cellTitleAttr = titleCellEl.getAttribute('title');
      var spliceIndex = cellTitleAttr.indexOf(compareViewDownload);

      if ( -1 !== spliceIndex ) {
        cleanCellTitleAttr = cellTitleAttr.slice(0, spliceIndex);
        titleCellEl.setAttribute('title', cleanCellTitleAttr);
        continue;
      }

      spliceIndex = cellTitleAttr.indexOf(compareDownload);

      if ( -1 !== spliceIndex ) {
        cleanCellTitleAttr = cellTitleAttr.slice(0, spliceIndex);
        titleCellEl.setAttribute('title', cleanCellTitleAttr);
      }
    }
  }

  function changeSelectAllRecord() {
    $.ajax({
      type: 'GET',
      url: selectAllJsonUrl,
      data: ($.param( getGridFilters() ) +
                      getSearchScopeParams() +
                      getDateLimitParams()),
      success: function(response) {
        totalRecordsFromGrid = response.length;
        selectAllBtnEl.setAttribute('value', 'Select all ' + totalRecordsFromGrid + ' documents');
      }
    });
  }

  function checkMaxLimit(selectedArrayLength) {
    if ( downloadMaxLimitNum ) {
      if ( downloadMaxLimitNum < selectedArrayLength ) {
        maxLimitPassedModalState();
        activateModalState();
        closeModalState();
      }
    }
  }

  function resetAllSelection() {
    clearAllSelected();
    $gridTable.jqGrid('resetSelection');
    selectedIdsArray = [];
  }

  function toggleElementDisplay(elInGrid, option, className) {
    if ( 'add' === option ) {
      elInGrid.classList.add(className);
    } else if ( 'remove' === option ) {
      elInGrid.classList.remove(className);
    }
  }

  function toggleAllOfElementDisplay(elsInGrid, option, className) {
    var singleElement;

    for ( var i = 0; i < elsInGrid.length; i++ ) {
      singleElement = elsInGrid[i];
      toggleElementDisplay(singleElement, option, className);
    }
  }

  function checkboxLabels(cBoxEls) {
    var cBoxEl;

    for (var i = 0; i < cBoxEls.length; i++) {
      cBoxEl = cBoxEls[i];
      addNewLabels(cBoxEl);
    }
  }

  function addNewLabels(cBoxEl) {
    var cBoxId = cBoxEl.id;

    cBoxEl.insertAdjacentHTML('afterend', '<label class="custom-checkbox" for="' + cBoxId + '"></label>');
  }

  function clearAllSelected() {
    toggleAllOfElementDisplay(customCheckboxEls, 'remove', 'show-checkbox');
    toggleElementDisplay(downloadBtnEl, 'remove', 'show-button');
    toggleElementDisplay(headerInfoEl, 'remove', 'show-info');
    toggleAllOfElementDisplay(singleDownloadLinkEls, 'remove', 'hide-links');
  }

  function bindFilterButtons() {
    for (var i = 0; i < formButtonEls.length; i++) {
      var formButtonEl = formButtonEls[i];

      formButtonEl.addEventListener('click', resetAllSelection);
    }
  }

  function bindStandardSelectEl() {
    if (standardSelectionEl) {
      standardSelectionEl.addEventListener('change', resetAllSelection);
    }
  }

  function selectRowsInArray() {
    var isArrayInPage = 0;

    for (var i = 0; i < gridRows.length; i++) {
      gridRow = gridRows[i];
      gridRowId = gridRow.id;

      if ( 0 !== selectedIdsArray.length ) {
        if ( -1 !== selectedIdsArray.indexOf(gridRowId) ) {
          isArrayInPage++;
          $gridTable.jqGrid('setSelection', gridRowId, false);
        }
      }
    }

    if ( 0 < isArrayInPage ) {
      selectionExists = true;
    } else {
      selectionExists = false;
    }
  }

  function changeHeaderInfo() {
    // Change header info number to reflect the amount of docs selected
    if ( 1 === selectedIdsArray.length ) {
      selectionEl.textContent = selectedIdsArray.length + ' document is selected';
    } else {
      selectionEl.textContent = selectedIdsArray.length + ' documents are selected';
    }
  }

  function toggleCheckboxes(tableCBoxEls, addAllToList) {
    var tableCBoxEl;

    for (var i = 0; i < tableCBoxEls.length; i++) {
      tableCBoxEl = tableCBoxEls[i];

      var attachableId = tableCBoxEl.id.split('_').pop();
      var index = selectedIdsArray.indexOf(attachableId);

      if ( addAllToList ) {
        if ( -1 === index ) {
          selectedIdsArray.push(attachableId);
        }
      } else {
        if ( -1 !== index ) {
          selectedIdsArray.splice(index, 1);
        }
      }
    }
  }

  function beforeSelectCheckboxes() {
    var tableCBoxEl;

    for (var i = 0; i < tableCBoxEls.length; i++) {
      tableCBoxEl = tableCBoxEls[i];
      var attachableId = tableCBoxEl.id.split('_').pop();
      var index = selectedIdsArray.indexOf(attachableId);

      if ( -1 < index ) {
        selectedIdsArray.splice(index, 1);
        $gridTable.jqGrid('setSelection', attachableId, false);
      }
    }
  }

  function setDocBlocId() {
    docBlockId = docBlockId.split('_').pop();
    docBlockId = Number(docBlockId);
  }

  function getSearchScopeParams() {
    var searchScopeParams = '';
    var associatedWithScope = $grid.backstopGrid('searchScope', 'associated_with');
    var tagScope = $grid.backstopGrid('searchScope', 'tags');
    var effectiveDateMinScope = $grid.backstopGrid('searchScope', 'effective_date_min');
    var effectiveDateMaxScope = $grid.backstopGrid('searchScope', 'effective_date_max');

    if (associatedWithScope) {
      searchScopeParams += '&search_scope[associated_with]=';
      searchScopeParams += associatedWithScope;
    }

    if (tagScope) {
      searchScopeParams += '&search_scope[tags]=';
      searchScopeParams += tagScope;
    }

    if (effectiveDateMinScope) {
      searchScopeParams += '&search_scope[effective_date_min]=';
      searchScopeParams += effectiveDateMinScope;
    }

    if (effectiveDateMaxScope) {
      searchScopeParams += '&search_scope[effective_date_max]=';
      searchScopeParams += effectiveDateMaxScope;
    }

    return searchScopeParams;
  }

  function getDateLimitParams() {
    var dateLimitParams = '';
    if (createdAtMin) {
      dateLimitParams += '&created_at_min=';
      dateLimitParams += createdAtMin;
    }
    if (createdAtMax) {
      dateLimitParams += '&created_at_max=';
      dateLimitParams += createdAtMax;
    }

    return dateLimitParams;
  }

  function getGridFilters() {
    var paramObj = $gridTable.jqGrid( 'getGridParam', 'postData' );

    if (!isNaN(docBlockId)) {
      paramObj.document_block_id = docBlockId;
    }

    if (0 !== investmentId) {
      paramObj.investment_id = investmentId;
    }

    return paramObj;
  }

  function addViewOnlyToRows(viewOnlyLinkEls) {
    var viewOnlyLinkEl;

    for (var i = 0; i < viewOnlyLinkEls.length; i++) {
      viewOnlyLinkEl = viewOnlyLinkEls[i];
      $(viewOnlyLinkEl).closest('tr').addClass('view_only_row');
    }

    viewOnlyRowEls = gridEl.querySelectorAll('.view_only_row');
  }

  function toggleViewOnlyStyles(option) {
    var viewOnlyRowEl;

    for (var i = 0; i < viewOnlyRowEls.length; i++) {
      viewOnlyRowEl = viewOnlyRowEls[i];

      if ( 'add' === option ) {
        viewOnlyRowEl.classList.add('show-disabled');
        toggleViewOnlyNotice(viewOnlyRowEl, 'add');
      } else if ( 'remove' === option ) {
        viewOnlyRowEl.classList.remove('show-disabled');
        toggleViewOnlyNotice(viewOnlyRowEl, 'remove');
      }
    }
  }

  function toggleViewOnlyNotice(rowEl, option) {
    var singleLinkEl = rowEl.querySelector('.single-download-links');
    var noticeEl = rowEl.querySelector('.view-only-notice');

    if ('add' === option) {
      // If notice is already inserted,
      // Do not insert another
      if (!noticeEl) {
        singleLinkEl.insertAdjacentHTML('afterend', '<div class="view-only-notice">Document is view only</div>');
      }
    } else if ('remove' === option) {
      // If notice exists, remove
      if (noticeEl) {
        noticeEl.remove();
      }
    }
  }

  function removeReadClass(ids) {
    ids.forEach(function(currentValue, index) {
      // You cannot select a row via an id that starts with a number
      // So target the hidden column holding the id, get parent, find .read-state
      var hiddenColumnIdEl = gridEl.querySelector('[title="' + currentValue + '"]');
      if (hiddenColumnIdEl) {
        var rowEl = hiddenColumnIdEl.parentElement;
        var readStateEl = rowEl.querySelector('.read-state');

        readStateEl.classList.remove('is-unread');
      }
    });
  }

  function hideMddHeaderCheck(){
    if ( hideMddHeader == "false" ){
      return
    }
    if ( selectedIdsArray.length === 0 ) {
      gridHeaderEl.classList.add('hide-header');
    } else {
      gridHeaderEl.classList.remove('hide-header');
    }
  }

  // Event Listeners --------------------------------------------------------
  // Execute when makeGrid is called
  insertMaxLimitInHeader();
  setDocBlocId();

  hideMddHeaderCheck();
  createModal();

  downloadBtnEl.addEventListener('click', function (event) {
    event.preventDefault();

    downloadMultipleDocuments = new Backstop.DownloadPoller( this,
      { attachable_ids: selectedIdsArray },
      function(response) {
        var stateResponse = JSON.parse(response.responseText).download;
        state = stateResponse.state;
        fileName = stateResponse.filename;
        if ( 2 === state ) {
          removeReadClass(selectedIdsArray);
          completeModalState(fileName);
          closeModalState();
        }
      },
      function(response) {
        var message = JSON.parse(response.responseText).download.messages;
        if ( 0 === message.indexOf('Maximum download is') ) {
          maxLimitPassedModalState();
        } else {
          errorModalState(message);
        }

        closeModalState();
      });

    downloadMultipleDocuments.start();

    defaultModalState();
    activateModalState();
  }, false);

  selectAllBtnEl.addEventListener('click', function (event) {
    event.preventDefault();

    toggleElementDisplay(selectAllBtnEl, 'remove', 'show-button');
    toggleElementDisplay(deselectAllBtnEl, 'add', 'show-button');
    toggleAllOfElementDisplay(singleDownloadLinkEls, 'add', 'hide-links');

    $.ajax({
      type: 'GET',
      url: selectAllJsonUrl,
      data: ($.param( getGridFilters() ) +
                      getSearchScopeParams() +
                      getDateLimitParams()),
      success: function(response) {
        selectedIdsArray = response;
        changeHeaderInfo();
        hideMddHeaderCheck();
        checkMaxLimit(selectedIdsArray.length);
      }
    });
  }, false);

  deselectAllBtnEl.addEventListener('click', function (event) {
    event.preventDefault();

    toggleElementDisplay(selectAllBtnEl, 'add', 'show-button');
    toggleElementDisplay(deselectAllBtnEl, 'remove', 'show-button');
    changeHeaderInfo();
    clearAllSelected();
    $gridTable.jqGrid('resetSelection');
    selectedIdsArray = [];
    hideMddHeaderCheck();
  }, false);

  $grid.bind( 'backstopgrid.loaded', function (data) {
    var highlightedOnPaginationEl = gridEl.querySelectorAll('.ui-state-highlight');
    shiftSelectionActive = false;
    $gridTable = $grid.backstopGrid('gridTable');
    gridFormEl = document.querySelector(gridAsId + '-form');
    $checkboxAllEl = $('#cb_' + attachablesGridData.gridId + '_grid');
    formButtonEls = gridFormEl.querySelectorAll('[type="submit"]');
    standardSelectionEl = gridFormEl.querySelector('.standard select');
    // Get elements after grid has been loaded
    singleDownloadLinkEls = gridEl.querySelectorAll('.single-download-links');
    viewOnlyLinkEls = gridEl.querySelectorAll('.view_only_link');
    addViewOnlyToRows(viewOnlyLinkEls);
    tableCBoxEls = gridEl.querySelectorAll('tr:not(.view_only_row) td .cbox');
    cBoxEls = gridEl.querySelectorAll('.cbox');
    checkboxLabels(cBoxEls);

    // Wait until labels are created
    customCheckboxEls = gridEl.querySelectorAll('tr:not(.view_only_row) .custom-checkbox');
    $('a.lightbox').on('click', function () {
      $(this).closest('span').prev().removeClass('is-unread');
    });
    $('a.lightbox').fancybox();
    changeTitleCellAttribute();
    changeSelectAllRecord();
    bindFilterButtons();
    bindStandardSelectEl();

    //view only docs are marked as read when clicked
    $('.view_only_link').on('click', function () {
      $(this).closest('span').prev().removeClass('is-unread');
    });

    // If there is more than one highlighted row, hide the view/download links
    if ( 2 <= highlightedOnPaginationEl.length ) {
      toggleAllOfElementDisplay(singleDownloadLinkEls, 'add', 'hide-links');
    } else {
      toggleAllOfElementDisplay(singleDownloadLinkEls, 'remove', 'hide-links');
    }

    $checkboxAllEl.bind('click', function() {
      var addAllToList = this.checked;

      toggleCheckboxes(tableCBoxEls, addAllToList);
      changeHeaderInfo();
      hideMddHeaderCheck();
      checkMaxLimit(selectedIdsArray.length);

      if ( selectedIdsArray.length === totalRecordsFromGrid ) {
        toggleElementDisplay(selectAllBtnEl, 'remove', 'show-button');
        toggleElementDisplay(deselectAllBtnEl, 'add', 'show-button');
      }
    });
  });

  var multiDocSettings = {
    multiselect: true,
    gridComplete: function() {
      // When you paginate, if there is a selection loaded in, show all checkboxes
      gridRows = gridEl.querySelectorAll('.ui-row-ltr');
      selectRowsInArray();

      if ( selectionExists ) {
        // Have to set a timeout here becuase the labels HAVE to be created first
        setTimeout(function() {
          toggleAllOfElementDisplay(customCheckboxEls, 'add', 'show-checkbox');
          // Check if view only rows exists because on first load,
          // They won't exist, but on pagination they will
          if (viewOnlyRowEls) {
            toggleViewOnlyStyles('add');
          }
        }, 5);
        toggleElementDisplay(downloadBtnEl, 'add', 'show-button');
      } else {
        toggleElementDisplay(downloadBtnEl, 'remove', 'show-button');

        if (viewOnlyRowEls) {
          toggleViewOnlyStyles('remove');
        }
      }
      if ( selectedIdsArray ) {
        if ( 0 < selectedIdsArray.length ) {
          toggleElementDisplay(headerInfoEl, 'add', 'show-info');
        } else {
          toggleElementDisplay(headerInfoEl, 'remove', 'show-info');
        }
      }
      toggleElementDisplay(selectAllBtnEl, 'remove', 'show-button');
    },
    onSelectAll: function(aRowids, status) {
      // On clicking the select all checkbox, toggle the show state for checkboxes, buttons, and info
      if ( status ) {
        toggleAllOfElementDisplay(customCheckboxEls, 'add', 'show-checkbox');
        toggleElementDisplay(downloadBtnEl, 'add', 'show-button');
        toggleElementDisplay(headerInfoEl, 'add', 'show-info');
        toggleAllOfElementDisplay(singleDownloadLinkEls, 'add', 'hide-links');
        toggleViewOnlyStyles('add');

        if ( attachablesGridData.pgbuttons === undefined || attachablesGridData.pgbuttons ) {
          toggleElementDisplay(selectAllBtnEl, 'add', 'show-button');
        }
      }
      if ( !status ) {
        toggleAllOfElementDisplay(customCheckboxEls, 'remove', 'show-checkbox');
        toggleElementDisplay(downloadBtnEl, 'remove', 'show-button');
        toggleElementDisplay(headerInfoEl, 'remove', 'show-info');
        toggleAllOfElementDisplay(singleDownloadLinkEls, 'remove', 'hide-links');
        toggleElementDisplay(selectAllBtnEl, 'remove', 'show-button');
        toggleElementDisplay(deselectAllBtnEl, 'remove', 'show-button');
        toggleViewOnlyStyles('remove');
      }
    },
    beforeSelectRow: function (rowid, e) { // Add shift select ability
      var rows = this.rows;
      var startId = $gridTable.jqGrid('getGridParam', 'selrow'); // Get id of the previous selected row
      var rowidIndex;
      var $selectedRow = $('#' + rowid);

      if ($selectedRow.hasClass('view_only_row')) {
        return false;
      }

      if ( e.metaKey || e.ctrlKey ) {
        cmdSelectionActive = true;
      }

      // If a shift selection is made, then a user single clicks, remove previous selection
      if ( shiftSelectionActive && !e.shiftKey && !e.ctrlKey && !e.metaKey ) {
        shiftSelectionActive = false;
        cmdSelectionActive = false;
        iStart = undefined;

        beforeSelectCheckboxes();
      }

      // If there is a previous selected row and the shift key is pressed
      if ( startId && e.shiftKey ) {

        if ( !cmdSelectionActive ) {
          beforeSelectCheckboxes();
        }

        // If there was already a selection, keep the starting point from previous selection
        if ( !shiftSelectionActive || cmdSelectionActive && ( !e.ctrlKey || !e.metaKey ) ) {
          startRow = rows.namedItem(startId);
        }

        endRow = rows.namedItem(rowid);

        if (startRow && endRow) {
          // Get min and max from the indexes of the previous selected and the currect selected rows
          iStart = startRow.rowIndex;
          iEnd = endRow.rowIndex;
          iStart = Math.min(startRow.rowIndex, endRow.rowIndex);
          rowidIndex = endRow.rowIndex;
          iEnd = Math.max(startRow.rowIndex, rowidIndex);

          for (var i = iStart; i <= iEnd; i++) {
            // If row isn't view only
            if (!$(rows[i]).hasClass('view_only_row')) {
              // The row with rowid will be selected by jqGrid, so:
              if (i != rowidIndex) {
                var index = selectedIdsArray.indexOf(rows[i].id);

                if ( -1 == index ) {
                  $gridTable.jqGrid('setSelection', rows[i].id, false);
                  selectedIdsArray.push(rows[i].id);
                }
              }
            }
          }
        }

        shiftSelectionActive = true;

      }
      // Needs to return true for final selection to occur
      return true;
    },
    onSelectRow: function(attachableId, isSelected) {
      var indexOfSelected = selectedIdsArray.indexOf(attachableId);

      // Update highlightedEls as rows are selected
      highlightedEls = gridEl.querySelectorAll('.ui-state-highlight');

      // If not in array, add to array
      if ( isSelected && ( -1 === indexOfSelected ) ) {
        selectedIdsArray.push(attachableId);
      } else if ( -1 < indexOfSelected ) {
        selectedIdsArray.splice(indexOfSelected, 1);
      }

      // If there is at least one highlighted row, show all checkboxes, show download button, show info
      if ( highlightedEls.length ) {
        toggleViewOnlyStyles('add');
        toggleAllOfElementDisplay(customCheckboxEls, 'add', 'show-checkbox');
        toggleElementDisplay(downloadBtnEl, 'add', 'show-button');
        toggleElementDisplay(headerInfoEl, 'add', 'show-info');
      }
      // If there is more than one highlighted row, hide the view/download links
      if ( 2 <= highlightedEls.length ) {
        toggleAllOfElementDisplay(singleDownloadLinkEls, 'add', 'hide-links');
      } else {
        toggleAllOfElementDisplay(singleDownloadLinkEls, 'remove', 'hide-links');
      }
      // If there are no highlighted rows, hide all checkboxes, hide download button
      if ( !highlightedEls.length ) {
        toggleViewOnlyStyles('remove');
        toggleAllOfElementDisplay(customCheckboxEls, 'remove', 'show-checkbox');
        toggleElementDisplay(downloadBtnEl, 'remove', 'show-button');
        toggleElementDisplay(headerInfoEl, 'remove', 'show-info');
      }

      changeHeaderInfo();
      hideMddHeaderCheck();
      toggleElementDisplay(selectAllBtnEl, 'remove', 'show-button');
      toggleElementDisplay(deselectAllBtnEl, 'remove', 'show-button');
      checkMaxLimit(selectedIdsArray.length);
    },
    beforeSearchAction: {
      beforeSearch: function () {
        selectedIdsArray = [];
      }
    }
  };

  var singleDocSettings = {
    multiselect: false,
  };

  // Define keys if specified
  if ( attachablesGridData.caption ) {
    multiDocSettings.caption = attachablesGridData.caption;
    singleDocSettings.caption = attachablesGridData.caption;
  }

  if ( attachablesGridData.sortOn ) {
    multiDocSettings.sortname = attachablesGridData.sortOn;
    singleDocSettings.sortname = attachablesGridData.sortOn;
  }

  if ( attachablesGridData.sortOrder ) {
    multiDocSettings.sortorder = attachablesGridData.sortOrder;
    singleDocSettings.sortorder = attachablesGridData.sortOrder;
  }

  if ( attachablesGridData.dateSearchOn ) {
    multiDocSettings.date_search = attachablesGridData.dateSearchOn;
    singleDocSettings.date_search = attachablesGridData.dateSearchOn;
  }

  if ( attachablesGridData.rowList ) {
    multiDocSettings.rowList = attachablesGridData.rowList;
    singleDocSettings.rowList = attachablesGridData.rowList;
  }

  if ( attachablesGridData.rowNum ) {
    multiDocSettings.rowNum = attachablesGridData.rowNum;
    singleDocSettings.rowNum = attachablesGridData.rowNum;
  }

  if ( attachablesGridData.advanced_search ) {
    multiDocSettings.advanced_search = attachablesGridData.advanced_search;
    singleDocSettings.advanced_search = attachablesGridData.advanced_search;
  }

  if ( attachablesGridData.hasOwnProperty('viewrecords') ) {
    multiDocSettings.viewrecords = attachablesGridData.viewrecords;
    singleDocSettings.viewrecords = attachablesGridData.viewrecords;
  }

  if ( attachablesGridData.hasOwnProperty('pgbuttons') ) {
    multiDocSettings.pgbuttons = attachablesGridData.pgbuttons;
    singleDocSettings.pgbuttons = attachablesGridData.pgbuttons;
  }

  if ( attachablesGridData.hasOwnProperty('pgtext') && !attachablesGridData.pgtext ) {
    multiDocSettings.pgtext = attachablesGridData.pgtext;
    singleDocSettings.pgtext = attachablesGridData.pgtext;
  }

  if ( attachablesGridData.filter ) {
    multiDocSettings.filter = attachablesGridData.filter;
    singleDocSettings.filter = attachablesGridData.filter;
  }

  if ( attachablesGridData.columns ) {
    multiDocSettings.columns = attachablesGridData.columns;
    singleDocSettings.columns = attachablesGridData.columns;
  } else {
    alert('There was a problem defining the filter. Please contact support.');
  }

  if ( 1 === downloadMaxLimitNum ) {
    gridHeaderEl.classList.add('hide-header');
    gridEl.classList.remove('multiGrid');
    $grid.backstopGrid(singleDocSettings);
  } else {
    $grid.backstopGrid(multiDocSettings);
  }
};
;(function ($) {
  $('.disable-right-click').bind('contextmenu', function() { return false; });
}(jQuery));
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 *
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Dear future developers, we have decided to 'own' this code and upgrade it to support JQuery 2.3x
 * (for security reasons).
 * We have done this because we are Bwakwak! (chicken noise). Upgrading would involve some serious design
 * regression risk, as the commands to style have changed, and we use those a bunch, and lots of front-end
 * client work relies on that. High-risk, very low payoff? Especially because we hope to move to React or
 * another modern javascript framework in the "near future."
 *
 * Sincerely, Jake Scruggs and Eric Tenza June 3, 2019
 */
;
(function($) {
    var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right,
        selectedIndex = 0,
        selectedOpts = {},
        selectedArray = [],
        currentIndex = 0,
        currentOpts = {},
        currentArray = [],
        ajaxLoader = null,
        imgPreloader = new Image(),
        imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,
        swfRegExp = /[^\.]\.(swf)\s*$/i,
        loadingTimer, loadingFrame = 1,
        titleHeight = 0,
        titleStr = '',
        start_pos, final_pos, busy = false,
        fx = $.extend($('<div/>')[0], {
            prop: 0
        }),
        isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
        /*
         * Private methods
         */
        _abort = function() {
            loading.hide();
            imgPreloader.onerror = imgPreloader.onload = null;
            if (ajaxLoader) {
                ajaxLoader.abort();
            }
            tmp.empty();
        },
        _error = function() {
            if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) {
                loading.hide();
                busy = false;
                return;
            }
            selectedOpts.titleShow = false;
            selectedOpts.width = 'auto';
            selectedOpts.height = 'auto';
            tmp.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');
            _process_inline();
        },
        _start = function() {
            var obj = selectedArray[selectedIndex],
                href,
                type,
                title,
                str,
                emb,
                ret;
            _abort();
            selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
            ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts);
            if (ret === false) {
                busy = false;
                return;
            } else if (typeof ret == 'object') {
                selectedOpts = $.extend(selectedOpts, ret);
            }
            title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || '';
            if (obj.nodeName && !selectedOpts.orig) {
                selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
            }
            if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) {
                title = selectedOpts.orig.attr('alt');
            }
            href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null;
            if ((/^(?:javascript)/i).test(href) || href == '#') {
                href = null;
            }
            if (selectedOpts.type) {
                type = selectedOpts.type;
                if (!href) {
                    href = selectedOpts.content;
                }
            } else if (selectedOpts.content) {
                type = 'html';
            } else if (href) {
                if (href.match(imgRegExp)) {
                    type = 'image';
                } else if (href.match(swfRegExp)) {
                    type = 'swf';
                } else if ($(obj).hasClass("iframe")) {
                    type = 'iframe';
                } else if (href.indexOf("#") === 0) {
                    type = 'inline';
                } else {
                    type = 'ajax';
                }
            }
            if (!type) {
                _error();
                return;
            }
            if (type == 'inline') {
                obj = href.substr(href.indexOf("#"));
                type = $(obj).length > 0 ? 'inline' : 'ajax';
            }
            selectedOpts.type = type;
            selectedOpts.href = href;
            selectedOpts.title = title;
            if (selectedOpts.autoDimensions) {
                if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') {
                    selectedOpts.width = 'auto';
                    selectedOpts.height = 'auto';
                } else {
                    selectedOpts.autoDimensions = false;
                }
            }
            if (selectedOpts.modal) {
                selectedOpts.overlayShow = true;
                selectedOpts.hideOnOverlayClick = false;
                selectedOpts.hideOnContentClick = false;
                selectedOpts.enableEscapeButton = false;
                selectedOpts.showCloseButton = false;
            }
            selectedOpts.padding = parseInt(selectedOpts.padding, 10);
            selectedOpts.margin = parseInt(selectedOpts.margin, 10);
            tmp.css('padding', (selectedOpts.padding + selectedOpts.margin));
            $('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
                $(this).replaceWith(content.children());
            });
            switch (type) {
                case 'html':
                    tmp.html(selectedOpts.content);
                    _process_inline();
                    break;
                case 'inline':
                    if ($(obj).parent().is('#fancybox-content') === true) {
                        busy = false;
                        return;
                    }
                    $('<div class="fancybox-inline-tmp" />')
                        .hide()
                        .insertBefore($(obj))
                        .bind('fancybox-cleanup', function() {
                            $(this).replaceWith(content.children());
                        }).bind('fancybox-cancel', function() {
                            $(this).replaceWith(tmp.children());
                        });
                    $(obj).appendTo(tmp);
                    _process_inline();
                    break;
                case 'image':
                    busy = false;
                    $.fancybox.showActivity();
                    imgPreloader = new Image();
                    imgPreloader.onerror = function() {
                        _error();
                    };
                    imgPreloader.onload = function() {
                        busy = true;
                        imgPreloader.onerror = imgPreloader.onload = null;
                        _process_image();
                    };
                    imgPreloader.src = href;
                    break;
                case 'swf':
                    selectedOpts.scrolling = 'no';
                    str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
                    emb = '';
                    $.each(selectedOpts.swf, function(name, val) {
                        str += '<param name="' + name + '" value="' + val + '"></param>';
                        emb += ' ' + name + '="' + val + '"';
                    });
                    str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';
                    tmp.html(str);
                    _process_inline();
                    break;
                case 'ajax':
                    busy = false;
                    $.fancybox.showActivity();
                    selectedOpts.ajax.win = selectedOpts.ajax.success;
                    ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, {
                        url: href,
                        data: selectedOpts.ajax.data || {},
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            if (XMLHttpRequest.status > 0) {
                                _error();
                            }
                        },
                        success: function(data, textStatus, XMLHttpRequest) {
                            var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader;
                            if (o.status == 200) {
                                if (typeof selectedOpts.ajax.win == 'function') {
                                    ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest);
                                    if (ret === false) {
                                        loading.hide();
                                        return;
                                    } else if (typeof ret == 'string' || typeof ret == 'object') {
                                        data = ret;
                                    }
                                }
                                tmp.html(data);
                                _process_inline();
                            }
                        }
                    }));
                    break;
                case 'iframe':
                    _show();
                    break;
            }
        },
        _process_inline = function() {
            var
                w = selectedOpts.width,
                h = selectedOpts.height;
            if (w.toString().indexOf('%') > -1) {
                w = parseInt(($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px';
            } else {
                w = w == 'auto' ? 'auto' : w + 'px';
            }
            if (h.toString().indexOf('%') > -1) {
                h = parseInt(($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px';
            } else {
                h = h == 'auto' ? 'auto' : h + 'px';
            }
            tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>');
            selectedOpts.width = tmp.width();
            selectedOpts.height = tmp.height();
            _show();
        },
        _process_image = function() {
            selectedOpts.width = imgPreloader.width;
            selectedOpts.height = imgPreloader.height;
            $("<img />").attr({
                'id': 'fancybox-img',
                'src': imgPreloader.src,
                'alt': selectedOpts.title
            }).appendTo(tmp);
            _show();
        },
        _show = function() {
            var pos, equal;
            loading.hide();
            if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
                $('.fancybox-inline-tmp').trigger('fancybox-cancel');
                busy = false;
                return;
            }
            busy = true;
            $(content.add(overlay)).unbind();
            $(window).unbind("resize.fb scroll.fb");
            $(document).unbind('keydown.fb');
            if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') {
                wrap.css('height', wrap.height());
            }
            currentArray = selectedArray;
            currentIndex = selectedIndex;
            currentOpts = selectedOpts;
            if (currentOpts.overlayShow) {
                overlay.css({
                    'background-color': currentOpts.overlayColor,
                    'opacity': currentOpts.overlayOpacity,
                    'cursor': currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
                    'height': $(document).height()
                });
                if (!overlay.is(':visible')) {
                    if (isIE6) {
                        $('select:not(#fancybox-tmp select)').filter(function() {
                            return this.style.visibility !== 'hidden';
                        }).css({
                            'visibility': 'hidden'
                        }).one('fancybox-cleanup', function() {
                            this.style.visibility = 'inherit';
                        });
                    }
                    overlay.show();
                }
            } else {
                overlay.hide();
            }
            final_pos = _get_zoom_to();
            _process_title();
            if (wrap.is(":visible")) {
                $(close.add(nav_left).add(nav_right)).hide();
                pos = wrap.position(),
                    start_pos = {
                        top: pos.top,
                        left: pos.left,
                        width: wrap.width(),
                        height: wrap.height()
                    };
                equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);
                content.fadeTo(currentOpts.changeFade, 0.3, function() {
                    var finish_resizing = function() {
                        content.html(tmp.contents()).fadeTo(currentOpts.changeFade, 1, _finish);
                    };
                    $('.fancybox-inline-tmp').trigger('fancybox-change');
                    content
                        .empty()
                        .removeAttr('filter')
                        .css({
                            'border-width': currentOpts.padding,
                            'width': final_pos.width - currentOpts.padding * 2,
                            'height': selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
                        });
                    if (equal) {
                        finish_resizing();
                    } else {
                        fx.prop = 0;
                        $(fx).animate({
                            prop: 1
                        }, {
                            duration: currentOpts.changeSpeed,
                            easing: currentOpts.easingChange,
                            step: _draw,
                            complete: finish_resizing
                        });
                    }
                });
                return;
            }
            wrap.removeAttr("style");
            content.css('border-width', currentOpts.padding);
            if (currentOpts.transitionIn == 'elastic') {
                start_pos = _get_zoom_from();
                content.html(tmp.contents());
                wrap.show();
                if (currentOpts.opacity) {
                    final_pos.opacity = 0;
                }
                fx.prop = 0;
                $(fx).animate({
                    prop: 1
                }, {
                    duration: currentOpts.speedIn,
                    easing: currentOpts.easingIn,
                    step: _draw,
                    complete: _finish
                });
                return;
            }
            if (currentOpts.titlePosition == 'inside' && titleHeight > 0) {
                title.show();
            }
            content
                .css({
                    'width': final_pos.width - currentOpts.padding * 2,
                    'height': selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
                })
                .html(tmp.contents());
            wrap
                .css(final_pos)
                .fadeIn(currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish);
        },
        _format_title = function(title) {
            if (title && title.length) {
                if (currentOpts.titlePosition == 'float') {
                    return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>';
                }
                return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>';
            }
            return false;
        },
        _process_title = function() {
            titleStr = currentOpts.title || '';
            titleHeight = 0;
            title
                .empty()
                .removeAttr('style')
                .removeClass();
            if (currentOpts.titleShow === false) {
                title.hide();
                return;
            }
            titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr);
            if (!titleStr || titleStr === '') {
                title.hide();
                return;
            }
            title
                .addClass('fancybox-title-' + currentOpts.titlePosition)
                .html(titleStr)
                .appendTo('body')
                .show();
            switch (currentOpts.titlePosition) {
                case 'inside':
                    title
                        .css({
                            'width': final_pos.width - (currentOpts.padding * 2),
                            'marginLeft': currentOpts.padding,
                            'marginRight': currentOpts.padding
                        });
                    titleHeight = title.outerHeight(true);
                    title.appendTo(outer);
                    final_pos.height += titleHeight;
                    break;
                case 'over':
                    title
                        .css({
                            'marginLeft': currentOpts.padding,
                            'width': final_pos.width - (currentOpts.padding * 2),
                            'bottom': currentOpts.padding
                        })
                        .appendTo(outer);
                    break;
                case 'float':
                    title
                        .css('left', parseInt((title.width() - final_pos.width - 40) / 2, 10) * -1)
                        .appendTo(wrap);
                    break;
                default:
                    title
                        .css({
                            'width': final_pos.width - (currentOpts.padding * 2),
                            'paddingLeft': currentOpts.padding,
                            'paddingRight': currentOpts.padding
                        })
                        .appendTo(wrap);
                    break;
            }
            title.hide();
        },
        _set_navigation = function() {
            if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) {
                $(document).bind('keydown.fb', function(e) {
                    if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
                        e.preventDefault();
                        $.fancybox.close();
                    } else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
                        e.preventDefault();
                        $.fancybox[e.keyCode == 37 ? 'prev' : 'next']();
                    }
                });
            }
            if (!currentOpts.showNavArrows) {
                nav_left.hide();
                nav_right.hide();
                return;
            }
            if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
                nav_left.show();
            }
            if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length - 1)) {
                nav_right.show();
            }
        },
        _finish = function() {
            if (!$.support.opacity) {
                $(content.get(0).style).removeAttr('filter');
                $(wrap.get(0).style).removeAttr('filter');
            }
            if (selectedOpts.autoDimensions) {
                content.css('height', 'auto');
            }
            wrap.css('height', 'auto');
            if (titleStr && titleStr.length) {
                title.show();
            }
            if (currentOpts.showCloseButton) {
                close.show();
            }
            _set_navigation();
            if (currentOpts.hideOnContentClick) {
                content.bind('click', $.fancybox.close);
            }
            if (currentOpts.hideOnOverlayClick) {
                overlay.bind('click', $.fancybox.close);
            }
            $(window).bind("resize.fb", $.fancybox.resize);
            if (currentOpts.centerOnScroll) {
                $(window).bind("scroll.fb", $.fancybox.center);
            }
            if (currentOpts.type == 'iframe') {
                $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
            }
            wrap.show();
            busy = false;
            $.fancybox.center();
            currentOpts.onComplete(currentArray, currentIndex, currentOpts);
            _preload_images();
        },
        _preload_images = function() {
            var href,
                objNext;
            if ((currentArray.length - 1) > currentIndex) {
                href = currentArray[currentIndex + 1].href;
                if (typeof href !== 'undefined' && href.match(imgRegExp)) {
                    objNext = new Image();
                    objNext.src = href;
                }
            }
            if (currentIndex > 0) {
                href = currentArray[currentIndex - 1].href;
                if (typeof href !== 'undefined' && href.match(imgRegExp)) {
                    objNext = new Image();
                    objNext.src = href;
                }
            }
        },
        _draw = function(pos) {
            var dim = {
                width: parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10),
                height: parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10),
                top: parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10),
                left: parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10)
            };
            if (typeof final_pos.opacity !== 'undefined') {
                dim.opacity = pos < 0.5 ? 0.5 : pos;
            }
            wrap.css(dim);
            content.css({
                'width': dim.width - currentOpts.padding * 2,
                'height': dim.height - (titleHeight * pos) - currentOpts.padding * 2
            });
        },
        _get_viewport = function() {
            return [
                $(window).width() - (currentOpts.margin * 2),
                $(window).height() - (currentOpts.margin * 2),
                $(document).scrollLeft() + currentOpts.margin,
                $(document).scrollTop() + currentOpts.margin
            ];
        },
        _get_zoom_to = function() {
            var view = _get_viewport(),
                to = {},
                resize = currentOpts.autoScale,
                double_padding = currentOpts.padding * 2,
                ratio;
            if (currentOpts.width.toString().indexOf('%') > -1) {
                to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10);
            } else {
                to.width = currentOpts.width + double_padding;
            }
            if (currentOpts.height.toString().indexOf('%') > -1) {
                to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10);
            } else {
                to.height = currentOpts.height + double_padding;
            }
            if (resize && (to.width > view[0] || to.height > view[1])) {
                if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
                    ratio = (currentOpts.width) / (currentOpts.height);
                    if ((to.width) > view[0]) {
                        to.width = view[0];
                        to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10);
                    }
                    if ((to.height) > view[1]) {
                        to.height = view[1];
                        to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10);
                    }
                } else {
                    to.width = Math.min(to.width, view[0]);
                    to.height = Math.min(to.height, view[1]);
                }
            }
            to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10);
            to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10);
            return to;
        },
        _get_obj_pos = function(obj) {
            var pos = obj.offset();
            pos.top += parseInt(obj.css('paddingTop'), 10) || 0;
            pos.left += parseInt(obj.css('paddingLeft'), 10) || 0;
            pos.top += parseInt(obj.css('border-top-width'), 10) || 0;
            pos.left += parseInt(obj.css('border-left-width'), 10) || 0;
            pos.width = obj.width();
            pos.height = obj.height();
            return pos;
        },
        _get_zoom_from = function() {
            var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
                from = {},
                pos,
                view;
            if (orig && orig.length) {
                pos = _get_obj_pos(orig);
                from = {
                    width: pos.width + (currentOpts.padding * 2),
                    height: pos.height + (currentOpts.padding * 2),
                    top: pos.top - currentOpts.padding - 20,
                    left: pos.left - currentOpts.padding - 20
                };
            } else {
                view = _get_viewport();
                from = {
                    width: currentOpts.padding * 2,
                    height: currentOpts.padding * 2,
                    top: parseInt(view[3] + view[1] * 0.5, 10),
                    left: parseInt(view[2] + view[0] * 0.5, 10)
                };
            }
            return from;
        },
        _animate_loading = function() {
            if (!loading.is(':visible')) {
                clearInterval(loadingTimer);
                return;
            }
            $('div', loading).css('top', (loadingFrame * -40) + 'px');
            loadingFrame = (loadingFrame + 1) % 12;
        };
    /*
     * Public methods
     */
    $.fn.fancybox = function(options) {
        if (!$(this).length) {
            return this;
        }
        $(this)
            .data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
            .unbind('click.fb')
            .bind('click.fb', function(e) {
                e.preventDefault();
                if (busy) {
                    return;
                }
                busy = true;
                $(this).blur();
                selectedArray = [];
                selectedIndex = 0;
                var rel = $(this).attr('rel') || '';
                if (!rel || rel == '' || rel === 'nofollow') {
                    selectedArray.push(this);
                } else {
                    selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
                    selectedIndex = selectedArray.index(this);
                }
                _start();
                return;
            });
        return this;
    };
    $.fancybox = function(obj) {
        var opts;
        if (busy) {
            return;
        }
        busy = true;
        opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};
        selectedArray = [];
        selectedIndex = parseInt(opts.index, 10) || 0;
        if ($.isArray(obj)) {
            for (var i = 0, j = obj.length; i < j; i++) {
                if (typeof obj[i] == 'object') {
                    $(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
                } else {
                    obj[i] = $({}).data('fancybox', $.extend({
                        content: obj[i]
                    }, opts));
                }
            }
            selectedArray = jQuery.merge(selectedArray, obj);
        } else {
            if (typeof obj == 'object') {
                $(obj).data('fancybox', $.extend({}, opts, obj));
            } else {
                obj = $({}).data('fancybox', $.extend({
                    content: obj
                }, opts));
            }
            selectedArray.push(obj);
        }
        if (selectedIndex > selectedArray.length || selectedIndex < 0) {
            selectedIndex = 0;
        }
        _start();
    };
    $.fancybox.showActivity = function() {
        clearInterval(loadingTimer);
        loading.show();
        loadingTimer = setInterval(_animate_loading, 66);
    };
    $.fancybox.hideActivity = function() {
        loading.hide();
    };
    $.fancybox.next = function() {
        return $.fancybox.pos(currentIndex + 1);
    };
    $.fancybox.prev = function() {
        return $.fancybox.pos(currentIndex - 1);
    };
    $.fancybox.pos = function(pos) {
        if (busy) {
            return;
        }
        pos = parseInt(pos);
        selectedArray = currentArray;
        if (pos > -1 && pos < currentArray.length) {
            selectedIndex = pos;
            _start();
        } else if (currentOpts.cyclic && currentArray.length > 1) {
            selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1;
            _start();
        }
        return;
    };
    $.fancybox.cancel = function() {
        if (busy) {
            return;
        }
        busy = true;
        $('.fancybox-inline-tmp').trigger('fancybox-cancel');
        _abort();
        selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
        busy = false;
    };
    // Note: within an iframe use - parent.$.fancybox.close();
    $.fancybox.close = function() {
        if (busy || wrap.is(':hidden')) {
            return;
        }
        busy = true;
        if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
            busy = false;
            return;
        }
        _abort();
        $(close.add(nav_left).add(nav_right)).hide();
        $(content.add(overlay)).unbind();
        $(window).unbind("resize.fb scroll.fb");
        $(document).unbind('keydown.fb');
        content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank');
        if (currentOpts.titlePosition !== 'inside') {
            title.empty();
        }
        wrap.stop();

        function _cleanup() {
            overlay.fadeOut('fast');
            title.empty().hide();
            wrap.hide();
            $('.fancybox-inline-tmp').trigger('fancybox-cleanup');
            content.empty();
            currentOpts.onClosed(currentArray, currentIndex, currentOpts);
            currentArray = selectedOpts = [];
            currentIndex = selectedIndex = 0;
            currentOpts = selectedOpts = {};
            busy = false;
        }
        if (currentOpts.transitionOut == 'elastic') {
            start_pos = _get_zoom_from();
            var pos = wrap.position();
            final_pos = {
                top: pos.top,
                left: pos.left,
                width: wrap.width(),
                height: wrap.height()
            };
            if (currentOpts.opacity) {
                final_pos.opacity = 1;
            }
            title.empty().hide();
            fx.prop = 1;
            $(fx).animate({
                prop: 0
            }, {
                duration: currentOpts.speedOut,
                easing: currentOpts.easingOut,
                step: _draw,
                complete: _cleanup
            });
        } else {
            wrap.fadeOut(currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
        }
    };
    $.fancybox.resize = function() {
        if (overlay.is(':visible')) {
            overlay.css('height', $(document).height());
        }
        $.fancybox.center(true);
    };
    $.fancybox.center = function() {
        var view, align;
        if (busy) {
            return;
        }
        align = arguments[0] === true ? 1 : 0;
        view = _get_viewport();
        if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) {
            return;
        }
        wrap
            .stop()
            .animate({
                'top': parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)),
                'left': parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding))
            }, typeof arguments[0] == 'number' ? arguments[0] : 200);
    };
    $.fancybox.init = function() {
        if ($("#fancybox-wrap").length) {
            return;
        }
        $('body').append(
            tmp = $('<div id="fancybox-tmp"></div>'),
            loading = $('<div id="fancybox-loading"><div></div></div>'),
            overlay = $('<div id="fancybox-overlay"></div>'),
            wrap = $('<div id="fancybox-wrap"></div>')
        );
        outer = $('<div id="fancybox-outer"></div>')
            .append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>')
            .appendTo(wrap);
        outer.append(
            content = $('<div id="fancybox-content"></div>'),
            close = $('<a id="fancybox-close"></a>'),
            title = $('<div id="fancybox-title"></div>'),
            nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
            nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
        );
        close.click($.fancybox.close);
        loading.click($.fancybox.cancel);
        nav_left.click(function(e) {
            e.preventDefault();
            $.fancybox.prev();
        });
        nav_right.click(function(e) {
            e.preventDefault();
            $.fancybox.next();
        });
        if ($.fn.mousewheel) {
            wrap.bind('mousewheel.fb', function(e, delta) {
                if (busy) {
                    e.preventDefault();
                } else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) {
                    e.preventDefault();
                    $.fancybox[delta > 0 ? 'prev' : 'next']();
                }
            });
        }
        if (!$.support.opacity) {
            wrap.addClass('fancybox-ie');
        }
        if (isIE6) {
            loading.addClass('fancybox-ie6');
            wrap.addClass('fancybox-ie6');
            $('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank') + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer);
        }
    };
    $.fn.fancybox.defaults = {
        padding: 10,
        margin: 40,
        opacity: false,
        modal: false,
        cyclic: false,
        scrolling: 'auto', // 'auto', 'yes' or 'no'
        width: 560,
        height: 340,
        autoScale: true,
        autoDimensions: true,
        centerOnScroll: false,
        ajax: {},
        swf: {
            wmode: 'transparent'
        },
        hideOnOverlayClick: true,
        hideOnContentClick: false,
        overlayShow: true,
        overlayOpacity: 0.7,
        overlayColor: '#777',
        titleShow: true,
        titlePosition: 'float', // 'float', 'outside', 'inside' or 'over'
        titleFormat: null,
        titleFromAlt: false,
        transitionIn: 'fade', // 'elastic', 'fade' or 'none'
        transitionOut: 'fade', // 'elastic', 'fade' or 'none'
        speedIn: 300,
        speedOut: 300,
        changeSpeed: 300,
        changeFade: 'fast',
        easingIn: 'swing',
        easingOut: 'swing',
        showCloseButton: true,
        showNavArrows: true,
        enableEscapeButton: true,
        enableKeyboardNav: true,
        onStart: function() {},
        onCancel: function() {},
        onComplete: function() {},
        onCleanup: function() {},
        onClosed: function() {},
        onError: function() {}
    };
    $(document).ready(function() {
        $.fancybox.init();
    });
})(jQuery);
/*! powerbi-client v2.16.2 | (c) 2016 Microsoft Corporation MIT */
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["powerbi-client"] = factory();
	else
		root["powerbi-client"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/powerbi-client.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/http-post-message/dist/httpPostMessage.js":
/*!****************************************************************!*\
  !*** ./node_modules/http-post-message/dist/httpPostMessage.js ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*! http-post-message v0.2.3 | (c) 2016 Microsoft Corporation MIT */
(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	"use strict";
	var HttpPostMessage = (function () {
	    function HttpPostMessage(windowPostMessageProxy, defaultHeaders, defaultTargetWindow) {
	        if (defaultHeaders === void 0) { defaultHeaders = {}; }
	        this.defaultHeaders = defaultHeaders;
	        this.defaultTargetWindow = defaultTargetWindow;
	        this.windowPostMessageProxy = windowPostMessageProxy;
	    }
	    // TODO: See if it's possible to share tracking properties interface?
	    // The responsibility of knowing how to configure windowPostMessageProxy for http should
	    // live in this http class, but the configuration would need ITrackingProperties
	    // interface which lives in WindowPostMessageProxy. Use <any> type as workaround
	    HttpPostMessage.addTrackingProperties = function (message, trackingProperties) {
	        message.headers = message.headers || {};
	        if (trackingProperties && trackingProperties.id) {
	            message.headers.id = trackingProperties.id;
	        }
	        return message;
	    };
	    HttpPostMessage.getTrackingProperties = function (message) {
	        return {
	            id: message.headers && message.headers.id
	        };
	    };
	    HttpPostMessage.isErrorMessage = function (message) {
	        if (typeof (message && message.statusCode) !== 'number') {
	            return false;
	        }
	        return !(200 <= message.statusCode && message.statusCode < 300);
	    };
	    HttpPostMessage.prototype.get = function (url, headers, targetWindow) {
	        if (headers === void 0) { headers = {}; }
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        return this.send({
	            method: "GET",
	            url: url,
	            headers: headers
	        }, targetWindow);
	    };
	    HttpPostMessage.prototype.post = function (url, body, headers, targetWindow) {
	        if (headers === void 0) { headers = {}; }
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        return this.send({
	            method: "POST",
	            url: url,
	            headers: headers,
	            body: body
	        }, targetWindow);
	    };
	    HttpPostMessage.prototype.put = function (url, body, headers, targetWindow) {
	        if (headers === void 0) { headers = {}; }
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        return this.send({
	            method: "PUT",
	            url: url,
	            headers: headers,
	            body: body
	        }, targetWindow);
	    };
	    HttpPostMessage.prototype.patch = function (url, body, headers, targetWindow) {
	        if (headers === void 0) { headers = {}; }
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        return this.send({
	            method: "PATCH",
	            url: url,
	            headers: headers,
	            body: body
	        }, targetWindow);
	    };
	    HttpPostMessage.prototype.delete = function (url, body, headers, targetWindow) {
	        if (body === void 0) { body = null; }
	        if (headers === void 0) { headers = {}; }
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        return this.send({
	            method: "DELETE",
	            url: url,
	            headers: headers,
	            body: body
	        }, targetWindow);
	    };
	    HttpPostMessage.prototype.send = function (request, targetWindow) {
	        if (targetWindow === void 0) { targetWindow = this.defaultTargetWindow; }
	        request.headers = this.assign({}, this.defaultHeaders, request.headers);
	        if (!targetWindow) {
	            throw new Error("target window is not provided.  You must either provide the target window explicitly as argument to request, or specify default target window when constructing instance of this class.");
	        }
	        return this.windowPostMessageProxy.postMessage(targetWindow, request);
	    };
	    /**
	     * Object.assign() polyfill
	     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
	     */
	    HttpPostMessage.prototype.assign = function (target) {
	        var sources = [];
	        for (var _i = 1; _i < arguments.length; _i++) {
	            sources[_i - 1] = arguments[_i];
	        }
	        if (target === undefined || target === null) {
	            throw new TypeError('Cannot convert undefined or null to object');
	        }
	        var output = Object(target);
	        sources.forEach(function (source) {
	            if (source !== undefined && source !== null) {
	                for (var nextKey in source) {
	                    if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
	                        output[nextKey] = source[nextKey];
	                    }
	                }
	            }
	        });
	        return output;
	    };
	    return HttpPostMessage;
	}());
	exports.HttpPostMessage = HttpPostMessage;


/***/ }
/******/ ])
});
;


/***/ }),

/***/ "./node_modules/powerbi-models/dist/models.js":
/*!****************************************************!*\
  !*** ./node_modules/powerbi-models/dist/models.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*! powerbi-models v1.7.0 | (c) 2016 Microsoft Corporation MIT */
(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateCustomTheme = exports.validateCommandsSettings = exports.validateVisualSettings = exports.validateVisualHeader = exports.validateExportDataRequest = exports.validateQnaInterpretInputData = exports.validateLoadQnaConfiguration = exports.validateSaveAsParameters = exports.validateFilter = exports.validatePage = exports.validateTileLoad = exports.validateDashboardLoad = exports.validateCreateReport = exports.validateReportLoad = exports.validateMenuGroupExtension = exports.validateExtension = exports.validateCustomPageSize = exports.validateVisualizationsPane = exports.validateSyncSlicersPane = exports.validateSelectionPane = exports.validatePageNavigationPane = exports.validateFieldsPane = exports.validateFiltersPane = exports.validateBookmarksPane = exports.validatePanes = exports.validateSettings = exports.validateCaptureBookmarkRequest = exports.validateApplyBookmarkStateRequest = exports.validateApplyBookmarkByNameRequest = exports.validateAddBookmarkRequest = exports.validatePlayBookmarkRequest = exports.validateSlicerState = exports.validateSlicer = exports.validateVisualSelector = exports.isIExtensionArray = exports.isIExtensions = exports.isGroupedMenuExtension = exports.isFlatMenuExtension = exports.VisualDataRoleKindPreference = exports.VisualDataRoleKind = exports.CommandDisplayOption = exports.SlicerTargetSelector = exports.VisualTypeSelector = exports.VisualSelector = exports.PageSelector = exports.Selector = exports.SortDirection = exports.LegendPosition = exports.TextAlignment = exports.CommonErrorCodes = exports.BookmarksPlayMode = exports.ExportDataType = exports.QnaMode = exports.PageNavigationPosition = exports.isColumnAggr = exports.isHierarchyLevelAggr = exports.isHierarchyLevel = exports.isColumn = exports.isMeasure = exports.getFilterType = exports.isBasicFilterWithKeys = exports.isFilterKeyColumnsTarget = exports.AdvancedFilter = exports.TupleFilter = exports.BasicFilterWithKeys = exports.BasicFilter = exports.RelativeTimeFilter = exports.RelativeDateFilter = exports.TopNFilter = exports.IncludeExcludeFilter = exports.NotSupportedFilter = exports.Filter = exports.RelativeDateOperators = exports.RelativeDateFilterTimeUnit = exports.FilterType = exports.FiltersLevel = exports.MenuLocation = exports.ContrastMode = exports.TokenType = exports.ViewMode = exports.Permissions = exports.SectionVisibility = exports.HyperlinkClickBehavior = exports.LayoutType = exports.VisualContainerDisplayMode = exports.BackgroundType = exports.DisplayOption = exports.PageSizeType = exports.TraceType = void 0;
var validator_1 = __webpack_require__(1);
var TraceType;
(function (TraceType) {
    TraceType[TraceType["Information"] = 0] = "Information";
    TraceType[TraceType["Verbose"] = 1] = "Verbose";
    TraceType[TraceType["Warning"] = 2] = "Warning";
    TraceType[TraceType["Error"] = 3] = "Error";
    TraceType[TraceType["ExpectedError"] = 4] = "ExpectedError";
    TraceType[TraceType["UnexpectedError"] = 5] = "UnexpectedError";
    TraceType[TraceType["Fatal"] = 6] = "Fatal";
})(TraceType = exports.TraceType || (exports.TraceType = {}));
var PageSizeType;
(function (PageSizeType) {
    PageSizeType[PageSizeType["Widescreen"] = 0] = "Widescreen";
    PageSizeType[PageSizeType["Standard"] = 1] = "Standard";
    PageSizeType[PageSizeType["Cortana"] = 2] = "Cortana";
    PageSizeType[PageSizeType["Letter"] = 3] = "Letter";
    PageSizeType[PageSizeType["Custom"] = 4] = "Custom";
})(PageSizeType = exports.PageSizeType || (exports.PageSizeType = {}));
var DisplayOption;
(function (DisplayOption) {
    DisplayOption[DisplayOption["FitToPage"] = 0] = "FitToPage";
    DisplayOption[DisplayOption["FitToWidth"] = 1] = "FitToWidth";
    DisplayOption[DisplayOption["ActualSize"] = 2] = "ActualSize";
})(DisplayOption = exports.DisplayOption || (exports.DisplayOption = {}));
var BackgroundType;
(function (BackgroundType) {
    BackgroundType[BackgroundType["Default"] = 0] = "Default";
    BackgroundType[BackgroundType["Transparent"] = 1] = "Transparent";
})(BackgroundType = exports.BackgroundType || (exports.BackgroundType = {}));
var VisualContainerDisplayMode;
(function (VisualContainerDisplayMode) {
    VisualContainerDisplayMode[VisualContainerDisplayMode["Visible"] = 0] = "Visible";
    VisualContainerDisplayMode[VisualContainerDisplayMode["Hidden"] = 1] = "Hidden";
})(VisualContainerDisplayMode = exports.VisualContainerDisplayMode || (exports.VisualContainerDisplayMode = {}));
var LayoutType;
(function (LayoutType) {
    LayoutType[LayoutType["Master"] = 0] = "Master";
    LayoutType[LayoutType["Custom"] = 1] = "Custom";
    LayoutType[LayoutType["MobilePortrait"] = 2] = "MobilePortrait";
    LayoutType[LayoutType["MobileLandscape"] = 3] = "MobileLandscape";
})(LayoutType = exports.LayoutType || (exports.LayoutType = {}));
var HyperlinkClickBehavior;
(function (HyperlinkClickBehavior) {
    HyperlinkClickBehavior[HyperlinkClickBehavior["Navigate"] = 0] = "Navigate";
    HyperlinkClickBehavior[HyperlinkClickBehavior["NavigateAndRaiseEvent"] = 1] = "NavigateAndRaiseEvent";
    HyperlinkClickBehavior[HyperlinkClickBehavior["RaiseEvent"] = 2] = "RaiseEvent";
})(HyperlinkClickBehavior = exports.HyperlinkClickBehavior || (exports.HyperlinkClickBehavior = {}));
var SectionVisibility;
(function (SectionVisibility) {
    SectionVisibility[SectionVisibility["AlwaysVisible"] = 0] = "AlwaysVisible";
    SectionVisibility[SectionVisibility["HiddenInViewMode"] = 1] = "HiddenInViewMode";
})(SectionVisibility = exports.SectionVisibility || (exports.SectionVisibility = {}));
var Permissions;
(function (Permissions) {
    Permissions[Permissions["Read"] = 0] = "Read";
    Permissions[Permissions["ReadWrite"] = 1] = "ReadWrite";
    Permissions[Permissions["Copy"] = 2] = "Copy";
    Permissions[Permissions["Create"] = 4] = "Create";
    Permissions[Permissions["All"] = 7] = "All";
})(Permissions = exports.Permissions || (exports.Permissions = {}));
var ViewMode;
(function (ViewMode) {
    ViewMode[ViewMode["View"] = 0] = "View";
    ViewMode[ViewMode["Edit"] = 1] = "Edit";
})(ViewMode = exports.ViewMode || (exports.ViewMode = {}));
var TokenType;
(function (TokenType) {
    TokenType[TokenType["Aad"] = 0] = "Aad";
    TokenType[TokenType["Embed"] = 1] = "Embed";
})(TokenType = exports.TokenType || (exports.TokenType = {}));
var ContrastMode;
(function (ContrastMode) {
    ContrastMode[ContrastMode["None"] = 0] = "None";
    ContrastMode[ContrastMode["HighContrast1"] = 1] = "HighContrast1";
    ContrastMode[ContrastMode["HighContrast2"] = 2] = "HighContrast2";
    ContrastMode[ContrastMode["HighContrastBlack"] = 3] = "HighContrastBlack";
    ContrastMode[ContrastMode["HighContrastWhite"] = 4] = "HighContrastWhite";
})(ContrastMode = exports.ContrastMode || (exports.ContrastMode = {}));
var MenuLocation;
(function (MenuLocation) {
    MenuLocation[MenuLocation["Bottom"] = 0] = "Bottom";
    MenuLocation[MenuLocation["Top"] = 1] = "Top";
})(MenuLocation = exports.MenuLocation || (exports.MenuLocation = {}));
var FiltersLevel;
(function (FiltersLevel) {
    FiltersLevel[FiltersLevel["Report"] = 0] = "Report";
    FiltersLevel[FiltersLevel["Page"] = 1] = "Page";
    FiltersLevel[FiltersLevel["Visual"] = 2] = "Visual";
})(FiltersLevel = exports.FiltersLevel || (exports.FiltersLevel = {}));
var FilterType;
(function (FilterType) {
    FilterType[FilterType["Advanced"] = 0] = "Advanced";
    FilterType[FilterType["Basic"] = 1] = "Basic";
    FilterType[FilterType["Unknown"] = 2] = "Unknown";
    FilterType[FilterType["IncludeExclude"] = 3] = "IncludeExclude";
    FilterType[FilterType["RelativeDate"] = 4] = "RelativeDate";
    FilterType[FilterType["TopN"] = 5] = "TopN";
    FilterType[FilterType["Tuple"] = 6] = "Tuple";
    FilterType[FilterType["RelativeTime"] = 7] = "RelativeTime";
})(FilterType = exports.FilterType || (exports.FilterType = {}));
var RelativeDateFilterTimeUnit;
(function (RelativeDateFilterTimeUnit) {
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Days"] = 0] = "Days";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Weeks"] = 1] = "Weeks";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["CalendarWeeks"] = 2] = "CalendarWeeks";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Months"] = 3] = "Months";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["CalendarMonths"] = 4] = "CalendarMonths";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Years"] = 5] = "Years";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["CalendarYears"] = 6] = "CalendarYears";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Minutes"] = 7] = "Minutes";
    RelativeDateFilterTimeUnit[RelativeDateFilterTimeUnit["Hours"] = 8] = "Hours";
})(RelativeDateFilterTimeUnit = exports.RelativeDateFilterTimeUnit || (exports.RelativeDateFilterTimeUnit = {}));
var RelativeDateOperators;
(function (RelativeDateOperators) {
    RelativeDateOperators[RelativeDateOperators["InLast"] = 0] = "InLast";
    RelativeDateOperators[RelativeDateOperators["InThis"] = 1] = "InThis";
    RelativeDateOperators[RelativeDateOperators["InNext"] = 2] = "InNext";
})(RelativeDateOperators = exports.RelativeDateOperators || (exports.RelativeDateOperators = {}));
var Filter = /** @class */ (function () {
    function Filter(target, filterType) {
        this.target = target;
        this.filterType = filterType;
    }
    Filter.prototype.toJSON = function () {
        var filter = {
            $schema: this.schemaUrl,
            target: this.target,
            filterType: this.filterType
        };
        // Add displaySettings only when defined
        if (this.displaySettings !== undefined) {
            filter.displaySettings = this.displaySettings;
        }
        return filter;
    };
    return Filter;
}());
exports.Filter = Filter;
var NotSupportedFilter = /** @class */ (function (_super) {
    __extends(NotSupportedFilter, _super);
    function NotSupportedFilter(target, message, notSupportedTypeName) {
        var _this = _super.call(this, target, FilterType.Unknown) || this;
        _this.message = message;
        _this.notSupportedTypeName = notSupportedTypeName;
        _this.schemaUrl = NotSupportedFilter.schemaUrl;
        return _this;
    }
    NotSupportedFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.message = this.message;
        filter.notSupportedTypeName = this.notSupportedTypeName;
        return filter;
    };
    NotSupportedFilter.schemaUrl = "http://powerbi.com/product/schema#notSupported";
    return NotSupportedFilter;
}(Filter));
exports.NotSupportedFilter = NotSupportedFilter;
var IncludeExcludeFilter = /** @class */ (function (_super) {
    __extends(IncludeExcludeFilter, _super);
    function IncludeExcludeFilter(target, isExclude, values) {
        var _this = _super.call(this, target, FilterType.IncludeExclude) || this;
        _this.values = values;
        _this.isExclude = isExclude;
        _this.schemaUrl = IncludeExcludeFilter.schemaUrl;
        return _this;
    }
    IncludeExcludeFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.isExclude = this.isExclude;
        filter.values = this.values;
        return filter;
    };
    IncludeExcludeFilter.schemaUrl = "http://powerbi.com/product/schema#includeExclude";
    return IncludeExcludeFilter;
}(Filter));
exports.IncludeExcludeFilter = IncludeExcludeFilter;
var TopNFilter = /** @class */ (function (_super) {
    __extends(TopNFilter, _super);
    function TopNFilter(target, operator, itemCount, orderBy) {
        var _this = _super.call(this, target, FilterType.TopN) || this;
        _this.operator = operator;
        _this.itemCount = itemCount;
        _this.schemaUrl = TopNFilter.schemaUrl;
        _this.orderBy = orderBy;
        return _this;
    }
    TopNFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.operator = this.operator;
        filter.itemCount = this.itemCount;
        filter.orderBy = this.orderBy;
        return filter;
    };
    TopNFilter.schemaUrl = "http://powerbi.com/product/schema#topN";
    return TopNFilter;
}(Filter));
exports.TopNFilter = TopNFilter;
var RelativeDateFilter = /** @class */ (function (_super) {
    __extends(RelativeDateFilter, _super);
    function RelativeDateFilter(target, operator, timeUnitsCount, timeUnitType, includeToday) {
        var _this = _super.call(this, target, FilterType.RelativeDate) || this;
        _this.operator = operator;
        _this.timeUnitsCount = timeUnitsCount;
        _this.timeUnitType = timeUnitType;
        _this.includeToday = includeToday;
        _this.schemaUrl = RelativeDateFilter.schemaUrl;
        return _this;
    }
    RelativeDateFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.operator = this.operator;
        filter.timeUnitsCount = this.timeUnitsCount;
        filter.timeUnitType = this.timeUnitType;
        filter.includeToday = this.includeToday;
        return filter;
    };
    RelativeDateFilter.schemaUrl = "http://powerbi.com/product/schema#relativeDate";
    return RelativeDateFilter;
}(Filter));
exports.RelativeDateFilter = RelativeDateFilter;
var RelativeTimeFilter = /** @class */ (function (_super) {
    __extends(RelativeTimeFilter, _super);
    function RelativeTimeFilter(target, operator, timeUnitsCount, timeUnitType) {
        var _this = _super.call(this, target, FilterType.RelativeTime) || this;
        _this.operator = operator;
        _this.timeUnitsCount = timeUnitsCount;
        _this.timeUnitType = timeUnitType;
        _this.schemaUrl = RelativeTimeFilter.schemaUrl;
        return _this;
    }
    RelativeTimeFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.operator = this.operator;
        filter.timeUnitsCount = this.timeUnitsCount;
        filter.timeUnitType = this.timeUnitType;
        return filter;
    };
    RelativeTimeFilter.schemaUrl = "http://powerbi.com/product/schema#relativeTime";
    return RelativeTimeFilter;
}(Filter));
exports.RelativeTimeFilter = RelativeTimeFilter;
var BasicFilter = /** @class */ (function (_super) {
    __extends(BasicFilter, _super);
    function BasicFilter(target, operator) {
        var values = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            values[_i - 2] = arguments[_i];
        }
        var _this = _super.call(this, target, FilterType.Basic) || this;
        _this.operator = operator;
        _this.schemaUrl = BasicFilter.schemaUrl;
        if (values.length === 0 && operator !== "All") {
            throw new Error("values must be a non-empty array unless your operator is \"All\".");
        }
        /**
         * Accept values as array instead of as individual arguments
         * new BasicFilter('a', 'b', 1, 2);
         * new BasicFilter('a', 'b', [1,2]);
         */
        if (Array.isArray(values[0])) {
            _this.values = values[0];
        }
        else {
            _this.values = values;
        }
        return _this;
    }
    BasicFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.operator = this.operator;
        filter.values = this.values;
        filter.requireSingleSelection = !!this.requireSingleSelection;
        return filter;
    };
    BasicFilter.schemaUrl = "http://powerbi.com/product/schema#basic";
    return BasicFilter;
}(Filter));
exports.BasicFilter = BasicFilter;
var BasicFilterWithKeys = /** @class */ (function (_super) {
    __extends(BasicFilterWithKeys, _super);
    function BasicFilterWithKeys(target, operator, values, keyValues) {
        var _this = _super.call(this, target, operator, values) || this;
        _this.keyValues = keyValues;
        _this.target = target;
        var numberOfKeys = target.keys ? target.keys.length : 0;
        if (numberOfKeys > 0 && !keyValues) {
            throw new Error("You should pass the values to be filtered for each key. You passed: no values and " + numberOfKeys + " keys");
        }
        if (numberOfKeys === 0 && keyValues && keyValues.length > 0) {
            throw new Error("You passed key values but your target object doesn't contain the keys to be filtered");
        }
        for (var _i = 0, _a = _this.keyValues; _i < _a.length; _i++) {
            var keyValue = _a[_i];
            if (keyValue) {
                var lengthOfArray = keyValue.length;
                if (lengthOfArray !== numberOfKeys) {
                    throw new Error("Each tuple of key values should contain a value for each of the keys. You passed: " + lengthOfArray + " values and " + numberOfKeys + " keys");
                }
            }
        }
        return _this;
    }
    BasicFilterWithKeys.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.keyValues = this.keyValues;
        return filter;
    };
    return BasicFilterWithKeys;
}(BasicFilter));
exports.BasicFilterWithKeys = BasicFilterWithKeys;
var TupleFilter = /** @class */ (function (_super) {
    __extends(TupleFilter, _super);
    function TupleFilter(target, operator, values) {
        var _this = _super.call(this, target, FilterType.Tuple) || this;
        _this.operator = operator;
        _this.schemaUrl = TupleFilter.schemaUrl;
        _this.values = values;
        return _this;
    }
    TupleFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.operator = this.operator;
        filter.values = this.values;
        filter.target = this.target;
        return filter;
    };
    TupleFilter.schemaUrl = "http://powerbi.com/product/schema#tuple";
    return TupleFilter;
}(Filter));
exports.TupleFilter = TupleFilter;
var AdvancedFilter = /** @class */ (function (_super) {
    __extends(AdvancedFilter, _super);
    function AdvancedFilter(target, logicalOperator) {
        var conditions = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            conditions[_i - 2] = arguments[_i];
        }
        var _this = _super.call(this, target, FilterType.Advanced) || this;
        _this.schemaUrl = AdvancedFilter.schemaUrl;
        // Guard statements
        if (typeof logicalOperator !== "string" || logicalOperator.length === 0) {
            // TODO: It would be nicer to list out the possible logical operators.
            throw new Error("logicalOperator must be a valid operator, You passed: " + logicalOperator);
        }
        _this.logicalOperator = logicalOperator;
        var extractedConditions;
        /**
         * Accept conditions as array instead of as individual arguments
         * new AdvancedFilter('a', 'b', "And", { value: 1, operator: "Equals" }, { value: 2, operator: "IsGreaterThan" });
         * new AdvancedFilter('a', 'b', "And", [{ value: 1, operator: "Equals" }, { value: 2, operator: "IsGreaterThan" }]);
         */
        if (Array.isArray(conditions[0])) {
            extractedConditions = conditions[0];
        }
        else {
            extractedConditions = conditions;
        }
        if (extractedConditions.length === 0) {
            throw new Error("conditions must be a non-empty array. You passed: " + conditions);
        }
        if (extractedConditions.length > 2) {
            throw new Error("AdvancedFilters may not have more than two conditions. You passed: " + conditions.length);
        }
        if (extractedConditions.length === 1 && logicalOperator !== "And") {
            throw new Error("Logical Operator must be \"And\" when there is only one condition provided");
        }
        _this.conditions = extractedConditions;
        return _this;
    }
    AdvancedFilter.prototype.toJSON = function () {
        var filter = _super.prototype.toJSON.call(this);
        filter.logicalOperator = this.logicalOperator;
        filter.conditions = this.conditions;
        return filter;
    };
    AdvancedFilter.schemaUrl = "http://powerbi.com/product/schema#advanced";
    return AdvancedFilter;
}(Filter));
exports.AdvancedFilter = AdvancedFilter;
function isFilterKeyColumnsTarget(target) {
    return isColumn(target) && !!target.keys;
}
exports.isFilterKeyColumnsTarget = isFilterKeyColumnsTarget;
function isBasicFilterWithKeys(filter) {
    return getFilterType(filter) === FilterType.Basic && !!filter.keyValues;
}
exports.isBasicFilterWithKeys = isBasicFilterWithKeys;
function getFilterType(filter) {
    if (filter.filterType) {
        return filter.filterType;
    }
    var basicFilter = filter;
    var advancedFilter = filter;
    if ((typeof basicFilter.operator === "string")
        && (Array.isArray(basicFilter.values))) {
        return FilterType.Basic;
    }
    else if ((typeof advancedFilter.logicalOperator === "string")
        && (Array.isArray(advancedFilter.conditions))) {
        return FilterType.Advanced;
    }
    else {
        return FilterType.Unknown;
    }
}
exports.getFilterType = getFilterType;
function isMeasure(arg) {
    return arg.table !== undefined && arg.measure !== undefined;
}
exports.isMeasure = isMeasure;
function isColumn(arg) {
    return !!(arg.table && arg.column && !arg.aggregationFunction);
}
exports.isColumn = isColumn;
function isHierarchyLevel(arg) {
    return !!(arg.table && arg.hierarchy && arg.hierarchyLevel && !arg.aggregationFunction);
}
exports.isHierarchyLevel = isHierarchyLevel;
function isHierarchyLevelAggr(arg) {
    return !!(arg.table && arg.hierarchy && arg.hierarchyLevel && arg.aggregationFunction);
}
exports.isHierarchyLevelAggr = isHierarchyLevelAggr;
function isColumnAggr(arg) {
    return !!(arg.table && arg.column && arg.aggregationFunction);
}
exports.isColumnAggr = isColumnAggr;
var PageNavigationPosition;
(function (PageNavigationPosition) {
    PageNavigationPosition[PageNavigationPosition["Bottom"] = 0] = "Bottom";
    PageNavigationPosition[PageNavigationPosition["Left"] = 1] = "Left";
})(PageNavigationPosition = exports.PageNavigationPosition || (exports.PageNavigationPosition = {}));
var QnaMode;
(function (QnaMode) {
    QnaMode[QnaMode["Interactive"] = 0] = "Interactive";
    QnaMode[QnaMode["ResultOnly"] = 1] = "ResultOnly";
})(QnaMode = exports.QnaMode || (exports.QnaMode = {}));
var ExportDataType;
(function (ExportDataType) {
    ExportDataType[ExportDataType["Summarized"] = 0] = "Summarized";
    ExportDataType[ExportDataType["Underlying"] = 1] = "Underlying";
})(ExportDataType = exports.ExportDataType || (exports.ExportDataType = {}));
var BookmarksPlayMode;
(function (BookmarksPlayMode) {
    BookmarksPlayMode[BookmarksPlayMode["Off"] = 0] = "Off";
    BookmarksPlayMode[BookmarksPlayMode["Presentation"] = 1] = "Presentation";
})(BookmarksPlayMode = exports.BookmarksPlayMode || (exports.BookmarksPlayMode = {}));
// This is not an enum because enum strings require
// us to upgrade typeScript version and change SDK build definition
exports.CommonErrorCodes = {
    TokenExpired: 'TokenExpired',
    NotFound: 'PowerBIEntityNotFound',
    InvalidParameters: 'Invalid parameters',
    LoadReportFailed: 'LoadReportFailed',
    NotAuthorized: 'PowerBINotAuthorizedException',
    FailedToLoadModel: 'ExplorationContainer_FailedToLoadModel_DefaultDetails',
};
exports.TextAlignment = {
    Left: 'left',
    Center: 'center',
    Right: 'right',
};
exports.LegendPosition = {
    Top: 'Top',
    Bottom: 'Bottom',
    Right: 'Right',
    Left: 'Left',
    TopCenter: 'TopCenter',
    BottomCenter: 'BottomCenter',
    RightCenter: 'RightCenter',
    LeftCenter: 'LeftCenter',
};
var SortDirection;
(function (SortDirection) {
    SortDirection[SortDirection["Ascending"] = 1] = "Ascending";
    SortDirection[SortDirection["Descending"] = 2] = "Descending";
})(SortDirection = exports.SortDirection || (exports.SortDirection = {}));
var Selector = /** @class */ (function () {
    function Selector(schema) {
        this.$schema = schema;
    }
    Selector.prototype.toJSON = function () {
        return {
            $schema: this.$schema
        };
    };
    return Selector;
}());
exports.Selector = Selector;
var PageSelector = /** @class */ (function (_super) {
    __extends(PageSelector, _super);
    function PageSelector(pageName) {
        var _this = _super.call(this, PageSelector.schemaUrl) || this;
        _this.pageName = pageName;
        return _this;
    }
    PageSelector.prototype.toJSON = function () {
        var selector = _super.prototype.toJSON.call(this);
        selector.pageName = this.pageName;
        return selector;
    };
    PageSelector.schemaUrl = "http://powerbi.com/product/schema#pageSelector";
    return PageSelector;
}(Selector));
exports.PageSelector = PageSelector;
var VisualSelector = /** @class */ (function (_super) {
    __extends(VisualSelector, _super);
    function VisualSelector(visualName) {
        var _this = _super.call(this, VisualSelector.schemaUrl) || this;
        _this.visualName = visualName;
        return _this;
    }
    VisualSelector.prototype.toJSON = function () {
        var selector = _super.prototype.toJSON.call(this);
        selector.visualName = this.visualName;
        return selector;
    };
    VisualSelector.schemaUrl = "http://powerbi.com/product/schema#visualSelector";
    return VisualSelector;
}(Selector));
exports.VisualSelector = VisualSelector;
var VisualTypeSelector = /** @class */ (function (_super) {
    __extends(VisualTypeSelector, _super);
    function VisualTypeSelector(visualType) {
        var _this = _super.call(this, VisualSelector.schemaUrl) || this;
        _this.visualType = visualType;
        return _this;
    }
    VisualTypeSelector.prototype.toJSON = function () {
        var selector = _super.prototype.toJSON.call(this);
        selector.visualType = this.visualType;
        return selector;
    };
    VisualTypeSelector.schemaUrl = "http://powerbi.com/product/schema#visualTypeSelector";
    return VisualTypeSelector;
}(Selector));
exports.VisualTypeSelector = VisualTypeSelector;
var SlicerTargetSelector = /** @class */ (function (_super) {
    __extends(SlicerTargetSelector, _super);
    function SlicerTargetSelector(target) {
        var _this = _super.call(this, VisualSelector.schemaUrl) || this;
        _this.target = target;
        return _this;
    }
    SlicerTargetSelector.prototype.toJSON = function () {
        var selector = _super.prototype.toJSON.call(this);
        selector.target = this.target;
        return selector;
    };
    SlicerTargetSelector.schemaUrl = "http://powerbi.com/product/schema#slicerTargetSelector";
    return SlicerTargetSelector;
}(Selector));
exports.SlicerTargetSelector = SlicerTargetSelector;
var CommandDisplayOption;
(function (CommandDisplayOption) {
    CommandDisplayOption[CommandDisplayOption["Enabled"] = 0] = "Enabled";
    CommandDisplayOption[CommandDisplayOption["Disabled"] = 1] = "Disabled";
    CommandDisplayOption[CommandDisplayOption["Hidden"] = 2] = "Hidden";
})(CommandDisplayOption = exports.CommandDisplayOption || (exports.CommandDisplayOption = {}));
/*
 * Visual CRUD
 */
var VisualDataRoleKind;
(function (VisualDataRoleKind) {
    // Indicates that the role should be bound to something that evaluates to a grouping of values.
    VisualDataRoleKind[VisualDataRoleKind["Grouping"] = 0] = "Grouping";
    // Indicates that the role should be bound to something that evaluates to a single value in a scope.
    VisualDataRoleKind[VisualDataRoleKind["Measure"] = 1] = "Measure";
    // Indicates that the role can be bound to either Grouping or Measure.
    VisualDataRoleKind[VisualDataRoleKind["GroupingOrMeasure"] = 2] = "GroupingOrMeasure";
})(VisualDataRoleKind = exports.VisualDataRoleKind || (exports.VisualDataRoleKind = {}));
// Indicates the visual preference on Grouping or Measure. Only applicable if kind is GroupingOrMeasure.
var VisualDataRoleKindPreference;
(function (VisualDataRoleKindPreference) {
    VisualDataRoleKindPreference[VisualDataRoleKindPreference["Measure"] = 0] = "Measure";
    VisualDataRoleKindPreference[VisualDataRoleKindPreference["Grouping"] = 1] = "Grouping";
})(VisualDataRoleKindPreference = exports.VisualDataRoleKindPreference || (exports.VisualDataRoleKindPreference = {}));
function isFlatMenuExtension(menuExtension) {
    return menuExtension && !isGroupedMenuExtension(menuExtension);
}
exports.isFlatMenuExtension = isFlatMenuExtension;
function isGroupedMenuExtension(menuExtension) {
    return menuExtension && !!menuExtension.groupName;
}
exports.isGroupedMenuExtension = isGroupedMenuExtension;
function isIExtensions(extensions) {
    return extensions && !isIExtensionArray(extensions);
}
exports.isIExtensions = isIExtensions;
function isIExtensionArray(extensions) {
    return Array.isArray(extensions);
}
exports.isIExtensionArray = isIExtensionArray;
function normalizeError(error) {
    var message = error.message;
    if (!message) {
        message = error.path + " is invalid. Not meeting " + error.keyword + " constraint";
    }
    return {
        message: message
    };
}
function validateVisualSelector(input) {
    var errors = validator_1.Validators.visualSelectorValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateVisualSelector = validateVisualSelector;
function validateSlicer(input) {
    var errors = validator_1.Validators.slicerValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSlicer = validateSlicer;
function validateSlicerState(input) {
    var errors = validator_1.Validators.slicerStateValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSlicerState = validateSlicerState;
function validatePlayBookmarkRequest(input) {
    var errors = validator_1.Validators.playBookmarkRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validatePlayBookmarkRequest = validatePlayBookmarkRequest;
function validateAddBookmarkRequest(input) {
    var errors = validator_1.Validators.addBookmarkRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateAddBookmarkRequest = validateAddBookmarkRequest;
function validateApplyBookmarkByNameRequest(input) {
    var errors = validator_1.Validators.applyBookmarkByNameRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateApplyBookmarkByNameRequest = validateApplyBookmarkByNameRequest;
function validateApplyBookmarkStateRequest(input) {
    var errors = validator_1.Validators.applyBookmarkStateRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateApplyBookmarkStateRequest = validateApplyBookmarkStateRequest;
function validateCaptureBookmarkRequest(input) {
    var errors = validator_1.Validators.captureBookmarkRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateCaptureBookmarkRequest = validateCaptureBookmarkRequest;
function validateSettings(input) {
    var errors = validator_1.Validators.settingsValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSettings = validateSettings;
function validatePanes(input) {
    var errors = validator_1.Validators.reportPanesValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validatePanes = validatePanes;
function validateBookmarksPane(input) {
    var errors = validator_1.Validators.bookmarksPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateBookmarksPane = validateBookmarksPane;
function validateFiltersPane(input) {
    var errors = validator_1.Validators.filtersPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateFiltersPane = validateFiltersPane;
function validateFieldsPane(input) {
    var errors = validator_1.Validators.fieldsPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateFieldsPane = validateFieldsPane;
function validatePageNavigationPane(input) {
    var errors = validator_1.Validators.pageNavigationPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validatePageNavigationPane = validatePageNavigationPane;
function validateSelectionPane(input) {
    var errors = validator_1.Validators.selectionPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSelectionPane = validateSelectionPane;
function validateSyncSlicersPane(input) {
    var errors = validator_1.Validators.syncSlicersPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSyncSlicersPane = validateSyncSlicersPane;
function validateVisualizationsPane(input) {
    var errors = validator_1.Validators.visualizationsPaneValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateVisualizationsPane = validateVisualizationsPane;
function validateCustomPageSize(input) {
    var errors = validator_1.Validators.customPageSizeValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateCustomPageSize = validateCustomPageSize;
function validateExtension(input) {
    var errors = validator_1.Validators.extensionValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateExtension = validateExtension;
function validateMenuGroupExtension(input) {
    var errors = validator_1.Validators.menuGroupExtensionValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateMenuGroupExtension = validateMenuGroupExtension;
function validateReportLoad(input) {
    var errors = validator_1.Validators.reportLoadValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateReportLoad = validateReportLoad;
function validateCreateReport(input) {
    var errors = validator_1.Validators.reportCreateValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateCreateReport = validateCreateReport;
function validateDashboardLoad(input) {
    var errors = validator_1.Validators.dashboardLoadValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateDashboardLoad = validateDashboardLoad;
function validateTileLoad(input) {
    var errors = validator_1.Validators.tileLoadValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateTileLoad = validateTileLoad;
function validatePage(input) {
    var errors = validator_1.Validators.pageValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validatePage = validatePage;
function validateFilter(input) {
    var errors = validator_1.Validators.filtersValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateFilter = validateFilter;
function validateSaveAsParameters(input) {
    var errors = validator_1.Validators.saveAsParametersValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateSaveAsParameters = validateSaveAsParameters;
function validateLoadQnaConfiguration(input) {
    var errors = validator_1.Validators.loadQnaValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateLoadQnaConfiguration = validateLoadQnaConfiguration;
function validateQnaInterpretInputData(input) {
    var errors = validator_1.Validators.qnaInterpretInputDataValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateQnaInterpretInputData = validateQnaInterpretInputData;
function validateExportDataRequest(input) {
    var errors = validator_1.Validators.exportDataRequestValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateExportDataRequest = validateExportDataRequest;
function validateVisualHeader(input) {
    var errors = validator_1.Validators.visualHeaderValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateVisualHeader = validateVisualHeader;
function validateVisualSettings(input) {
    var errors = validator_1.Validators.visualSettingsValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateVisualSettings = validateVisualSettings;
function validateCommandsSettings(input) {
    var errors = validator_1.Validators.commandsSettingsValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateCommandsSettings = validateCommandsSettings;
function validateCustomTheme(input) {
    var errors = validator_1.Validators.customThemeValidator.validate(input);
    return errors ? errors.map(normalizeError) : undefined;
}
exports.validateCustomTheme = validateCustomTheme;


/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.Validators = void 0;
var barsValidator_1 = __webpack_require__(2);
var bookmarkValidator_1 = __webpack_require__(5);
var commandsSettingsValidator_1 = __webpack_require__(6);
var customThemeValidator_1 = __webpack_require__(7);
var dashboardLoadValidator_1 = __webpack_require__(8);
var datasetBindingValidator_1 = __webpack_require__(9);
var exportDataValidator_1 = __webpack_require__(10);
var extensionsValidator_1 = __webpack_require__(11);
var filtersValidator_1 = __webpack_require__(12);
var layoutValidator_1 = __webpack_require__(13);
var pageValidator_1 = __webpack_require__(14);
var panesValidator_1 = __webpack_require__(15);
var qnaValidator_1 = __webpack_require__(16);
var reportCreateValidator_1 = __webpack_require__(17);
var reportLoadValidator_1 = __webpack_require__(18);
var saveAsParametersValidator_1 = __webpack_require__(19);
var selectorsValidator_1 = __webpack_require__(20);
var settingsValidator_1 = __webpack_require__(21);
var slicersValidator_1 = __webpack_require__(22);
var tileLoadValidator_1 = __webpack_require__(23);
var visualSettingsValidator_1 = __webpack_require__(24);
var anyOfValidator_1 = __webpack_require__(25);
var fieldForbiddenValidator_1 = __webpack_require__(26);
var fieldRequiredValidator_1 = __webpack_require__(27);
var mapValidator_1 = __webpack_require__(28);
var typeValidator_1 = __webpack_require__(4);
exports.Validators = {
    addBookmarkRequestValidator: new bookmarkValidator_1.AddBookmarkRequestValidator(),
    advancedFilterTypeValidator: new typeValidator_1.EnumValidator([0]),
    advancedFilterValidator: new filtersValidator_1.AdvancedFilterValidator(),
    anyArrayValidator: new typeValidator_1.ArrayValidator([new anyOfValidator_1.AnyOfValidator([new typeValidator_1.StringValidator(), new typeValidator_1.NumberValidator(), new typeValidator_1.BooleanValidator()])]),
    anyFilterValidator: new anyOfValidator_1.AnyOfValidator([new filtersValidator_1.BasicFilterValidator(), new filtersValidator_1.AdvancedFilterValidator(), new filtersValidator_1.IncludeExcludeFilterValidator(), new filtersValidator_1.NotSupportedFilterValidator(), new filtersValidator_1.RelativeDateFilterValidator(), new filtersValidator_1.TopNFilterValidator(), new filtersValidator_1.RelativeTimeFilterValidator()]),
    anyValueValidator: new anyOfValidator_1.AnyOfValidator([new typeValidator_1.StringValidator(), new typeValidator_1.NumberValidator(), new typeValidator_1.BooleanValidator()]),
    actionBarValidator: new barsValidator_1.ActionBarValidator(),
    applyBookmarkByNameRequestValidator: new bookmarkValidator_1.ApplyBookmarkByNameRequestValidator(),
    applyBookmarkStateRequestValidator: new bookmarkValidator_1.ApplyBookmarkStateRequestValidator(),
    applyBookmarkValidator: new anyOfValidator_1.AnyOfValidator([new bookmarkValidator_1.ApplyBookmarkByNameRequestValidator(), new bookmarkValidator_1.ApplyBookmarkStateRequestValidator()]),
    backgroundValidator: new typeValidator_1.EnumValidator([0, 1]),
    basicFilterTypeValidator: new typeValidator_1.EnumValidator([1]),
    basicFilterValidator: new filtersValidator_1.BasicFilterValidator(),
    booleanArrayValidator: new typeValidator_1.BooleanArrayValidator(),
    booleanValidator: new typeValidator_1.BooleanValidator(),
    bookmarksPaneValidator: new panesValidator_1.BookmarksPaneValidator(),
    captureBookmarkOptionsValidator: new bookmarkValidator_1.CaptureBookmarkOptionsValidator(),
    captureBookmarkRequestValidator: new bookmarkValidator_1.CaptureBookmarkRequestValidator(),
    commandDisplayOptionValidator: new typeValidator_1.EnumValidator([0, 1, 2]),
    commandExtensionSelectorValidator: new anyOfValidator_1.AnyOfValidator([new selectorsValidator_1.VisualSelectorValidator(), new selectorsValidator_1.VisualTypeSelectorValidator()]),
    commandExtensionArrayValidator: new typeValidator_1.ArrayValidator([new extensionsValidator_1.CommandExtensionValidator()]),
    commandExtensionValidator: new extensionsValidator_1.CommandExtensionValidator(),
    commandsSettingsArrayValidator: new typeValidator_1.ArrayValidator([new commandsSettingsValidator_1.CommandsSettingsValidator()]),
    commandsSettingsValidator: new commandsSettingsValidator_1.CommandsSettingsValidator(),
    conditionItemValidator: new filtersValidator_1.ConditionItemValidator(),
    contrastModeValidator: new typeValidator_1.EnumValidator([0, 1, 2, 3, 4]),
    customLayoutDisplayOptionValidator: new typeValidator_1.EnumValidator([0, 1, 2]),
    customLayoutValidator: new layoutValidator_1.CustomLayoutValidator(),
    customPageSizeValidator: new pageValidator_1.CustomPageSizeValidator(),
    customThemeValidator: new customThemeValidator_1.CustomThemeValidator(),
    dashboardLoadValidator: new dashboardLoadValidator_1.DashboardLoadValidator(),
    datasetBindingValidator: new datasetBindingValidator_1.DatasetBindingValidator(),
    displayStateModeValidator: new typeValidator_1.EnumValidator([0, 1]),
    displayStateValidator: new layoutValidator_1.DisplayStateValidator(),
    exportDataRequestValidator: new exportDataValidator_1.ExportDataRequestValidator(),
    extensionArrayValidator: new typeValidator_1.ArrayValidator([new extensionsValidator_1.ExtensionValidator()]),
    extensionsValidator: new anyOfValidator_1.AnyOfValidator([new typeValidator_1.ArrayValidator([new extensionsValidator_1.ExtensionValidator()]), new extensionsValidator_1.ExtensionsValidator()]),
    extensionPointsValidator: new extensionsValidator_1.ExtensionPointsValidator(),
    extensionValidator: new extensionsValidator_1.ExtensionValidator(),
    fieldForbiddenValidator: new fieldForbiddenValidator_1.FieldForbiddenValidator(),
    fieldRequiredValidator: new fieldRequiredValidator_1.FieldRequiredValidator(),
    fieldsPaneValidator: new panesValidator_1.FieldsPaneValidator(),
    filterColumnTargetValidator: new filtersValidator_1.FilterColumnTargetValidator(),
    filterConditionsValidator: new typeValidator_1.ArrayValidator([new filtersValidator_1.ConditionItemValidator()]),
    filterHierarchyTargetValidator: new filtersValidator_1.FilterHierarchyTargetValidator(),
    filterMeasureTargetValidator: new filtersValidator_1.FilterMeasureTargetValidator(),
    filterTargetValidator: new anyOfValidator_1.AnyOfValidator([new filtersValidator_1.FilterColumnTargetValidator(), new filtersValidator_1.FilterHierarchyTargetValidator(), new filtersValidator_1.FilterMeasureTargetValidator()]),
    filtersArrayValidator: new typeValidator_1.ArrayValidator([new anyOfValidator_1.AnyOfValidator([new filtersValidator_1.BasicFilterValidator(), new filtersValidator_1.AdvancedFilterValidator(), new filtersValidator_1.RelativeDateFilterValidator(), new filtersValidator_1.RelativeTimeFilterValidator()])]),
    filtersValidator: new filtersValidator_1.FilterValidator(),
    filtersPaneValidator: new panesValidator_1.FiltersPaneValidator(),
    hyperlinkClickBehaviorValidator: new typeValidator_1.EnumValidator([0, 1, 2]),
    includeExcludeFilterValidator: new filtersValidator_1.IncludeExcludeFilterValidator(),
    includeExludeFilterTypeValidator: new typeValidator_1.EnumValidator([3]),
    layoutTypeValidator: new typeValidator_1.EnumValidator([0, 1, 2, 3]),
    loadQnaValidator: new qnaValidator_1.LoadQnaValidator(),
    menuExtensionValidator: new anyOfValidator_1.AnyOfValidator([new extensionsValidator_1.FlatMenuExtensionValidator(), new extensionsValidator_1.GroupedMenuExtensionValidator()]),
    menuGroupExtensionArrayValidator: new typeValidator_1.ArrayValidator([new extensionsValidator_1.MenuGroupExtensionValidator()]),
    menuGroupExtensionValidator: new extensionsValidator_1.MenuGroupExtensionValidator(),
    menuLocationValidator: new typeValidator_1.EnumValidator([0, 1]),
    notSupportedFilterTypeValidator: new typeValidator_1.EnumValidator([2]),
    notSupportedFilterValidator: new filtersValidator_1.NotSupportedFilterValidator(),
    numberArrayValidator: new typeValidator_1.NumberArrayValidator(),
    numberValidator: new typeValidator_1.NumberValidator(),
    pageLayoutValidator: new mapValidator_1.MapValidator([new typeValidator_1.StringValidator()], [new layoutValidator_1.VisualLayoutValidator()]),
    pageNavigationPaneValidator: new panesValidator_1.PageNavigationPaneValidator(),
    pageNavigationPositionValidator: new typeValidator_1.EnumValidator([0, 1]),
    pageSizeTypeValidator: new typeValidator_1.EnumValidator([0, 1, 2, 3, 4, 5]),
    pageSizeValidator: new pageValidator_1.PageSizeValidator(),
    pageValidator: new pageValidator_1.PageValidator(),
    pageViewFieldValidator: new pageValidator_1.PageViewFieldValidator(),
    pagesLayoutValidator: new mapValidator_1.MapValidator([new typeValidator_1.StringValidator()], [new layoutValidator_1.PageLayoutValidator()]),
    reportBarsValidator: new barsValidator_1.ReportBarsValidator(),
    reportPanesValidator: new panesValidator_1.ReportPanesValidator(),
    permissionsValidator: new typeValidator_1.EnumValidator([0, 1, 2, 4, 7]),
    playBookmarkRequestValidator: new bookmarkValidator_1.PlayBookmarkRequestValidator(),
    qnaInterpretInputDataValidator: new qnaValidator_1.QnaInterpretInputDataValidator(),
    qnaSettingValidator: new qnaValidator_1.QnaSettingsValidator(),
    relativeDateFilterOperatorValidator: new typeValidator_1.EnumValidator([0, 1, 2]),
    relativeDateFilterTimeUnitTypeValidator: new typeValidator_1.EnumValidator([0, 1, 2, 3, 4, 5, 6]),
    relativeDateFilterTypeValidator: new typeValidator_1.EnumValidator([4]),
    relativeDateFilterValidator: new filtersValidator_1.RelativeDateFilterValidator(),
    relativeTimeFilterTimeUnitTypeValidator: new typeValidator_1.EnumValidator([7, 8]),
    relativeTimeFilterTypeValidator: new typeValidator_1.EnumValidator([7]),
    relativeTimeFilterValidator: new filtersValidator_1.RelativeTimeFilterValidator(),
    reportCreateValidator: new reportCreateValidator_1.ReportCreateValidator(),
    reportLoadValidator: new reportLoadValidator_1.ReportLoadValidator(),
    saveAsParametersValidator: new saveAsParametersValidator_1.SaveAsParametersValidator(),
    selectionPaneValidator: new panesValidator_1.SelectionPaneValidator(),
    settingsValidator: new settingsValidator_1.SettingsValidator(),
    singleCommandSettingsValidator: new commandsSettingsValidator_1.SingleCommandSettingsValidator(),
    slicerSelectorValidator: new anyOfValidator_1.AnyOfValidator([new selectorsValidator_1.VisualSelectorValidator(), new selectorsValidator_1.SlicerTargetSelectorValidator()]),
    slicerStateValidator: new slicersValidator_1.SlicerStateValidator(),
    slicerTargetValidator: new anyOfValidator_1.AnyOfValidator([new filtersValidator_1.FilterColumnTargetValidator(), new filtersValidator_1.FilterHierarchyTargetValidator(), new filtersValidator_1.FilterMeasureTargetValidator(), new filtersValidator_1.FilterKeyColumnsTargetValidator(), new filtersValidator_1.FilterKeyHierarchyTargetValidator()]),
    slicerValidator: new slicersValidator_1.SlicerValidator(),
    stringArrayValidator: new typeValidator_1.StringArrayValidator(),
    stringValidator: new typeValidator_1.StringValidator(),
    syncSlicersPaneValidator: new panesValidator_1.SyncSlicersPaneValidator(),
    tileLoadValidator: new tileLoadValidator_1.TileLoadValidator(),
    tokenTypeValidator: new typeValidator_1.EnumValidator([0, 1]),
    topNFilterTypeValidator: new typeValidator_1.EnumValidator([5]),
    topNFilterValidator: new filtersValidator_1.TopNFilterValidator(),
    viewModeValidator: new typeValidator_1.EnumValidator([0, 1]),
    visualCommandSelectorValidator: new anyOfValidator_1.AnyOfValidator([new selectorsValidator_1.VisualSelectorValidator(), new selectorsValidator_1.VisualTypeSelectorValidator()]),
    visualHeaderSelectorValidator: new anyOfValidator_1.AnyOfValidator([new selectorsValidator_1.VisualSelectorValidator(), new selectorsValidator_1.VisualTypeSelectorValidator()]),
    visualHeaderSettingsValidator: new visualSettingsValidator_1.VisualHeaderSettingsValidator(),
    visualHeaderValidator: new visualSettingsValidator_1.VisualHeaderValidator(),
    visualHeadersValidator: new typeValidator_1.ArrayValidator([new visualSettingsValidator_1.VisualHeaderValidator()]),
    visualizationsPaneValidator: new panesValidator_1.VisualizationsPaneValidator(),
    visualLayoutValidator: new layoutValidator_1.VisualLayoutValidator(),
    visualSelectorValidator: new selectorsValidator_1.VisualSelectorValidator(),
    visualSettingsValidator: new visualSettingsValidator_1.VisualSettingsValidator(),
    visualTypeSelectorValidator: new selectorsValidator_1.VisualTypeSelectorValidator(),
};


/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionBarValidator = exports.ReportBarsValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var ReportBarsValidator = /** @class */ (function (_super) {
    __extends(ReportBarsValidator, _super);
    function ReportBarsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ReportBarsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "actionBar",
                validators: [validator_1.Validators.actionBarValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ReportBarsValidator;
}(typeValidator_1.ObjectValidator));
exports.ReportBarsValidator = ReportBarsValidator;
var ActionBarValidator = /** @class */ (function (_super) {
    __extends(ActionBarValidator, _super);
    function ActionBarValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ActionBarValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ActionBarValidator;
}(typeValidator_1.ObjectValidator));
exports.ActionBarValidator = ActionBarValidator;


/***/ }),
/* 3 */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.MultipleFieldsValidator = void 0;
var MultipleFieldsValidator = /** @class */ (function () {
    function MultipleFieldsValidator(fieldValidatorsPairs) {
        this.fieldValidatorsPairs = fieldValidatorsPairs;
    }
    MultipleFieldsValidator.prototype.validate = function (input, path, field) {
        if (!this.fieldValidatorsPairs) {
            return null;
        }
        var fieldsPath = path ? path + "." + field : field;
        for (var _i = 0, _a = this.fieldValidatorsPairs; _i < _a.length; _i++) {
            var fieldValidators = _a[_i];
            for (var _b = 0, _c = fieldValidators.validators; _b < _c.length; _b++) {
                var validator = _c[_b];
                var errors = validator.validate(input[fieldValidators.field], fieldsPath, fieldValidators.field);
                if (errors) {
                    return errors;
                }
            }
        }
        return null;
    };
    return MultipleFieldsValidator;
}());
exports.MultipleFieldsValidator = MultipleFieldsValidator;


/***/ }),
/* 4 */
/***/ (function(module, exports) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberArrayValidator = exports.BooleanArrayValidator = exports.StringArrayValidator = exports.EnumValidator = exports.SchemaValidator = exports.ValueValidator = exports.NumberValidator = exports.BooleanValidator = exports.StringValidator = exports.TypeValidator = exports.ArrayValidator = exports.ObjectValidator = void 0;
var ObjectValidator = /** @class */ (function () {
    function ObjectValidator() {
    }
    ObjectValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        if (typeof input !== "object" || Array.isArray(input)) {
            return [{
                    message: field !== undefined ? field + " must be an object" : "input must be an object",
                    path: path,
                    keyword: "type"
                }];
        }
        return null;
    };
    return ObjectValidator;
}());
exports.ObjectValidator = ObjectValidator;
var ArrayValidator = /** @class */ (function () {
    function ArrayValidator(itemValidators) {
        this.itemValidators = itemValidators;
    }
    ArrayValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        if (!(Array.isArray(input))) {
            return [{
                    message: field + " property is invalid",
                    path: (path ? path + "." : "") + field,
                    keyword: "type"
                }];
        }
        for (var i = 0; i < input.length; i++) {
            var fieldsPath = (path ? path + "." : "") + field + "." + i;
            for (var _i = 0, _a = this.itemValidators; _i < _a.length; _i++) {
                var validator = _a[_i];
                var errors = validator.validate(input[i], fieldsPath, field);
                if (errors) {
                    return [{
                            message: field + " property is invalid",
                            path: (path ? path + "." : "") + field,
                            keyword: "type"
                        }];
                }
            }
        }
        return null;
    };
    return ArrayValidator;
}());
exports.ArrayValidator = ArrayValidator;
var TypeValidator = /** @class */ (function () {
    function TypeValidator(expectedType) {
        this.expectedType = expectedType;
    }
    TypeValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        if (!(typeof input === this.expectedType)) {
            return [{
                    message: field + " must be a " + this.expectedType,
                    path: (path ? path + "." : "") + field,
                    keyword: "type"
                }];
        }
        return null;
    };
    return TypeValidator;
}());
exports.TypeValidator = TypeValidator;
var StringValidator = /** @class */ (function (_super) {
    __extends(StringValidator, _super);
    function StringValidator() {
        return _super.call(this, "string") || this;
    }
    return StringValidator;
}(TypeValidator));
exports.StringValidator = StringValidator;
var BooleanValidator = /** @class */ (function (_super) {
    __extends(BooleanValidator, _super);
    function BooleanValidator() {
        return _super.call(this, "boolean") || this;
    }
    return BooleanValidator;
}(TypeValidator));
exports.BooleanValidator = BooleanValidator;
var NumberValidator = /** @class */ (function (_super) {
    __extends(NumberValidator, _super);
    function NumberValidator() {
        return _super.call(this, "number") || this;
    }
    return NumberValidator;
}(TypeValidator));
exports.NumberValidator = NumberValidator;
var ValueValidator = /** @class */ (function () {
    function ValueValidator(possibleValues) {
        this.possibleValues = possibleValues;
    }
    ValueValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        if (this.possibleValues.indexOf(input) < 0) {
            return [{
                    message: field + " property is invalid",
                    path: (path ? path + "." : "") + field,
                    keyword: "invalid"
                }];
        }
        return null;
    };
    return ValueValidator;
}());
exports.ValueValidator = ValueValidator;
var SchemaValidator = /** @class */ (function (_super) {
    __extends(SchemaValidator, _super);
    function SchemaValidator(schemaValue) {
        var _this = _super.call(this, [schemaValue]) || this;
        _this.schemaValue = schemaValue;
        return _this;
    }
    SchemaValidator.prototype.validate = function (input, path, field) {
        return _super.prototype.validate.call(this, input, path, field);
    };
    return SchemaValidator;
}(ValueValidator));
exports.SchemaValidator = SchemaValidator;
var EnumValidator = /** @class */ (function (_super) {
    __extends(EnumValidator, _super);
    function EnumValidator(possibleValues) {
        var _this = _super.call(this) || this;
        _this.possibleValues = possibleValues;
        return _this;
    }
    EnumValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var valueValidator = new ValueValidator(this.possibleValues);
        return valueValidator.validate(input, path, field);
    };
    return EnumValidator;
}(NumberValidator));
exports.EnumValidator = EnumValidator;
var StringArrayValidator = /** @class */ (function (_super) {
    __extends(StringArrayValidator, _super);
    function StringArrayValidator() {
        return _super.call(this, [new StringValidator()]) || this;
    }
    StringArrayValidator.prototype.validate = function (input, path, field) {
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return [{
                    message: field + " must be an array of strings",
                    path: (path ? path + "." : "") + field,
                    keyword: "type"
                }];
        }
        return null;
    };
    return StringArrayValidator;
}(ArrayValidator));
exports.StringArrayValidator = StringArrayValidator;
var BooleanArrayValidator = /** @class */ (function (_super) {
    __extends(BooleanArrayValidator, _super);
    function BooleanArrayValidator() {
        return _super.call(this, [new BooleanValidator()]) || this;
    }
    BooleanArrayValidator.prototype.validate = function (input, path, field) {
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return [{
                    message: field + " must be an array of booleans",
                    path: (path ? path + "." : "") + field,
                    keyword: "type"
                }];
        }
        return null;
    };
    return BooleanArrayValidator;
}(ArrayValidator));
exports.BooleanArrayValidator = BooleanArrayValidator;
var NumberArrayValidator = /** @class */ (function (_super) {
    __extends(NumberArrayValidator, _super);
    function NumberArrayValidator() {
        return _super.call(this, [new NumberValidator()]) || this;
    }
    NumberArrayValidator.prototype.validate = function (input, path, field) {
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return [{
                    message: field + " must be an array of numbers",
                    path: (path ? path + "." : "") + field,
                    keyword: "type"
                }];
        }
        return null;
    };
    return NumberArrayValidator;
}(ArrayValidator));
exports.NumberArrayValidator = NumberArrayValidator;


/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CaptureBookmarkRequestValidator = exports.CaptureBookmarkOptionsValidator = exports.ApplyBookmarkStateRequestValidator = exports.ApplyBookmarkByNameRequestValidator = exports.AddBookmarkRequestValidator = exports.PlayBookmarkRequestValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var PlayBookmarkRequestValidator = /** @class */ (function (_super) {
    __extends(PlayBookmarkRequestValidator, _super);
    function PlayBookmarkRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PlayBookmarkRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "playMode",
                validators: [validator_1.Validators.fieldRequiredValidator, new typeValidator_1.EnumValidator([0, 1])]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return PlayBookmarkRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.PlayBookmarkRequestValidator = PlayBookmarkRequestValidator;
var AddBookmarkRequestValidator = /** @class */ (function (_super) {
    __extends(AddBookmarkRequestValidator, _super);
    function AddBookmarkRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AddBookmarkRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "state",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "displayName",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "apply",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return AddBookmarkRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.AddBookmarkRequestValidator = AddBookmarkRequestValidator;
var ApplyBookmarkByNameRequestValidator = /** @class */ (function (_super) {
    __extends(ApplyBookmarkByNameRequestValidator, _super);
    function ApplyBookmarkByNameRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ApplyBookmarkByNameRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "name",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ApplyBookmarkByNameRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.ApplyBookmarkByNameRequestValidator = ApplyBookmarkByNameRequestValidator;
var ApplyBookmarkStateRequestValidator = /** @class */ (function (_super) {
    __extends(ApplyBookmarkStateRequestValidator, _super);
    function ApplyBookmarkStateRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ApplyBookmarkStateRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "state",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ApplyBookmarkStateRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.ApplyBookmarkStateRequestValidator = ApplyBookmarkStateRequestValidator;
var CaptureBookmarkOptionsValidator = /** @class */ (function (_super) {
    __extends(CaptureBookmarkOptionsValidator, _super);
    function CaptureBookmarkOptionsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CaptureBookmarkOptionsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "personalizeVisuals",
                validators: [validator_1.Validators.booleanValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CaptureBookmarkOptionsValidator;
}(typeValidator_1.ObjectValidator));
exports.CaptureBookmarkOptionsValidator = CaptureBookmarkOptionsValidator;
var CaptureBookmarkRequestValidator = /** @class */ (function (_super) {
    __extends(CaptureBookmarkRequestValidator, _super);
    function CaptureBookmarkRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CaptureBookmarkRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "options",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.captureBookmarkOptionsValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CaptureBookmarkRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.CaptureBookmarkRequestValidator = CaptureBookmarkRequestValidator;


/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SingleCommandSettingsValidator = exports.CommandsSettingsValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var CommandsSettingsValidator = /** @class */ (function (_super) {
    __extends(CommandsSettingsValidator, _super);
    function CommandsSettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CommandsSettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "copy",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "drill",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "drillthrough",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "expandCollapse",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "exportData",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "includeExclude",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "removeVisual",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "search",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "seeData",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "sort",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
            {
                field: "spotlight",
                validators: [validator_1.Validators.singleCommandSettingsValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CommandsSettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.CommandsSettingsValidator = CommandsSettingsValidator;
var SingleCommandSettingsValidator = /** @class */ (function (_super) {
    __extends(SingleCommandSettingsValidator, _super);
    function SingleCommandSettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SingleCommandSettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "displayOption",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.commandDisplayOptionValidator]
            },
            {
                field: "selector",
                validators: [validator_1.Validators.visualCommandSelectorValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SingleCommandSettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.SingleCommandSettingsValidator = SingleCommandSettingsValidator;


/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomThemeValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var CustomThemeValidator = /** @class */ (function (_super) {
    __extends(CustomThemeValidator, _super);
    function CustomThemeValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CustomThemeValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "themeJson",
                validators: [new typeValidator_1.ObjectValidator()]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CustomThemeValidator;
}(typeValidator_1.ObjectValidator));
exports.CustomThemeValidator = CustomThemeValidator;


/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DashboardLoadValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var DashboardLoadValidator = /** @class */ (function (_super) {
    __extends(DashboardLoadValidator, _super);
    function DashboardLoadValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DashboardLoadValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "accessToken",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "id",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "groupId",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "pageView",
                validators: [validator_1.Validators.pageViewFieldValidator]
            },
            {
                field: "tokenType",
                validators: [validator_1.Validators.tokenTypeValidator]
            },
            {
                field: "embedUrl",
                validators: [validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return DashboardLoadValidator;
}(typeValidator_1.ObjectValidator));
exports.DashboardLoadValidator = DashboardLoadValidator;


/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatasetBindingValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var DatasetBindingValidator = /** @class */ (function (_super) {
    __extends(DatasetBindingValidator, _super);
    function DatasetBindingValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DatasetBindingValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "datasetId",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return DatasetBindingValidator;
}(typeValidator_1.ObjectValidator));
exports.DatasetBindingValidator = DatasetBindingValidator;


/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExportDataRequestValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var ExportDataRequestValidator = /** @class */ (function (_super) {
    __extends(ExportDataRequestValidator, _super);
    function ExportDataRequestValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ExportDataRequestValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "rows",
                validators: [new typeValidator_1.NumberValidator()]
            },
            {
                field: "exportDataType",
                validators: [new typeValidator_1.EnumValidator([0, 1])]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ExportDataRequestValidator;
}(typeValidator_1.ObjectValidator));
exports.ExportDataRequestValidator = ExportDataRequestValidator;


/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExtensionsValidator = exports.MenuGroupExtensionValidator = exports.ExtensionValidator = exports.CommandExtensionValidator = exports.ExtensionItemValidator = exports.ExtensionPointsValidator = exports.GroupedMenuExtensionValidator = exports.FlatMenuExtensionValidator = exports.MenuExtensionBaseValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var MenuExtensionBaseValidator = /** @class */ (function (_super) {
    __extends(MenuExtensionBaseValidator, _super);
    function MenuExtensionBaseValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MenuExtensionBaseValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "title",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "icon",
                validators: [validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return MenuExtensionBaseValidator;
}(typeValidator_1.ObjectValidator));
exports.MenuExtensionBaseValidator = MenuExtensionBaseValidator;
var FlatMenuExtensionValidator = /** @class */ (function (_super) {
    __extends(FlatMenuExtensionValidator, _super);
    function FlatMenuExtensionValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FlatMenuExtensionValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "menuLocation",
                validators: [validator_1.Validators.menuLocationValidator]
            },
            {
                field: "groupName",
                validators: [validator_1.Validators.fieldForbiddenValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FlatMenuExtensionValidator;
}(MenuExtensionBaseValidator));
exports.FlatMenuExtensionValidator = FlatMenuExtensionValidator;
var GroupedMenuExtensionValidator = /** @class */ (function (_super) {
    __extends(GroupedMenuExtensionValidator, _super);
    function GroupedMenuExtensionValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    GroupedMenuExtensionValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "groupName",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "menuLocation",
                validators: [validator_1.Validators.fieldForbiddenValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return GroupedMenuExtensionValidator;
}(MenuExtensionBaseValidator));
exports.GroupedMenuExtensionValidator = GroupedMenuExtensionValidator;
var ExtensionPointsValidator = /** @class */ (function (_super) {
    __extends(ExtensionPointsValidator, _super);
    function ExtensionPointsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ExtensionPointsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visualContextMenu",
                validators: [validator_1.Validators.menuExtensionValidator]
            },
            {
                field: "visualOptionsMenu",
                validators: [validator_1.Validators.menuExtensionValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ExtensionPointsValidator;
}(typeValidator_1.ObjectValidator));
exports.ExtensionPointsValidator = ExtensionPointsValidator;
var ExtensionItemValidator = /** @class */ (function (_super) {
    __extends(ExtensionItemValidator, _super);
    function ExtensionItemValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ExtensionItemValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "name",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "extend",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.extensionPointsValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ExtensionItemValidator;
}(typeValidator_1.ObjectValidator));
exports.ExtensionItemValidator = ExtensionItemValidator;
var CommandExtensionValidator = /** @class */ (function (_super) {
    __extends(CommandExtensionValidator, _super);
    function CommandExtensionValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CommandExtensionValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "title",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "icon",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "selector",
                validators: [validator_1.Validators.commandExtensionSelectorValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CommandExtensionValidator;
}(ExtensionItemValidator));
exports.CommandExtensionValidator = CommandExtensionValidator;
var ExtensionValidator = /** @class */ (function (_super) {
    __extends(ExtensionValidator, _super);
    function ExtensionValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ExtensionValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "command",
                validators: [validator_1.Validators.commandExtensionValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ExtensionValidator;
}(typeValidator_1.ObjectValidator));
exports.ExtensionValidator = ExtensionValidator;
var MenuGroupExtensionValidator = /** @class */ (function (_super) {
    __extends(MenuGroupExtensionValidator, _super);
    function MenuGroupExtensionValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MenuGroupExtensionValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "name",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "title",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "menuLocation",
                validators: [validator_1.Validators.menuLocationValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return MenuGroupExtensionValidator;
}(typeValidator_1.ObjectValidator));
exports.MenuGroupExtensionValidator = MenuGroupExtensionValidator;
var ExtensionsValidator = /** @class */ (function (_super) {
    __extends(ExtensionsValidator, _super);
    function ExtensionsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ExtensionsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "commands",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.commandExtensionArrayValidator]
            },
            {
                field: "groups",
                validators: [validator_1.Validators.menuGroupExtensionArrayValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ExtensionsValidator;
}(typeValidator_1.ObjectValidator));
exports.ExtensionsValidator = ExtensionsValidator;


/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConditionItemValidator = exports.FilterValidator = exports.IncludeExcludeFilterValidator = exports.NotSupportedFilterValidator = exports.TopNFilterValidator = exports.RelativeTimeFilterValidator = exports.RelativeDateFilterValidator = exports.AdvancedFilterValidator = exports.BasicFilterValidator = exports.FilterMeasureTargetValidator = exports.FilterKeyHierarchyTargetValidator = exports.FilterHierarchyTargetValidator = exports.FilterKeyColumnsTargetValidator = exports.FilterColumnTargetValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var FilterColumnTargetValidator = /** @class */ (function (_super) {
    __extends(FilterColumnTargetValidator, _super);
    function FilterColumnTargetValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterColumnTargetValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "table",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "column",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FilterColumnTargetValidator;
}(typeValidator_1.ObjectValidator));
exports.FilterColumnTargetValidator = FilterColumnTargetValidator;
var FilterKeyColumnsTargetValidator = /** @class */ (function (_super) {
    __extends(FilterKeyColumnsTargetValidator, _super);
    function FilterKeyColumnsTargetValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterKeyColumnsTargetValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "keys",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringArrayValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FilterKeyColumnsTargetValidator;
}(FilterColumnTargetValidator));
exports.FilterKeyColumnsTargetValidator = FilterKeyColumnsTargetValidator;
var FilterHierarchyTargetValidator = /** @class */ (function (_super) {
    __extends(FilterHierarchyTargetValidator, _super);
    function FilterHierarchyTargetValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterHierarchyTargetValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "table",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "hierarchy",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "hierarchyLevel",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FilterHierarchyTargetValidator;
}(typeValidator_1.ObjectValidator));
exports.FilterHierarchyTargetValidator = FilterHierarchyTargetValidator;
var FilterKeyHierarchyTargetValidator = /** @class */ (function (_super) {
    __extends(FilterKeyHierarchyTargetValidator, _super);
    function FilterKeyHierarchyTargetValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterKeyHierarchyTargetValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "keys",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringArrayValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FilterKeyHierarchyTargetValidator;
}(FilterHierarchyTargetValidator));
exports.FilterKeyHierarchyTargetValidator = FilterKeyHierarchyTargetValidator;
var FilterMeasureTargetValidator = /** @class */ (function (_super) {
    __extends(FilterMeasureTargetValidator, _super);
    function FilterMeasureTargetValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterMeasureTargetValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "table",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "measure",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FilterMeasureTargetValidator;
}(typeValidator_1.ObjectValidator));
exports.FilterMeasureTargetValidator = FilterMeasureTargetValidator;
var BasicFilterValidator = /** @class */ (function (_super) {
    __extends(BasicFilterValidator, _super);
    function BasicFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BasicFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "operator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "values",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.anyArrayValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.basicFilterTypeValidator]
            },
            {
                field: "requireSingleSelection",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return BasicFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.BasicFilterValidator = BasicFilterValidator;
var AdvancedFilterValidator = /** @class */ (function (_super) {
    __extends(AdvancedFilterValidator, _super);
    function AdvancedFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AdvancedFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "logicalOperator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "conditions",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterConditionsValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.advancedFilterTypeValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return AdvancedFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.AdvancedFilterValidator = AdvancedFilterValidator;
var RelativeDateFilterValidator = /** @class */ (function (_super) {
    __extends(RelativeDateFilterValidator, _super);
    function RelativeDateFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    RelativeDateFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "operator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.relativeDateFilterOperatorValidator]
            },
            {
                field: "timeUnitsCount",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.numberValidator]
            },
            {
                field: "timeUnitType",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.relativeDateFilterTimeUnitTypeValidator]
            },
            {
                field: "includeToday",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.booleanValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.relativeDateFilterTypeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return RelativeDateFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.RelativeDateFilterValidator = RelativeDateFilterValidator;
var RelativeTimeFilterValidator = /** @class */ (function (_super) {
    __extends(RelativeTimeFilterValidator, _super);
    function RelativeTimeFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    RelativeTimeFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "operator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.relativeDateFilterOperatorValidator]
            },
            {
                field: "timeUnitsCount",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.numberValidator]
            },
            {
                field: "timeUnitType",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.relativeTimeFilterTimeUnitTypeValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.relativeTimeFilterTypeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return RelativeTimeFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.RelativeTimeFilterValidator = RelativeTimeFilterValidator;
var TopNFilterValidator = /** @class */ (function (_super) {
    __extends(TopNFilterValidator, _super);
    function TopNFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TopNFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "operator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "itemCount",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.numberValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.topNFilterTypeValidator]
            },
            {
                field: "orderBy",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return TopNFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.TopNFilterValidator = TopNFilterValidator;
var NotSupportedFilterValidator = /** @class */ (function (_super) {
    __extends(NotSupportedFilterValidator, _super);
    function NotSupportedFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    NotSupportedFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.filterTargetValidator]
            },
            {
                field: "message",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "notSupportedTypeName",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.notSupportedFilterTypeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return NotSupportedFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.NotSupportedFilterValidator = NotSupportedFilterValidator;
var IncludeExcludeFilterValidator = /** @class */ (function (_super) {
    __extends(IncludeExcludeFilterValidator, _super);
    function IncludeExcludeFilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    IncludeExcludeFilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.filterTargetValidator]
            },
            {
                field: "isExclude",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.booleanValidator]
            },
            {
                field: "values",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.anyArrayValidator]
            },
            {
                field: "filterType",
                validators: [validator_1.Validators.includeExludeFilterTypeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return IncludeExcludeFilterValidator;
}(typeValidator_1.ObjectValidator));
exports.IncludeExcludeFilterValidator = IncludeExcludeFilterValidator;
var FilterValidator = /** @class */ (function (_super) {
    __extends(FilterValidator, _super);
    function FilterValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FilterValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        return validator_1.Validators.anyFilterValidator.validate(input, path, field);
    };
    return FilterValidator;
}(typeValidator_1.ObjectValidator));
exports.FilterValidator = FilterValidator;
var ConditionItemValidator = /** @class */ (function (_super) {
    __extends(ConditionItemValidator, _super);
    function ConditionItemValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ConditionItemValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "value",
                validators: [validator_1.Validators.anyValueValidator]
            },
            {
                field: "operator",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ConditionItemValidator;
}(typeValidator_1.ObjectValidator));
exports.ConditionItemValidator = ConditionItemValidator;


/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageLayoutValidator = exports.DisplayStateValidator = exports.VisualLayoutValidator = exports.CustomLayoutValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var CustomLayoutValidator = /** @class */ (function (_super) {
    __extends(CustomLayoutValidator, _super);
    function CustomLayoutValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CustomLayoutValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "pageSize",
                validators: [validator_1.Validators.pageSizeValidator]
            },
            {
                field: "displayOption",
                validators: [validator_1.Validators.customLayoutDisplayOptionValidator]
            },
            {
                field: "pagesLayout",
                validators: [validator_1.Validators.pagesLayoutValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CustomLayoutValidator;
}(typeValidator_1.ObjectValidator));
exports.CustomLayoutValidator = CustomLayoutValidator;
var VisualLayoutValidator = /** @class */ (function (_super) {
    __extends(VisualLayoutValidator, _super);
    function VisualLayoutValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualLayoutValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "x",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "y",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "z",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "width",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "height",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "displayState",
                validators: [validator_1.Validators.displayStateValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualLayoutValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualLayoutValidator = VisualLayoutValidator;
var DisplayStateValidator = /** @class */ (function (_super) {
    __extends(DisplayStateValidator, _super);
    function DisplayStateValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DisplayStateValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "mode",
                validators: [validator_1.Validators.displayStateModeValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return DisplayStateValidator;
}(typeValidator_1.ObjectValidator));
exports.DisplayStateValidator = DisplayStateValidator;
var PageLayoutValidator = /** @class */ (function (_super) {
    __extends(PageLayoutValidator, _super);
    function PageLayoutValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageLayoutValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visualsLayout",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.pageLayoutValidator]
            },
            {
                field: "defaultLayout",
                validators: [validator_1.Validators.visualLayoutValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return PageLayoutValidator;
}(typeValidator_1.ObjectValidator));
exports.PageLayoutValidator = PageLayoutValidator;


/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageViewFieldValidator = exports.PageValidator = exports.CustomPageSizeValidator = exports.PageSizeValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var PageSizeValidator = /** @class */ (function (_super) {
    __extends(PageSizeValidator, _super);
    function PageSizeValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageSizeValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "type",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.pageSizeTypeValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return PageSizeValidator;
}(typeValidator_1.ObjectValidator));
exports.PageSizeValidator = PageSizeValidator;
var CustomPageSizeValidator = /** @class */ (function (_super) {
    __extends(CustomPageSizeValidator, _super);
    function CustomPageSizeValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CustomPageSizeValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "width",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "height",
                validators: [validator_1.Validators.numberValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return CustomPageSizeValidator;
}(PageSizeValidator));
exports.CustomPageSizeValidator = CustomPageSizeValidator;
var PageValidator = /** @class */ (function (_super) {
    __extends(PageValidator, _super);
    function PageValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "name",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return PageValidator;
}(typeValidator_1.ObjectValidator));
exports.PageValidator = PageValidator;
var PageViewFieldValidator = /** @class */ (function (_super) {
    __extends(PageViewFieldValidator, _super);
    function PageViewFieldValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageViewFieldValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var possibleValues = ["actualSize", "fitToWidth", "oneColumn"];
        if (possibleValues.indexOf(input) < 0) {
            return [{
                    message: "pageView must be a string with one of the following values: \"actualSize\", \"fitToWidth\", \"oneColumn\""
                }];
        }
        return null;
    };
    return PageViewFieldValidator;
}(typeValidator_1.StringValidator));
exports.PageViewFieldValidator = PageViewFieldValidator;


/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.VisualizationsPaneValidator = exports.SyncSlicersPaneValidator = exports.SelectionPaneValidator = exports.PageNavigationPaneValidator = exports.FiltersPaneValidator = exports.FieldsPaneValidator = exports.BookmarksPaneValidator = exports.ReportPanesValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var ReportPanesValidator = /** @class */ (function (_super) {
    __extends(ReportPanesValidator, _super);
    function ReportPanesValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ReportPanesValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "bookmarks",
                validators: [validator_1.Validators.bookmarksPaneValidator]
            },
            {
                field: "fields",
                validators: [validator_1.Validators.fieldsPaneValidator]
            },
            {
                field: "filters",
                validators: [validator_1.Validators.filtersPaneValidator]
            },
            {
                field: "pageNavigation",
                validators: [validator_1.Validators.pageNavigationPaneValidator]
            },
            {
                field: "selection",
                validators: [validator_1.Validators.selectionPaneValidator]
            },
            {
                field: "syncSlicers",
                validators: [validator_1.Validators.syncSlicersPaneValidator]
            },
            {
                field: "visualizations",
                validators: [validator_1.Validators.visualizationsPaneValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ReportPanesValidator;
}(typeValidator_1.ObjectValidator));
exports.ReportPanesValidator = ReportPanesValidator;
var BookmarksPaneValidator = /** @class */ (function (_super) {
    __extends(BookmarksPaneValidator, _super);
    function BookmarksPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BookmarksPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return BookmarksPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.BookmarksPaneValidator = BookmarksPaneValidator;
var FieldsPaneValidator = /** @class */ (function (_super) {
    __extends(FieldsPaneValidator, _super);
    function FieldsPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FieldsPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "expanded",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FieldsPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.FieldsPaneValidator = FieldsPaneValidator;
var FiltersPaneValidator = /** @class */ (function (_super) {
    __extends(FiltersPaneValidator, _super);
    function FiltersPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    FiltersPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "expanded",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return FiltersPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.FiltersPaneValidator = FiltersPaneValidator;
var PageNavigationPaneValidator = /** @class */ (function (_super) {
    __extends(PageNavigationPaneValidator, _super);
    function PageNavigationPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageNavigationPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "position",
                validators: [validator_1.Validators.pageNavigationPositionValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return PageNavigationPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.PageNavigationPaneValidator = PageNavigationPaneValidator;
var SelectionPaneValidator = /** @class */ (function (_super) {
    __extends(SelectionPaneValidator, _super);
    function SelectionPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SelectionPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SelectionPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.SelectionPaneValidator = SelectionPaneValidator;
var SyncSlicersPaneValidator = /** @class */ (function (_super) {
    __extends(SyncSlicersPaneValidator, _super);
    function SyncSlicersPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SyncSlicersPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SyncSlicersPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.SyncSlicersPaneValidator = SyncSlicersPaneValidator;
var VisualizationsPaneValidator = /** @class */ (function (_super) {
    __extends(VisualizationsPaneValidator, _super);
    function VisualizationsPaneValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualizationsPaneValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "expanded",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualizationsPaneValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualizationsPaneValidator = VisualizationsPaneValidator;


/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.QnaInterpretInputDataValidator = exports.QnaSettingsValidator = exports.LoadQnaValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var LoadQnaValidator = /** @class */ (function (_super) {
    __extends(LoadQnaValidator, _super);
    function LoadQnaValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LoadQnaValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "accessToken",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "datasetIds",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringArrayValidator]
            },
            {
                field: "question",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "viewMode",
                validators: [validator_1.Validators.viewModeValidator]
            },
            {
                field: "settings",
                validators: [validator_1.Validators.qnaSettingValidator]
            },
            {
                field: "tokenType",
                validators: [validator_1.Validators.tokenTypeValidator]
            },
            {
                field: "groupId",
                validators: [validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return LoadQnaValidator;
}(typeValidator_1.ObjectValidator));
exports.LoadQnaValidator = LoadQnaValidator;
var QnaSettingsValidator = /** @class */ (function (_super) {
    __extends(QnaSettingsValidator, _super);
    function QnaSettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    QnaSettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "filterPaneEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "hideErrors",
                validators: [validator_1.Validators.booleanValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return QnaSettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.QnaSettingsValidator = QnaSettingsValidator;
var QnaInterpretInputDataValidator = /** @class */ (function (_super) {
    __extends(QnaInterpretInputDataValidator, _super);
    function QnaInterpretInputDataValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    QnaInterpretInputDataValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "datasetIds",
                validators: [validator_1.Validators.stringArrayValidator]
            },
            {
                field: "question",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return QnaInterpretInputDataValidator;
}(typeValidator_1.ObjectValidator));
exports.QnaInterpretInputDataValidator = QnaInterpretInputDataValidator;


/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReportCreateValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var ReportCreateValidator = /** @class */ (function (_super) {
    __extends(ReportCreateValidator, _super);
    function ReportCreateValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ReportCreateValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "accessToken",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "datasetId",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "groupId",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "tokenType",
                validators: [validator_1.Validators.tokenTypeValidator]
            },
            {
                field: "theme",
                validators: [validator_1.Validators.customThemeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ReportCreateValidator;
}(typeValidator_1.ObjectValidator));
exports.ReportCreateValidator = ReportCreateValidator;


/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReportLoadValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var ReportLoadValidator = /** @class */ (function (_super) {
    __extends(ReportLoadValidator, _super);
    function ReportLoadValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ReportLoadValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "accessToken",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "id",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "groupId",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "settings",
                validators: [validator_1.Validators.settingsValidator]
            },
            {
                field: "pageName",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "filters",
                validators: [validator_1.Validators.filtersArrayValidator]
            },
            {
                field: "permissions",
                validators: [validator_1.Validators.permissionsValidator]
            },
            {
                field: "viewMode",
                validators: [validator_1.Validators.viewModeValidator]
            },
            {
                field: "tokenType",
                validators: [validator_1.Validators.tokenTypeValidator]
            },
            {
                field: "bookmark",
                validators: [validator_1.Validators.applyBookmarkValidator]
            },
            {
                field: "theme",
                validators: [validator_1.Validators.customThemeValidator]
            },
            {
                field: "embedUrl",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "datasetBinding",
                validators: [validator_1.Validators.datasetBindingValidator]
            },
            {
                field: "contrastMode",
                validators: [validator_1.Validators.contrastModeValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return ReportLoadValidator;
}(typeValidator_1.ObjectValidator));
exports.ReportLoadValidator = ReportLoadValidator;


/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SaveAsParametersValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var SaveAsParametersValidator = /** @class */ (function (_super) {
    __extends(SaveAsParametersValidator, _super);
    function SaveAsParametersValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SaveAsParametersValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "name",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SaveAsParametersValidator;
}(typeValidator_1.ObjectValidator));
exports.SaveAsParametersValidator = SaveAsParametersValidator;


/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlicerTargetSelectorValidator = exports.VisualTypeSelectorValidator = exports.VisualSelectorValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var typeValidator_2 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var VisualSelectorValidator = /** @class */ (function (_super) {
    __extends(VisualSelectorValidator, _super);
    function VisualSelectorValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualSelectorValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                // Not required for this selector only - Backward compatibility
                field: "$schema",
                validators: [validator_1.Validators.stringValidator, new typeValidator_2.SchemaValidator("http://powerbi.com/product/schema#visualSelector")]
            },
            {
                field: "visualName",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualSelectorValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualSelectorValidator = VisualSelectorValidator;
var VisualTypeSelectorValidator = /** @class */ (function (_super) {
    __extends(VisualTypeSelectorValidator, _super);
    function VisualTypeSelectorValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualTypeSelectorValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "$schema",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator, new typeValidator_2.SchemaValidator("http://powerbi.com/product/schema#visualTypeSelector")]
            },
            {
                field: "visualType",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualTypeSelectorValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualTypeSelectorValidator = VisualTypeSelectorValidator;
var SlicerTargetSelectorValidator = /** @class */ (function (_super) {
    __extends(SlicerTargetSelectorValidator, _super);
    function SlicerTargetSelectorValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SlicerTargetSelectorValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "$schema",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator, new typeValidator_2.SchemaValidator("http://powerbi.com/product/schema#slicerTargetSelector")]
            },
            {
                field: "target",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.slicerTargetValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SlicerTargetSelectorValidator;
}(typeValidator_1.ObjectValidator));
exports.SlicerTargetSelectorValidator = SlicerTargetSelectorValidator;


/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingsValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var SettingsValidator = /** @class */ (function (_super) {
    __extends(SettingsValidator, _super);
    function SettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "filterPaneEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "navContentPaneEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "bookmarksPaneEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "useCustomSaveAsDialog",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "extensions",
                validators: [validator_1.Validators.extensionsValidator]
            },
            {
                field: "layoutType",
                validators: [validator_1.Validators.layoutTypeValidator]
            },
            {
                field: "customLayout",
                validators: [validator_1.Validators.customLayoutValidator]
            },
            {
                field: "background",
                validators: [validator_1.Validators.backgroundValidator]
            },
            {
                field: "visualSettings",
                validators: [validator_1.Validators.visualSettingsValidator]
            },
            {
                field: "hideErrors",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "commands",
                validators: [validator_1.Validators.commandsSettingsArrayValidator]
            },
            {
                field: "hyperlinkClickBehavior",
                validators: [validator_1.Validators.hyperlinkClickBehaviorValidator]
            },
            {
                field: "bars",
                validators: [validator_1.Validators.reportBarsValidator]
            },
            {
                field: "panes",
                validators: [validator_1.Validators.reportPanesValidator]
            },
            {
                field: "personalBookmarksEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "persistentFiltersEnabled",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "visualRenderedEvents",
                validators: [validator_1.Validators.booleanValidator]
            },
            {
                field: "authoringHintsEnabled",
                validators: [validator_1.Validators.booleanValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.SettingsValidator = SettingsValidator;


/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SlicerStateValidator = exports.SlicerValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var SlicerValidator = /** @class */ (function (_super) {
    __extends(SlicerValidator, _super);
    function SlicerValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SlicerValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "selector",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.slicerSelectorValidator]
            },
            {
                field: "state",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.slicerStateValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SlicerValidator;
}(typeValidator_1.ObjectValidator));
exports.SlicerValidator = SlicerValidator;
var SlicerStateValidator = /** @class */ (function (_super) {
    __extends(SlicerStateValidator, _super);
    function SlicerStateValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SlicerStateValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "filters",
                validators: [validator_1.Validators.filtersArrayValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return SlicerStateValidator;
}(typeValidator_1.ObjectValidator));
exports.SlicerStateValidator = SlicerStateValidator;


/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TileLoadValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var TileLoadValidator = /** @class */ (function (_super) {
    __extends(TileLoadValidator, _super);
    function TileLoadValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TileLoadValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "accessToken",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "id",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "dashboardId",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.stringValidator]
            },
            {
                field: "groupId",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "pageView",
                validators: [validator_1.Validators.stringValidator]
            },
            {
                field: "tokenType",
                validators: [validator_1.Validators.tokenTypeValidator]
            },
            {
                field: "width",
                validators: [validator_1.Validators.numberValidator]
            },
            {
                field: "height",
                validators: [validator_1.Validators.numberValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return TileLoadValidator;
}(typeValidator_1.ObjectValidator));
exports.TileLoadValidator = TileLoadValidator;


/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.VisualHeaderValidator = exports.VisualHeaderSettingsValidator = exports.VisualSettingsValidator = void 0;
var multipleFieldsValidator_1 = __webpack_require__(3);
var typeValidator_1 = __webpack_require__(4);
var validator_1 = __webpack_require__(1);
var VisualSettingsValidator = /** @class */ (function (_super) {
    __extends(VisualSettingsValidator, _super);
    function VisualSettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualSettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visualHeaders",
                validators: [validator_1.Validators.visualHeadersValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualSettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualSettingsValidator = VisualSettingsValidator;
var VisualHeaderSettingsValidator = /** @class */ (function (_super) {
    __extends(VisualHeaderSettingsValidator, _super);
    function VisualHeaderSettingsValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualHeaderSettingsValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "visible",
                validators: [validator_1.Validators.booleanValidator]
            }
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualHeaderSettingsValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualHeaderSettingsValidator = VisualHeaderSettingsValidator;
var VisualHeaderValidator = /** @class */ (function (_super) {
    __extends(VisualHeaderValidator, _super);
    function VisualHeaderValidator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VisualHeaderValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        var fields = [
            {
                field: "settings",
                validators: [validator_1.Validators.fieldRequiredValidator, validator_1.Validators.visualHeaderSettingsValidator]
            },
            {
                field: "selector",
                validators: [validator_1.Validators.visualHeaderSelectorValidator]
            },
        ];
        var multipleFieldsValidator = new multipleFieldsValidator_1.MultipleFieldsValidator(fields);
        return multipleFieldsValidator.validate(input, path, field);
    };
    return VisualHeaderValidator;
}(typeValidator_1.ObjectValidator));
exports.VisualHeaderValidator = VisualHeaderValidator;


/***/ }),
/* 25 */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.AnyOfValidator = void 0;
var AnyOfValidator = /** @class */ (function () {
    function AnyOfValidator(validators) {
        this.validators = validators;
    }
    AnyOfValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var valid = false;
        for (var _i = 0, _a = this.validators; _i < _a.length; _i++) {
            var validator = _a[_i];
            var errors = validator.validate(input, path, field);
            if (!errors) {
                valid = true;
                break;
            }
        }
        if (!valid) {
            return [{
                    message: field + " property is invalid",
                    path: (path ? path + "." : "") + field,
                    keyword: "invalid"
                }];
        }
        return null;
    };
    return AnyOfValidator;
}());
exports.AnyOfValidator = AnyOfValidator;


/***/ }),
/* 26 */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldForbiddenValidator = void 0;
var FieldForbiddenValidator = /** @class */ (function () {
    function FieldForbiddenValidator() {
    }
    FieldForbiddenValidator.prototype.validate = function (input, path, field) {
        if (input !== undefined) {
            return [{
                    message: field + " is forbidden",
                    path: (path ? path + "." : "") + field,
                    keyword: "forbidden"
                }];
        }
        return null;
    };
    return FieldForbiddenValidator;
}());
exports.FieldForbiddenValidator = FieldForbiddenValidator;


/***/ }),
/* 27 */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldRequiredValidator = void 0;
var FieldRequiredValidator = /** @class */ (function () {
    function FieldRequiredValidator() {
    }
    FieldRequiredValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return [{
                    message: field + " is required",
                    path: (path ? path + "." : "") + field,
                    keyword: "required"
                }];
        }
        return null;
    };
    return FieldRequiredValidator;
}());
exports.FieldRequiredValidator = FieldRequiredValidator;


/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapValidator = void 0;
var typeValidator_1 = __webpack_require__(4);
var MapValidator = /** @class */ (function (_super) {
    __extends(MapValidator, _super);
    function MapValidator(keyValidators, valueValidators) {
        var _this = _super.call(this) || this;
        _this.keyValidators = keyValidators;
        _this.valueValidators = valueValidators;
        return _this;
    }
    MapValidator.prototype.validate = function (input, path, field) {
        if (input == null) {
            return null;
        }
        var errors = _super.prototype.validate.call(this, input, path, field);
        if (errors) {
            return errors;
        }
        for (var key in input) {
            if (input.hasOwnProperty(key)) {
                var fieldsPath = (path ? path + "." : "") + field + "." + key;
                for (var _i = 0, _a = this.keyValidators; _i < _a.length; _i++) {
                    var keyValidator = _a[_i];
                    errors = keyValidator.validate(key, fieldsPath, field);
                    if (errors) {
                        return errors;
                    }
                }
                for (var _b = 0, _c = this.valueValidators; _b < _c.length; _b++) {
                    var valueValidator = _c[_b];
                    errors = valueValidator.validate(input[key], fieldsPath, field);
                    if (errors) {
                        return errors;
                    }
                }
            }
        }
        return null;
    };
    return MapValidator;
}(typeValidator_1.ObjectValidator));
exports.MapValidator = MapValidator;


/***/ })
/******/ ]);
});


/***/ }),

/***/ "./node_modules/powerbi-router/dist/router.js":
/*!****************************************************!*\
  !*** ./node_modules/powerbi-router/dist/router.js ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*! powerbi-router v0.1.5 | (c) 2016 Microsoft Corporation MIT */
(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";
	var RouteRecognizer = __webpack_require__(1);
	var Router = (function () {
	    function Router(handlers) {
	        this.handlers = handlers;
	        /**
	         * TODO: look at generating the router dynamically based on list of supported http methods
	         * instead of hardcoding the creation of these and the methods.
	         */
	        this.getRouteRecognizer = new RouteRecognizer();
	        this.patchRouteRecognizer = new RouteRecognizer();
	        this.postRouteRecognizer = new RouteRecognizer();
	        this.putRouteRecognizer = new RouteRecognizer();
	        this.deleteRouteRecognizer = new RouteRecognizer();
	    }
	    Router.prototype.get = function (url, handler) {
	        this.registerHandler(this.getRouteRecognizer, "GET", url, handler);
	        return this;
	    };
	    Router.prototype.patch = function (url, handler) {
	        this.registerHandler(this.patchRouteRecognizer, "PATCH", url, handler);
	        return this;
	    };
	    Router.prototype.post = function (url, handler) {
	        this.registerHandler(this.postRouteRecognizer, "POST", url, handler);
	        return this;
	    };
	    Router.prototype.put = function (url, handler) {
	        this.registerHandler(this.putRouteRecognizer, "PUT", url, handler);
	        return this;
	    };
	    Router.prototype.delete = function (url, handler) {
	        this.registerHandler(this.deleteRouteRecognizer, "DELETE", url, handler);
	        return this;
	    };
	    /**
	     * TODO: This method could use some refactoring.  There is conflict of interest between keeping clean separation of test and handle method
	     * Test method only returns boolean indicating if request can be handled, and handle method has opportunity to modify response and return promise of it.
	     * In the case of the router with route-recognizer where handlers are associated with routes, this already guarantees that only one handler is selected and makes the test method feel complicated
	     * Will leave as is an investigate cleaner ways at later time.
	     */
	    Router.prototype.registerHandler = function (routeRecognizer, method, url, handler) {
	        var routeRecognizerHandler = function (request) {
	            var response = new Response();
	            return Promise.resolve(handler(request, response))
	                .then(function (x) { return response; });
	        };
	        routeRecognizer.add([
	            { path: url, handler: routeRecognizerHandler }
	        ]);
	        var internalHandler = {
	            test: function (request) {
	                if (request.method !== method) {
	                    return false;
	                }
	                var matchingRoutes = routeRecognizer.recognize(request.url);
	                if (matchingRoutes === undefined) {
	                    return false;
	                }
	                /**
	                 * Copy parameters from recognized route to the request so they can be used within the handler function
	                 * This isn't ideal because it is side affect which modifies the request instead of strictly testing for true or false
	                 * but I don't see a better place to put this.  If we move it between the call to test and the handle it becomes part of the window post message proxy
	                 * even though it's responsibility is related to routing.
	                 */
	                var route = matchingRoutes[0];
	                request.params = route.params;
	                request.queryParams = matchingRoutes.queryParams;
	                request.handler = route.handler;
	                return true;
	            },
	            handle: function (request) {
	                return request.handler(request);
	            }
	        };
	        this.handlers.addHandler(internalHandler);
	    };
	    return Router;
	}());
	exports.Router = Router;
	var Response = (function () {
	    function Response() {
	        this.statusCode = 200;
	        this.headers = {};
	        this.body = null;
	    }
	    Response.prototype.send = function (statusCode, body) {
	        this.statusCode = statusCode;
	        this.body = body;
	    };
	    return Response;
	}());
	exports.Response = Response;


/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {(function() {
	    "use strict";
	    function $$route$recognizer$dsl$$Target(path, matcher, delegate) {
	      this.path = path;
	      this.matcher = matcher;
	      this.delegate = delegate;
	    }
	
	    $$route$recognizer$dsl$$Target.prototype = {
	      to: function(target, callback) {
	        var delegate = this.delegate;
	
	        if (delegate && delegate.willAddRoute) {
	          target = delegate.willAddRoute(this.matcher.target, target);
	        }
	
	        this.matcher.add(this.path, target);
	
	        if (callback) {
	          if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); }
	          this.matcher.addChild(this.path, target, callback, this.delegate);
	        }
	        return this;
	      }
	    };
	
	    function $$route$recognizer$dsl$$Matcher(target) {
	      this.routes = {};
	      this.children = {};
	      this.target = target;
	    }
	
	    $$route$recognizer$dsl$$Matcher.prototype = {
	      add: function(path, handler) {
	        this.routes[path] = handler;
	      },
	
	      addChild: function(path, target, callback, delegate) {
	        var matcher = new $$route$recognizer$dsl$$Matcher(target);
	        this.children[path] = matcher;
	
	        var match = $$route$recognizer$dsl$$generateMatch(path, matcher, delegate);
	
	        if (delegate && delegate.contextEntered) {
	          delegate.contextEntered(target, match);
	        }
	
	        callback(match);
	      }
	    };
	
	    function $$route$recognizer$dsl$$generateMatch(startingPath, matcher, delegate) {
	      return function(path, nestedCallback) {
	        var fullPath = startingPath + path;
	
	        if (nestedCallback) {
	          nestedCallback($$route$recognizer$dsl$$generateMatch(fullPath, matcher, delegate));
	        } else {
	          return new $$route$recognizer$dsl$$Target(startingPath + path, matcher, delegate);
	        }
	      };
	    }
	
	    function $$route$recognizer$dsl$$addRoute(routeArray, path, handler) {
	      var len = 0;
	      for (var i=0; i<routeArray.length; i++) {
	        len += routeArray[i].path.length;
	      }
	
	      path = path.substr(len);
	      var route = { path: path, handler: handler };
	      routeArray.push(route);
	    }
	
	    function $$route$recognizer$dsl$$eachRoute(baseRoute, matcher, callback, binding) {
	      var routes = matcher.routes;
	
	      for (var path in routes) {
	        if (routes.hasOwnProperty(path)) {
	          var routeArray = baseRoute.slice();
	          $$route$recognizer$dsl$$addRoute(routeArray, path, routes[path]);
	
	          if (matcher.children[path]) {
	            $$route$recognizer$dsl$$eachRoute(routeArray, matcher.children[path], callback, binding);
	          } else {
	            callback.call(binding, routeArray);
	          }
	        }
	      }
	    }
	
	    var $$route$recognizer$dsl$$default = function(callback, addRouteCallback) {
	      var matcher = new $$route$recognizer$dsl$$Matcher();
	
	      callback($$route$recognizer$dsl$$generateMatch("", matcher, this.delegate));
	
	      $$route$recognizer$dsl$$eachRoute([], matcher, function(route) {
	        if (addRouteCallback) { addRouteCallback(this, route); }
	        else { this.add(route); }
	      }, this);
	    };
	
	    var $$route$recognizer$$specials = [
	      '/', '.', '*', '+', '?', '|',
	      '(', ')', '[', ']', '{', '}', '\\'
	    ];
	
	    var $$route$recognizer$$escapeRegex = new RegExp('(\\' + $$route$recognizer$$specials.join('|\\') + ')', 'g');
	
	    function $$route$recognizer$$isArray(test) {
	      return Object.prototype.toString.call(test) === "[object Array]";
	    }
	
	    // A Segment represents a segment in the original route description.
	    // Each Segment type provides an `eachChar` and `regex` method.
	    //
	    // The `eachChar` method invokes the callback with one or more character
	    // specifications. A character specification consumes one or more input
	    // characters.
	    //
	    // The `regex` method returns a regex fragment for the segment. If the
	    // segment is a dynamic of star segment, the regex fragment also includes
	    // a capture.
	    //
	    // A character specification contains:
	    //
	    // * `validChars`: a String with a list of all valid characters, or
	    // * `invalidChars`: a String with a list of all invalid characters
	    // * `repeat`: true if the character specification can repeat
	
	    function $$route$recognizer$$StaticSegment(string) { this.string = string; }
	    $$route$recognizer$$StaticSegment.prototype = {
	      eachChar: function(currentState) {
	        var string = this.string, ch;
	
	        for (var i=0; i<string.length; i++) {
	          ch = string.charAt(i);
	          currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: ch });
	        }
	
	        return currentState;
	      },
	
	      regex: function() {
	        return this.string.replace($$route$recognizer$$escapeRegex, '\\$1');
	      },
	
	      generate: function() {
	        return this.string;
	      }
	    };
	
	    function $$route$recognizer$$DynamicSegment(name) { this.name = name; }
	    $$route$recognizer$$DynamicSegment.prototype = {
	      eachChar: function(currentState) {
	        return currentState.put({ invalidChars: "/", repeat: true, validChars: undefined });
	      },
	
	      regex: function() {
	        return "([^/]+)";
	      },
	
	      generate: function(params) {
	        return params[this.name];
	      }
	    };
	
	    function $$route$recognizer$$StarSegment(name) { this.name = name; }
	    $$route$recognizer$$StarSegment.prototype = {
	      eachChar: function(currentState) {
	        return currentState.put({ invalidChars: "", repeat: true, validChars: undefined });
	      },
	
	      regex: function() {
	        return "(.+)";
	      },
	
	      generate: function(params) {
	        return params[this.name];
	      }
	    };
	
	    function $$route$recognizer$$EpsilonSegment() {}
	    $$route$recognizer$$EpsilonSegment.prototype = {
	      eachChar: function(currentState) {
	        return currentState;
	      },
	      regex: function() { return ""; },
	      generate: function() { return ""; }
	    };
	
	    function $$route$recognizer$$parse(route, names, specificity) {
	      // normalize route as not starting with a "/". Recognition will
	      // also normalize.
	      if (route.charAt(0) === "/") { route = route.substr(1); }
	
	      var segments = route.split("/");
	      var results = new Array(segments.length);
	
	      // A routes has specificity determined by the order that its different segments
	      // appear in. This system mirrors how the magnitude of numbers written as strings
	      // works.
	      // Consider a number written as: "abc". An example would be "200". Any other number written
	      // "xyz" will be smaller than "abc" so long as `a > z`. For instance, "199" is smaller
	      // then "200", even though "y" and "z" (which are both 9) are larger than "0" (the value
	      // of (`b` and `c`). This is because the leading symbol, "2", is larger than the other
	      // leading symbol, "1".
	      // The rule is that symbols to the left carry more weight than symbols to the right
	      // when a number is written out as a string. In the above strings, the leading digit
	      // represents how many 100's are in the number, and it carries more weight than the middle
	      // number which represents how many 10's are in the number.
	      // This system of number magnitude works well for route specificity, too. A route written as
	      // `a/b/c` will be more specific than `x/y/z` as long as `a` is more specific than
	      // `x`, irrespective of the other parts.
	      // Because of this similarity, we assign each type of segment a number value written as a
	      // string. We can find the specificity of compound routes by concatenating these strings
	      // together, from left to right. After we have looped through all of the segments,
	      // we convert the string to a number.
	      specificity.val = '';
	
	      for (var i=0; i<segments.length; i++) {
	        var segment = segments[i], match;
	
	        if (match = segment.match(/^:([^\/]+)$/)) {
	          results[i] = new $$route$recognizer$$DynamicSegment(match[1]);
	          names.push(match[1]);
	          specificity.val += '3';
	        } else if (match = segment.match(/^\*([^\/]+)$/)) {
	          results[i] = new $$route$recognizer$$StarSegment(match[1]);
	          specificity.val += '1';
	          names.push(match[1]);
	        } else if(segment === "") {
	          results[i] = new $$route$recognizer$$EpsilonSegment();
	          specificity.val += '2';
	        } else {
	          results[i] = new $$route$recognizer$$StaticSegment(segment);
	          specificity.val += '4';
	        }
	      }
	
	      specificity.val = +specificity.val;
	
	      return results;
	    }
	
	    // A State has a character specification and (`charSpec`) and a list of possible
	    // subsequent states (`nextStates`).
	    //
	    // If a State is an accepting state, it will also have several additional
	    // properties:
	    //
	    // * `regex`: A regular expression that is used to extract parameters from paths
	    //   that reached this accepting state.
	    // * `handlers`: Information on how to convert the list of captures into calls
	    //   to registered handlers with the specified parameters
	    // * `types`: How many static, dynamic or star segments in this route. Used to
	    //   decide which route to use if multiple registered routes match a path.
	    //
	    // Currently, State is implemented naively by looping over `nextStates` and
	    // comparing a character specification against a character. A more efficient
	    // implementation would use a hash of keys pointing at one or more next states.
	
	    function $$route$recognizer$$State(charSpec) {
	      this.charSpec = charSpec;
	      this.nextStates = [];
	      this.charSpecs = {};
	      this.regex = undefined;
	      this.handlers = undefined;
	      this.specificity = undefined;
	    }
	
	    $$route$recognizer$$State.prototype = {
	      get: function(charSpec) {
	        if (this.charSpecs[charSpec.validChars]) {
	          return this.charSpecs[charSpec.validChars];
	        }
	
	        var nextStates = this.nextStates;
	
	        for (var i=0; i<nextStates.length; i++) {
	          var child = nextStates[i];
	
	          var isEqual = child.charSpec.validChars === charSpec.validChars;
	          isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars;
	
	          if (isEqual) {
	            this.charSpecs[charSpec.validChars] = child;
	            return child;
	          }
	        }
	      },
	
	      put: function(charSpec) {
	        var state;
	
	        // If the character specification already exists in a child of the current
	        // state, just return that state.
	        if (state = this.get(charSpec)) { return state; }
	
	        // Make a new state for the character spec
	        state = new $$route$recognizer$$State(charSpec);
	
	        // Insert the new state as a child of the current state
	        this.nextStates.push(state);
	
	        // If this character specification repeats, insert the new state as a child
	        // of itself. Note that this will not trigger an infinite loop because each
	        // transition during recognition consumes a character.
	        if (charSpec.repeat) {
	          state.nextStates.push(state);
	        }
	
	        // Return the new state
	        return state;
	      },
	
	      // Find a list of child states matching the next character
	      match: function(ch) {
	        var nextStates = this.nextStates,
	            child, charSpec, chars;
	
	        var returned = [];
	
	        for (var i=0; i<nextStates.length; i++) {
	          child = nextStates[i];
	
	          charSpec = child.charSpec;
	
	          if (typeof (chars = charSpec.validChars) !== 'undefined') {
	            if (chars.indexOf(ch) !== -1) { returned.push(child); }
	          } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
	            if (chars.indexOf(ch) === -1) { returned.push(child); }
	          }
	        }
	
	        return returned;
	      }
	    };
	
	    // Sort the routes by specificity
	    function $$route$recognizer$$sortSolutions(states) {
	      return states.sort(function(a, b) {
	        return b.specificity.val - a.specificity.val;
	      });
	    }
	
	    function $$route$recognizer$$recognizeChar(states, ch) {
	      var nextStates = [];
	
	      for (var i=0, l=states.length; i<l; i++) {
	        var state = states[i];
	
	        nextStates = nextStates.concat(state.match(ch));
	      }
	
	      return nextStates;
	    }
	
	    var $$route$recognizer$$oCreate = Object.create || function(proto) {
	      function F() {}
	      F.prototype = proto;
	      return new F();
	    };
	
	    function $$route$recognizer$$RecognizeResults(queryParams) {
	      this.queryParams = queryParams || {};
	    }
	    $$route$recognizer$$RecognizeResults.prototype = $$route$recognizer$$oCreate({
	      splice: Array.prototype.splice,
	      slice:  Array.prototype.slice,
	      push:   Array.prototype.push,
	      length: 0,
	      queryParams: null
	    });
	
	    function $$route$recognizer$$findHandler(state, path, queryParams) {
	      var handlers = state.handlers, regex = state.regex;
	      var captures = path.match(regex), currentCapture = 1;
	      var result = new $$route$recognizer$$RecognizeResults(queryParams);
	
	      result.length = handlers.length;
	
	      for (var i=0; i<handlers.length; i++) {
	        var handler = handlers[i], names = handler.names, params = {};
	
	        for (var j=0; j<names.length; j++) {
	          params[names[j]] = captures[currentCapture++];
	        }
	
	        result[i] = { handler: handler.handler, params: params, isDynamic: !!names.length };
	      }
	
	      return result;
	    }
	
	    function $$route$recognizer$$decodeQueryParamPart(part) {
	      // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
	      part = part.replace(/\+/gm, '%20');
	      var result;
	      try {
	        result = decodeURIComponent(part);
	      } catch(error) {result = '';}
	      return result;
	    }
	
	    // The main interface
	
	    var $$route$recognizer$$RouteRecognizer = function() {
	      this.rootState = new $$route$recognizer$$State();
	      this.names = {};
	    };
	
	
	    $$route$recognizer$$RouteRecognizer.prototype = {
	      add: function(routes, options) {
	        var currentState = this.rootState, regex = "^",
	            specificity = {},
	            handlers = new Array(routes.length), allSegments = [], name;
	
	        var isEmpty = true;
	
	        for (var i=0; i<routes.length; i++) {
	          var route = routes[i], names = [];
	
	          var segments = $$route$recognizer$$parse(route.path, names, specificity);
	
	          allSegments = allSegments.concat(segments);
	
	          for (var j=0; j<segments.length; j++) {
	            var segment = segments[j];
	
	            if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; }
	
	            isEmpty = false;
	
	            // Add a "/" for the new segment
	            currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: "/" });
	            regex += "/";
	
	            // Add a representation of the segment to the NFA and regex
	            currentState = segment.eachChar(currentState);
	            regex += segment.regex();
	          }
	          var handler = { handler: route.handler, names: names };
	          handlers[i] = handler;
	        }
	
	        if (isEmpty) {
	          currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: "/" });
	          regex += "/";
	        }
	
	        currentState.handlers = handlers;
	        currentState.regex = new RegExp(regex + "$");
	        currentState.specificity = specificity;
	
	        if (name = options && options.as) {
	          this.names[name] = {
	            segments: allSegments,
	            handlers: handlers
	          };
	        }
	      },
	
	      handlersFor: function(name) {
	        var route = this.names[name];
	
	        if (!route) { throw new Error("There is no route named " + name); }
	
	        var result = new Array(route.handlers.length);
	
	        for (var i=0; i<route.handlers.length; i++) {
	          result[i] = route.handlers[i];
	        }
	
	        return result;
	      },
	
	      hasRoute: function(name) {
	        return !!this.names[name];
	      },
	
	      generate: function(name, params) {
	        var route = this.names[name], output = "";
	        if (!route) { throw new Error("There is no route named " + name); }
	
	        var segments = route.segments;
	
	        for (var i=0; i<segments.length; i++) {
	          var segment = segments[i];
	
	          if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; }
	
	          output += "/";
	          output += segment.generate(params);
	        }
	
	        if (output.charAt(0) !== '/') { output = '/' + output; }
	
	        if (params && params.queryParams) {
	          output += this.generateQueryString(params.queryParams, route.handlers);
	        }
	
	        return output;
	      },
	
	      generateQueryString: function(params, handlers) {
	        var pairs = [];
	        var keys = [];
	        for(var key in params) {
	          if (params.hasOwnProperty(key)) {
	            keys.push(key);
	          }
	        }
	        keys.sort();
	        for (var i = 0; i < keys.length; i++) {
	          key = keys[i];
	          var value = params[key];
	          if (value == null) {
	            continue;
	          }
	          var pair = encodeURIComponent(key);
	          if ($$route$recognizer$$isArray(value)) {
	            for (var j = 0; j < value.length; j++) {
	              var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]);
	              pairs.push(arrayPair);
	            }
	          } else {
	            pair += "=" + encodeURIComponent(value);
	            pairs.push(pair);
	          }
	        }
	
	        if (pairs.length === 0) { return ''; }
	
	        return "?" + pairs.join("&");
	      },
	
	      parseQueryString: function(queryString) {
	        var pairs = queryString.split("&"), queryParams = {};
	        for(var i=0; i < pairs.length; i++) {
	          var pair      = pairs[i].split('='),
	              key       = $$route$recognizer$$decodeQueryParamPart(pair[0]),
	              keyLength = key.length,
	              isArray = false,
	              value;
	          if (pair.length === 1) {
	            value = 'true';
	          } else {
	            //Handle arrays
	            if (keyLength > 2 && key.slice(keyLength -2) === '[]') {
	              isArray = true;
	              key = key.slice(0, keyLength - 2);
	              if(!queryParams[key]) {
	                queryParams[key] = [];
	              }
	            }
	            value = pair[1] ? $$route$recognizer$$decodeQueryParamPart(pair[1]) : '';
	          }
	          if (isArray) {
	            queryParams[key].push(value);
	          } else {
	            queryParams[key] = value;
	          }
	        }
	        return queryParams;
	      },
	
	      recognize: function(path) {
	        var states = [ this.rootState ],
	            pathLen, i, l, queryStart, queryParams = {},
	            isSlashDropped = false;
	
	        queryStart = path.indexOf('?');
	        if (queryStart !== -1) {
	          var queryString = path.substr(queryStart + 1, path.length);
	          path = path.substr(0, queryStart);
	          queryParams = this.parseQueryString(queryString);
	        }
	
	        path = decodeURI(path);
	
	        if (path.charAt(0) !== "/") { path = "/" + path; }
	
	        pathLen = path.length;
	        if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
	          path = path.substr(0, pathLen - 1);
	          isSlashDropped = true;
	        }
	
	        for (i=0; i<path.length; i++) {
	          states = $$route$recognizer$$recognizeChar(states, path.charAt(i));
	          if (!states.length) { break; }
	        }
	
	        var solutions = [];
	        for (i=0; i<states.length; i++) {
	          if (states[i].handlers) { solutions.push(states[i]); }
	        }
	
	        states = $$route$recognizer$$sortSolutions(solutions);
	
	        var state = solutions[0];
	
	        if (state && state.handlers) {
	          // if a trailing slash was dropped and a star segment is the last segment
	          // specified, put the trailing slash back
	          if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") {
	            path = path + "/";
	          }
	          return $$route$recognizer$$findHandler(state, path, queryParams);
	        }
	      }
	    };
	
	    $$route$recognizer$$RouteRecognizer.prototype.map = $$route$recognizer$dsl$$default;
	
	    $$route$recognizer$$RouteRecognizer.VERSION = '0.1.11';
	
	    var $$route$recognizer$$default = $$route$recognizer$$RouteRecognizer;
	
	    /* global define:true module:true window: true */
	    if ( true && __webpack_require__(3)['amd']) {
	      !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return $$route$recognizer$$default; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	    } else if (typeof module !== 'undefined' && module['exports']) {
	      module['exports'] = $$route$recognizer$$default;
	    } else if (typeof this !== 'undefined') {
	      this['RouteRecognizer'] = $$route$recognizer$$default;
	    }
	}).call(this);
	
	
	/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)(module)))

/***/ },
/* 2 */
/***/ function(module, exports) {

	module.exports = function(module) {
		if(!module.webpackPolyfill) {
			module.deprecate = function() {};
			module.paths = [];
			// module.parent = undefined by default
			module.children = [];
			module.webpackPolyfill = 1;
		}
		return module;
	}


/***/ },
/* 3 */
/***/ function(module, exports) {

	module.exports = function() { throw new Error("define cannot be used indirect"); };


/***/ }
/******/ ])
});
;


/***/ }),

/***/ "./node_modules/window-post-message-proxy/dist/windowPostMessageProxy.js":
/*!*******************************************************************************!*\
  !*** ./node_modules/window-post-message-proxy/dist/windowPostMessageProxy.js ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

/*! window-post-message-proxy v0.2.6 | (c) 2016 Microsoft Corporation MIT */
(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

	"use strict";
	var WindowPostMessageProxy = (function () {
	    function WindowPostMessageProxy(options) {
	        var _this = this;
	        if (options === void 0) { options = {
	            processTrackingProperties: {
	                addTrackingProperties: WindowPostMessageProxy.defaultAddTrackingProperties,
	                getTrackingProperties: WindowPostMessageProxy.defaultGetTrackingProperties
	            },
	            isErrorMessage: WindowPostMessageProxy.defaultIsErrorMessage,
	            receiveWindow: window,
	            name: WindowPostMessageProxy.createRandomString()
	        }; }
	        this.pendingRequestPromises = {};
	        // save options with defaults
	        this.addTrackingProperties = (options.processTrackingProperties && options.processTrackingProperties.addTrackingProperties) || WindowPostMessageProxy.defaultAddTrackingProperties;
	        this.getTrackingProperties = (options.processTrackingProperties && options.processTrackingProperties.getTrackingProperties) || WindowPostMessageProxy.defaultGetTrackingProperties;
	        this.isErrorMessage = options.isErrorMessage || WindowPostMessageProxy.defaultIsErrorMessage;
	        this.receiveWindow = options.receiveWindow || window;
	        this.name = options.name || WindowPostMessageProxy.createRandomString();
	        this.logMessages = options.logMessages || false;
	        this.eventSourceOverrideWindow = options.eventSourceOverrideWindow;
	        this.suppressWarnings = options.suppressWarnings || false;
	        if (this.logMessages) {
	            console.log("new WindowPostMessageProxy created with name: " + this.name + " receiving on window: " + this.receiveWindow.document.title);
	        }
	        // Initialize
	        this.handlers = [];
	        this.windowMessageHandler = function (event) { return _this.onMessageReceived(event); };
	        this.start();
	    }
	    // Static
	    WindowPostMessageProxy.defaultAddTrackingProperties = function (message, trackingProperties) {
	        message[WindowPostMessageProxy.messagePropertyName] = trackingProperties;
	        return message;
	    };
	    WindowPostMessageProxy.defaultGetTrackingProperties = function (message) {
	        return message[WindowPostMessageProxy.messagePropertyName];
	    };
	    WindowPostMessageProxy.defaultIsErrorMessage = function (message) {
	        return !!message.error;
	    };
	    /**
	     * Utility to create a deferred object.
	     */
	    // TODO: Look to use RSVP library instead of doing this manually.
	    // From what I searched RSVP would work better because it has .finally and .deferred; however, it doesn't have Typings information. 
	    WindowPostMessageProxy.createDeferred = function () {
	        var deferred = {
	            resolve: null,
	            reject: null,
	            promise: null
	        };
	        var promise = new Promise(function (resolve, reject) {
	            deferred.resolve = resolve;
	            deferred.reject = reject;
	        });
	        deferred.promise = promise;
	        return deferred;
	    };
	    /**
	     * Utility to generate random sequence of characters used as tracking id for promises.
	     */
	    WindowPostMessageProxy.createRandomString = function () {
	        // window.msCrypto for IE
	        var cryptoObj = window.crypto || window.msCrypto;
	        var randomValueArray = new Uint32Array(1);
	        cryptoObj.getRandomValues(randomValueArray);
	        return randomValueArray[0].toString(36).substring(1);
	    };
	    /**
	     * Adds handler.
	     * If the first handler whose test method returns true will handle the message and provide a response.
	     */
	    WindowPostMessageProxy.prototype.addHandler = function (handler) {
	        this.handlers.push(handler);
	    };
	    /**
	     * Removes handler.
	     * The reference must match the original object that was provided when adding the handler.
	     */
	    WindowPostMessageProxy.prototype.removeHandler = function (handler) {
	        var handlerIndex = this.handlers.indexOf(handler);
	        if (handlerIndex === -1) {
	            throw new Error("You attempted to remove a handler but no matching handler was found.");
	        }
	        this.handlers.splice(handlerIndex, 1);
	    };
	    /**
	     * Start listening to message events.
	     */
	    WindowPostMessageProxy.prototype.start = function () {
	        this.receiveWindow.addEventListener('message', this.windowMessageHandler);
	    };
	    /**
	     * Stops listening to message events.
	     */
	    WindowPostMessageProxy.prototype.stop = function () {
	        this.receiveWindow.removeEventListener('message', this.windowMessageHandler);
	    };
	    /**
	     * Post message to target window with tracking properties added and save deferred object referenced by tracking id.
	     */
	    WindowPostMessageProxy.prototype.postMessage = function (targetWindow, message) {
	        // Add tracking properties to indicate message came from this proxy
	        var trackingProperties = { id: WindowPostMessageProxy.createRandomString() };
	        this.addTrackingProperties(message, trackingProperties);
	        if (this.logMessages) {
	            console.log(this.name + " Posting message:");
	            console.log(JSON.stringify(message, null, '  '));
	        }
	        targetWindow.postMessage(message, "*");
	        var deferred = WindowPostMessageProxy.createDeferred();
	        this.pendingRequestPromises[trackingProperties.id] = deferred;
	        return deferred.promise;
	    };
	    /**
	     * Send response message to target window.
	     * Response messages re-use tracking properties from a previous request message.
	     */
	    WindowPostMessageProxy.prototype.sendResponse = function (targetWindow, message, trackingProperties) {
	        this.addTrackingProperties(message, trackingProperties);
	        if (this.logMessages) {
	            console.log(this.name + " Sending response:");
	            console.log(JSON.stringify(message, null, '  '));
	        }
	        targetWindow.postMessage(message, "*");
	    };
	    /**
	     * Message handler.
	     */
	    WindowPostMessageProxy.prototype.onMessageReceived = function (event) {
	        var _this = this;
	        if (this.logMessages) {
	            console.log(this.name + " Received message:");
	            console.log("type: " + event.type);
	            console.log(JSON.stringify(event.data, null, '  '));
	        }
	        var sendingWindow = this.eventSourceOverrideWindow || event.source;
	        var message = event.data;
	        if (typeof message !== "object") {
	            if (!this.suppressWarnings) {
	                console.warn("Proxy(" + this.name + "): Received message that was not an object. Discarding message");
	            }
	            return;
	        }
	        var trackingProperties;
	        try {
	            trackingProperties = this.getTrackingProperties(message);
	        }
	        catch (e) {
	            if (!this.suppressWarnings) {
	                console.warn("Proxy(" + this.name + "): Error occurred when attempting to get tracking properties from incoming message:", JSON.stringify(message, null, '  '), "Error: ", e);
	            }
	        }
	        var deferred;
	        if (trackingProperties) {
	            deferred = this.pendingRequestPromises[trackingProperties.id];
	        }
	        // If message does not have a known ID, treat it as a request
	        // Otherwise, treat message as response
	        if (!deferred) {
	            var handled = this.handlers.some(function (handler) {
	                var canMessageBeHandled = false;
	                try {
	                    canMessageBeHandled = handler.test(message);
	                }
	                catch (e) {
	                    if (!_this.suppressWarnings) {
	                        console.warn("Proxy(" + _this.name + "): Error occurred when handler was testing incoming message:", JSON.stringify(message, null, '  '), "Error: ", e);
	                    }
	                }
	                if (canMessageBeHandled) {
	                    var responseMessagePromise = void 0;
	                    try {
	                        responseMessagePromise = Promise.resolve(handler.handle(message));
	                    }
	                    catch (e) {
	                        if (!_this.suppressWarnings) {
	                            console.warn("Proxy(" + _this.name + "): Error occurred when handler was processing incoming message:", JSON.stringify(message, null, '  '), "Error: ", e);
	                        }
	                        responseMessagePromise = Promise.resolve();
	                    }
	                    responseMessagePromise
	                        .then(function (responseMessage) {
	                        if (!responseMessage) {
	                            var warningMessage = "Handler for message: " + JSON.stringify(message, null, '  ') + " did not return a response message. The default response message will be returned instead.";
	                            if (!_this.suppressWarnings) {
	                                console.warn("Proxy(" + _this.name + "): " + warningMessage);
	                            }
	                            responseMessage = {
	                                warning: warningMessage
	                            };
	                        }
	                        _this.sendResponse(sendingWindow, responseMessage, trackingProperties);
	                    });
	                    return true;
	                }
	            });
	            /**
	             * TODO: Consider returning an error message if nothing handled the message.
	             * In the case of the Report receiving messages all of them should be handled,
	             * however, in the case of the SDK receiving messages it's likely it won't register handlers
	             * for all events. Perhaps make this an option at construction time.
	             */
	            if (!handled && !this.suppressWarnings) {
	                console.warn("Proxy(" + this.name + ") did not handle message. Handlers: " + this.handlers.length + "  Message: " + JSON.stringify(message, null, '') + ".");
	            }
	        }
	        else {
	            /**
	             * If error message reject promise,
	             * Otherwise, resolve promise
	             */
	            var isErrorMessage = true;
	            try {
	                isErrorMessage = this.isErrorMessage(message);
	            }
	            catch (e) {
	                console.warn("Proxy(" + this.name + ") Error occurred when trying to determine if message is consider an error response. Message: ", JSON.stringify(message, null, ''), 'Error: ', e);
	            }
	            if (isErrorMessage) {
	                deferred.reject(message);
	            }
	            else {
	                deferred.resolve(message);
	            }
	            // TODO: Move to .finally clause up where promise is created for better maitenance like original proxy code.
	            delete this.pendingRequestPromises[trackingProperties.id];
	        }
	    };
	    WindowPostMessageProxy.messagePropertyName = "windowPostMessageProxy";
	    return WindowPostMessageProxy;
	}());
	exports.WindowPostMessageProxy = WindowPostMessageProxy;


/***/ })
/******/ ])
});
;


/***/ }),

/***/ "./src/bookmarksManager.ts":
/*!*********************************!*\
  !*** ./src/bookmarksManager.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BookmarksManager = void 0;
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
var errors = __webpack_require__(/*! ./errors */ "./src/errors.ts");
/**
 * Manages report bookmarks.
 *
 * @export
 * @class BookmarksManager
 * @implements {IBookmarksManager}
 */
var BookmarksManager = /** @class */ (function () {
    /**
     * @hidden
     */
    function BookmarksManager(service, config, iframe) {
        this.service = service;
        this.config = config;
        this.iframe = iframe;
    }
    /**
     * Gets bookmarks that are defined in the report.
     *
     * ```javascript
     * // Gets bookmarks that are defined in the report
     * bookmarksManager.getBookmarks()
     *   .then(bookmarks => {
     *     ...
     *   });
     * ```
     *
     * @returns {Promise<models.IReportBookmark[]>}
     */
    BookmarksManager.prototype.getBookmarks = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.get("/report/bookmarks", { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Apply bookmark by name.
     *
     * ```javascript
     * bookmarksManager.apply(bookmarkName)
     * ```
     *
     * @param {string} bookmarkName The name of the bookmark to be applied
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    BookmarksManager.prototype.apply = function (bookmarkName) {
        return __awaiter(this, void 0, void 0, function () {
            var request, response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        request = {
                            name: bookmarkName
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/bookmarks/applyByName", request, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Play bookmarks: Enter or Exit bookmarks presentation mode.
     *
     * ```javascript
     * // Enter presentation mode.
     * bookmarksManager.play(models.BookmarksPlayMode.Presentation)
     * ```
     *
     * @param {models.BookmarksPlayMode} playMode Play mode can be either `Presentation` or `Off`
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    BookmarksManager.prototype.play = function (playMode) {
        return __awaiter(this, void 0, void 0, function () {
            var playBookmarkRequest, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        playBookmarkRequest = {
                            playMode: playMode
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/bookmarks/play", playBookmarkRequest, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Capture bookmark from current state.
     *
     * ```javascript
     * bookmarksManager.capture(options)
     * ```
     *
     * @param {models.ICaptureBookmarkOptions} [options] Options for bookmark capturing
     * @returns {Promise<models.IReportBookmark>}
     */
    BookmarksManager.prototype.capture = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var request, response, response_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        request = {
                            options: options || {}
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/bookmarks/capture", request, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_4 = _a.sent();
                        throw response_4.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Apply bookmark state.
     *
     * ```javascript
     * bookmarksManager.applyState(bookmarkState)
     * ```
     *
     * @param {string} state A base64 bookmark state to be applied
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    BookmarksManager.prototype.applyState = function (state) {
        return __awaiter(this, void 0, void 0, function () {
            var request, response_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        request = {
                            state: state
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/bookmarks/applyState", request, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_5 = _a.sent();
                        throw response_5.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    return BookmarksManager;
}());
exports.BookmarksManager = BookmarksManager;


/***/ }),

/***/ "./src/config.ts":
/*!***********************!*\
  !*** ./src/config.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
/** @ignore */ /** */
var config = {
    version: '2.16.2',
    type: 'js'
};
exports.default = config;


/***/ }),

/***/ "./src/create.ts":
/*!***********************!*\
  !*** ./src/create.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Create = void 0;
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
/**
 * A Power BI Report creator component
 *
 * @export
 * @class Create
 * @extends {embed.Embed}
 */
var Create = /** @class */ (function (_super) {
    __extends(Create, _super);
    /*
     * @hidden
     */
    function Create(service, element, config, phasedRender, isBootstrap) {
        return _super.call(this, service, element, config, /* iframe */ undefined, phasedRender, isBootstrap) || this;
    }
    /**
     * Gets the dataset ID from the first available location: createConfig or embed url.
     *
     * @returns {string}
     */
    Create.prototype.getId = function () {
        var datasetId = (this.createConfig && this.createConfig.datasetId) ? this.createConfig.datasetId : Create.findIdFromEmbedUrl(this.config.embedUrl);
        if (typeof datasetId !== 'string' || datasetId.length === 0) {
            throw new Error('Dataset id is required, but it was not found. You must provide an id either as part of embed configuration.');
        }
        return datasetId;
    };
    /**
     * Validate create report configuration.
     */
    Create.prototype.validate = function (config) {
        return models.validateCreateReport(config);
    };
    /**
     * Handle config changes.
     *
     * @hidden
     * @returns {void}
     */
    Create.prototype.configChanged = function (isBootstrap) {
        if (isBootstrap) {
            return;
        }
        var config = this.config;
        this.createConfig = {
            accessToken: config.accessToken,
            datasetId: config.datasetId || this.getId(),
            groupId: config.groupId,
            settings: config.settings,
            tokenType: config.tokenType,
            theme: config.theme
        };
    };
    /**
     * @hidden
     * @returns {string}
     */
    Create.prototype.getDefaultEmbedUrlEndpoint = function () {
        return "reportEmbed";
    };
    /**
     * checks if the report is saved.
     *
     * ```javascript
     * report.isSaved()
     * ```
     *
     * @returns {Promise<boolean>}
     */
    Create.prototype.isSaved = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, utils.isSavedInternal(this.service.hpm, this.config.uniqueId, this.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Adds the ability to get datasetId from url.
     * (e.g. http://embedded.powerbi.com/appTokenReportEmbed?datasetId=854846ed-2106-4dc2-bc58-eb77533bf2f1).
     *
     * By extracting the ID we can ensure that the ID is always explicitly provided as part of the create configuration.
     *
     * @static
     * @param {string} url
     * @returns {string}
     * @hidden
     */
    Create.findIdFromEmbedUrl = function (url) {
        var datasetIdRegEx = /datasetId="?([^&]+)"?/;
        var datasetIdMatch = url.match(datasetIdRegEx);
        var datasetId;
        if (datasetIdMatch) {
            datasetId = datasetIdMatch[1];
        }
        return datasetId;
    };
    return Create;
}(embed.Embed));
exports.Create = Create;


/***/ }),

/***/ "./src/dashboard.ts":
/*!**************************!*\
  !*** ./src/dashboard.ts ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dashboard = void 0;
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
/**
 * A Power BI Dashboard embed component
 *
 * @export
 * @class Dashboard
 * @extends {embed.Embed}
 * @implements {IDashboardNode}
 */
var Dashboard = /** @class */ (function (_super) {
    __extends(Dashboard, _super);
    /**
     * Creates an instance of a Power BI Dashboard.
     *
     * @param {service.Service} service
     * @hidden
     * @param {HTMLElement} element
     */
    function Dashboard(service, element, config, phasedRender, isBootstrap) {
        var _this = _super.call(this, service, element, config, /* iframe */ undefined, phasedRender, isBootstrap) || this;
        _this.loadPath = "/dashboard/load";
        _this.phasedLoadPath = "/dashboard/prepare";
        Array.prototype.push.apply(_this.allowedEvents, Dashboard.allowedEvents);
        return _this;
    }
    /**
     * This adds backwards compatibility for older config which used the dashboardId query param to specify dashboard id.
     * E.g. https://powerbi-df.analysis-df.windows.net/dashboardEmbedHost?dashboardId=e9363c62-edb6-4eac-92d3-2199c5ca2a9e
     *
     * By extracting the id we can ensure id is always explicitly provided as part of the load configuration.
     * @hidden
     * @static
     * @param {string} url
     * @returns {string}
     */
    Dashboard.findIdFromEmbedUrl = function (url) {
        var dashboardIdRegEx = /dashboardId="?([^&]+)"?/;
        var dashboardIdMatch = url.match(dashboardIdRegEx);
        var dashboardId;
        if (dashboardIdMatch) {
            dashboardId = dashboardIdMatch[1];
        }
        return dashboardId;
    };
    /**
     * Get dashboard id from first available location: options, attribute, embed url.
     *
     * @returns {string}
     */
    Dashboard.prototype.getId = function () {
        var config = this.config;
        var dashboardId = config.id || this.element.getAttribute(Dashboard.dashboardIdAttribute) || Dashboard.findIdFromEmbedUrl(config.embedUrl);
        if (typeof dashboardId !== 'string' || dashboardId.length === 0) {
            throw new Error("Dashboard id is required, but it was not found. You must provide an id either as part of embed configuration or as attribute '" + Dashboard.dashboardIdAttribute + "'.");
        }
        return dashboardId;
    };
    /**
     * Validate load configuration.
     *
     * @hidden
     */
    Dashboard.prototype.validate = function (baseConfig) {
        var config = baseConfig;
        var error = models.validateDashboardLoad(config);
        return error ? error : this.ValidatePageView(config.pageView);
    };
    /**
     * Handle config changes.
     * @hidden
     * @returns {void}
     */
    Dashboard.prototype.configChanged = function (isBootstrap) {
        if (isBootstrap) {
            return;
        }
        // Populate dashboard id into config object.
        this.config.id = this.getId();
    };
    /**
     * @hidden
     * @returns {string}
     */
    Dashboard.prototype.getDefaultEmbedUrlEndpoint = function () {
        return "dashboardEmbed";
    };
    /**
     * Validate that pageView has a legal value: if page view is defined it must have one of the values defined in models.PageView
     * @hidden
     */
    Dashboard.prototype.ValidatePageView = function (pageView) {
        if (pageView && pageView !== "fitToWidth" && pageView !== "oneColumn" && pageView !== "actualSize") {
            return [{ message: "pageView must be one of the followings: fitToWidth, oneColumn, actualSize" }];
        }
    };
    /** @hidden */
    Dashboard.allowedEvents = ["tileClicked", "error"];
    /** @hidden */
    Dashboard.dashboardIdAttribute = 'powerbi-dashboard-id';
    /** @hidden */
    Dashboard.typeAttribute = 'powerbi-type';
    /** @hidden */
    Dashboard.type = "Dashboard";
    return Dashboard;
}(embed.Embed));
exports.Dashboard = Dashboard;


/***/ }),

/***/ "./src/embed.ts":
/*!**********************!*\
  !*** ./src/embed.ts ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Embed = void 0;
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
var sdkConfig = __webpack_require__(/*! ./config */ "./src/config.ts");
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var errors_1 = __webpack_require__(/*! ./errors */ "./src/errors.ts");
/**
 * Base class for all Power BI embed components
 *
 * @export
 * @abstract
 * @hidden
 * @class Embed
 */
var Embed = /** @class */ (function () {
    /**
     * Creates an instance of Embed.
     *
     * Note: there is circular reference between embeds and the service, because
     * the service has a list of all embeds on the host page, and each embed has a reference to the service that created it.
     *
     * @param {service.Service} service
     * @param {HTMLElement} element
     * @param {IEmbedConfigurationBase} config
     * @hidden
     */
    function Embed(service, element, config, iframe, phasedRender, isBootstrap) {
        /** @hidden */
        this.allowedEvents = [];
        if (utils.autoAuthInEmbedUrl(config.embedUrl)) {
            throw new Error(errors_1.EmbedUrlNotSupported);
        }
        Array.prototype.push.apply(this.allowedEvents, Embed.allowedEvents);
        this.eventHandlers = [];
        this.service = service;
        this.element = element;
        this.iframe = iframe;
        this.iframeLoaded = false;
        this.embedtype = config.type.toLowerCase();
        this.populateConfig(config, isBootstrap);
        if (this.embedtype === 'create') {
            this.setIframe(false /*set EventListener to call create() on 'load' event*/, phasedRender, isBootstrap);
        }
        else {
            this.setIframe(true /*set EventListener to call load() on 'load' event*/, phasedRender, isBootstrap);
        }
    }
    /**
     * Sends createReport configuration data.
     *
     * ```javascript
     * createReport({
     *   datasetId: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
     *   accessToken: 'eyJ0eXA ... TaE2rTSbmg',
     * ```
     * @hidden
     * @param {models.IReportCreateConfiguration} config
     * @returns {Promise<void>}
     */
    Embed.prototype.createReport = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var errors, response, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        errors = models.validateCreateReport(config);
                        if (errors) {
                            throw errors;
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/create", config, { uid: this.config.uniqueId, sdkSessionId: this.service.getSdkSessionId() }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Saves Report.
     *
     * @returns {Promise<void>}
     */
    Embed.prototype.save = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.post('/report/save', null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * SaveAs Report.
     *
     * @returns {Promise<void>}
     */
    Embed.prototype.saveAs = function (saveAsParameters) {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.post('/report/saveAs', saveAsParameters, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Get the correlationId for the current embed session.
     *
     * ```javascript
     * // Get the correlationId for the current embed session
     * report.getCorrelationId()
     *   .then(correlationId => {
     *     ...
     *   });
     * ```
     *
     * @returns {Promise<string>}
     */
    Embed.prototype.getCorrelationId = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.get("/getCorrelationId", { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_4 = _a.sent();
                        throw response_4.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sends load configuration data.
     *
     * ```javascript
     * report.load({
     *   type: 'report',
     *   id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
     *   accessToken: 'eyJ0eXA ... TaE2rTSbmg',
     *   settings: {
     *     navContentPaneEnabled: false
     *   },
     *   pageName: "DefaultPage",
     *   filters: [
     *     {
     *        ...  DefaultReportFilter ...
     *     }
     *   ]
     * })
     *   .catch(error => { ... });
     * ```
     * @hidden
     * @param {models.ILoadConfiguration} config
     * @param {boolean} phasedRender
     * @returns {Promise<void>}
     */
    Embed.prototype.load = function (phasedRender) {
        return __awaiter(this, void 0, void 0, function () {
            var path, headers, timeNow, response, response_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.config.accessToken) {
                            console.debug("Power BI SDK iframe is loaded but powerbi.embed is not called yet.");
                            return [2 /*return*/];
                        }
                        if (!this.iframeLoaded) {
                            console.debug("Power BI SDK is trying to post /report/load before iframe is ready.");
                            return [2 /*return*/];
                        }
                        path = phasedRender && this.config.type === 'report' ? this.phasedLoadPath : this.loadPath;
                        headers = {
                            uid: this.config.uniqueId,
                            sdkSessionId: this.service.getSdkSessionId(),
                            bootstrapped: this.config.bootstrapped,
                            sdkVersion: sdkConfig.default.version
                        };
                        timeNow = new Date();
                        if (this.lastLoadRequest && utils.getTimeDiffInMilliseconds(this.lastLoadRequest, timeNow) < 100) {
                            console.debug("Power BI SDK sent more than two /report/load requests in the last 100ms interval.");
                            return [2 /*return*/];
                        }
                        this.lastLoadRequest = timeNow;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post(path, this.config, headers, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_5 = _a.sent();
                        throw response_5.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Removes one or more event handlers from the list of handlers.
     * If a reference to the existing handle function is specified, remove the specific handler.
     * If the handler is not specified, remove all handlers for the event name specified.
     *
     * ```javascript
     * report.off('pageChanged')
     *
     * or
     *
     * const logHandler = function (event) {
     *    console.log(event);
     * };
     *
     * report.off('pageChanged', logHandler);
     * ```
     *
     * @template T
     * @param {string} eventName
     * @param {service.IEventHandler<T>} [handler]
     */
    Embed.prototype.off = function (eventName, handler) {
        var _this = this;
        var fakeEvent = { name: eventName, type: null, id: null, value: null };
        if (handler) {
            utils.remove(function (eventHandler) { return eventHandler.test(fakeEvent) && (eventHandler.handle === handler); }, this.eventHandlers);
            this.element.removeEventListener(eventName, handler);
        }
        else {
            var eventHandlersToRemove = this.eventHandlers
                .filter(function (eventHandler) { return eventHandler.test(fakeEvent); });
            eventHandlersToRemove
                .forEach(function (eventHandlerToRemove) {
                utils.remove(function (eventHandler) { return eventHandler === eventHandlerToRemove; }, _this.eventHandlers);
                _this.element.removeEventListener(eventName, eventHandlerToRemove.handle);
            });
        }
    };
    /**
     * Adds an event handler for a specific event.
     *
     * ```javascript
     * report.on('pageChanged', (event) => {
     *   console.log('PageChanged: ', event.page.name);
     * });
     * ```
     *
     * @template T
     * @param {string} eventName
     * @param {service.IEventHandler<T>} handler
     */
    Embed.prototype.on = function (eventName, handler) {
        if (this.allowedEvents.indexOf(eventName) === -1) {
            throw new Error("eventName must be one of " + this.allowedEvents + ". You passed: " + eventName);
        }
        this.eventHandlers.push({
            test: function (event) { return event.name === eventName; },
            handle: handler
        });
        this.element.addEventListener(eventName, handler);
    };
    /**
     * Reloads embed using existing configuration.
     * E.g. For reports this effectively clears all filters and makes the first page active which simulates resetting a report back to loaded state.
     *
     * ```javascript
     * report.reload();
     * ```
     */
    Embed.prototype.reload = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.load()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Set accessToken.
     *
     * @returns {Promise<void>}
     */
    Embed.prototype.setAccessToken = function (accessToken) {
        return __awaiter(this, void 0, void 0, function () {
            var embedType, response, response_6;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        embedType = this.config.type;
                        embedType = (embedType === 'create' || embedType === 'visual' || embedType === 'qna') ? 'report' : embedType;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post('/' + embedType + '/token', accessToken, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        this.config.accessToken = accessToken;
                        this.element.setAttribute(Embed.accessTokenAttribute, accessToken);
                        this.service.accessToken = accessToken;
                        return [2 /*return*/, response.body];
                    case 3:
                        response_6 = _a.sent();
                        throw response_6.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets an access token from the first available location: config, attribute, global.
     *
     * @private
     * @param {string} globalAccessToken
     * @returns {string}
     * @hidden
     */
    Embed.prototype.getAccessToken = function (globalAccessToken) {
        var accessToken = this.config.accessToken || this.element.getAttribute(Embed.accessTokenAttribute) || globalAccessToken;
        if (!accessToken) {
            throw new Error("No access token was found for element. You must specify an access token directly on the element using attribute '" + Embed.accessTokenAttribute + "' or specify a global token at: powerbi.accessToken.");
        }
        return accessToken;
    };
    /**
     * Populate config for create and load
     *
     * @hidden
     * @param {IEmbedConfiguration}
     * @returns {void}
     */
    Embed.prototype.populateConfig = function (config, isBootstrap) {
        if (this.bootstrapConfig) {
            this.config = utils.assign({}, this.bootstrapConfig, config);
            // reset bootstrapConfig because we do not want to merge it in re-embed scenario.
            this.bootstrapConfig = null;
        }
        else {
            // Copy config - important for multiple iframe scenario.
            // Otherwise, if a user uses the same config twice, same unique Id which will be used in different iframes.
            this.config = utils.assign({}, config);
        }
        this.config.embedUrl = this.getEmbedUrl(isBootstrap);
        this.config.groupId = this.getGroupId();
        this.addLocaleToEmbedUrl(config);
        this.config.uniqueId = this.getUniqueId();
        if (isBootstrap) {
            // save current config in bootstrapConfig to be able to merge it on next call to powerbi.embed
            this.bootstrapConfig = this.config;
            this.bootstrapConfig.bootstrapped = true;
        }
        else {
            this.config.accessToken = this.getAccessToken(this.service.accessToken);
        }
        this.configChanged(isBootstrap);
    };
    /**
     * Adds locale parameters to embedUrl
     *
     * @private
     * @param {IEmbedConfiguration | models.ICommonEmbedConfiguration} config
     * @hidden
     */
    Embed.prototype.addLocaleToEmbedUrl = function (config) {
        if (!config.settings) {
            return;
        }
        var localeSettings = config.settings.localeSettings;
        if (localeSettings && localeSettings.language) {
            this.config.embedUrl = utils.addParamToUrl(this.config.embedUrl, 'language', localeSettings.language);
        }
        if (localeSettings && localeSettings.formatLocale) {
            this.config.embedUrl = utils.addParamToUrl(this.config.embedUrl, 'formatLocale', localeSettings.formatLocale);
        }
    };
    /**
     * Gets an embed url from the first available location: options, attribute.
     *
     * @private
     * @returns {string}
     * @hidden
     */
    Embed.prototype.getEmbedUrl = function (isBootstrap) {
        var embedUrl = this.config.embedUrl || this.element.getAttribute(Embed.embedUrlAttribute);
        if (isBootstrap && !embedUrl) {
            // Prepare flow, embed url was not provided, use hostname to build embed url.
            embedUrl = this.getDefaultEmbedUrl(this.config.hostname);
        }
        if (typeof embedUrl !== 'string' || embedUrl.length === 0) {
            throw new Error("Embed Url is required, but it was not found. You must provide an embed url either as part of embed configuration or as attribute '" + Embed.embedUrlAttribute + "'.");
        }
        return embedUrl;
    };
    /**
     * @hidden
     */
    Embed.prototype.getDefaultEmbedUrl = function (hostname) {
        if (!hostname) {
            hostname = Embed.defaultEmbedHostName;
        }
        var endpoint = this.getDefaultEmbedUrlEndpoint();
        // Trim spaces to fix user mistakes.
        hostname = hostname.toLowerCase().trim();
        if (hostname.indexOf("http://") === 0) {
            throw new Error("HTTP is not allowed. HTTPS is required");
        }
        if (hostname.indexOf("https://") === 0) {
            return hostname + "/" + endpoint;
        }
        return "https://" + hostname + "/" + endpoint;
    };
    /**
     * Gets a unique ID from the first available location: options, attribute.
     * If neither is provided generate a unique string.
     *
     * @private
     * @returns {string}
     * @hidden
     */
    Embed.prototype.getUniqueId = function () {
        return this.config.uniqueId || this.element.getAttribute(Embed.nameAttribute) || utils.createRandomString();
    };
    /**
     * Gets the group ID from the first available location: options, embeddedUrl.
     *
     * @private
     * @returns {string}
     * @hidden
     */
    Embed.prototype.getGroupId = function () {
        return this.config.groupId || Embed.findGroupIdFromEmbedUrl(this.config.embedUrl);
    };
    /**
     * Requests the browser to render the component's iframe in fullscreen mode.
     */
    Embed.prototype.fullscreen = function () {
        var requestFullScreen = this.iframe.requestFullscreen || this.iframe.msRequestFullscreen || this.iframe.mozRequestFullScreen || this.iframe.webkitRequestFullscreen;
        requestFullScreen.call(this.iframe);
    };
    /**
     * Requests the browser to exit fullscreen mode.
     */
    Embed.prototype.exitFullscreen = function () {
        if (!this.isFullscreen(this.iframe)) {
            return;
        }
        var exitFullscreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen;
        exitFullscreen.call(document);
    };
    /**
     * Returns true if the iframe is rendered in fullscreen mode,
     * otherwise returns false.
     *
     * @private
     * @param {HTMLIFrameElement} iframe
     * @returns {boolean}
     * @hidden
     */
    Embed.prototype.isFullscreen = function (iframe) {
        var options = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullscreenScreenElement', 'msFullscreenElement'];
        return options.some(function (option) { return document[option] === iframe; });
    };
    /**
     * Sets Iframe for embed
     * @hidden
     */
    Embed.prototype.setIframe = function (isLoad, phasedRender, isBootstrap) {
        var _this = this;
        if (!this.iframe) {
            var iframeContent = document.createElement("iframe");
            var embedUrl = this.config.uniqueId ? utils.addParamToUrl(this.config.embedUrl, 'uid', this.config.uniqueId) : this.config.embedUrl;
            iframeContent.style.width = '100%';
            iframeContent.style.height = '100%';
            iframeContent.setAttribute("src", embedUrl);
            iframeContent.setAttribute("scrolling", "no");
            iframeContent.setAttribute("allowfullscreen", "true");
            var node = this.element;
            while (node.firstChild) {
                node.removeChild(node.firstChild);
            }
            node.appendChild(iframeContent);
            this.iframe = node.firstChild;
        }
        if (isLoad) {
            if (!isBootstrap) {
                // Validate config if it's not a bootstrap case.
                var errors = this.validate(this.config);
                if (errors) {
                    throw errors;
                }
            }
            this.iframe.addEventListener('load', function () {
                _this.iframeLoaded = true;
                _this.load(phasedRender);
            }, false);
            if (this.service.getNumberOfComponents() <= Embed.maxFrontLoadTimes) {
                this.frontLoadHandler = function () {
                    _this.frontLoadSendConfig(_this.config);
                };
                // 'ready' event is fired by the embedded element (not by the iframe)
                this.element.addEventListener('ready', this.frontLoadHandler, false);
            }
        }
        else {
            this.iframe.addEventListener('load', function () { return _this.createReport(_this.createConfig); }, false);
        }
    };
    /**
     * Set the component title for accessibility. In case of iframes, this method will change the iframe title.
     */
    Embed.prototype.setComponentTitle = function (title) {
        if (!this.iframe) {
            return;
        }
        if (title == null) {
            this.iframe.removeAttribute("title");
        }
        else {
            this.iframe.setAttribute("title", title);
        }
    };
    /**
     * Sets element's tabindex attribute
     */
    Embed.prototype.setComponentTabIndex = function (tabIndex) {
        if (!this.element) {
            return;
        }
        this.element.setAttribute("tabindex", (tabIndex == null) ? "0" : tabIndex.toString());
    };
    /**
     * Removes element's tabindex attribute
     */
    Embed.prototype.removeComponentTabIndex = function (tabIndex) {
        if (!this.element) {
            return;
        }
        this.element.removeAttribute("tabindex");
    };
    /**
     * Adds the ability to get groupId from url.
     * By extracting the ID we can ensure that the ID is always explicitly provided as part of the load configuration.
     *
     * @hidden
     * @static
     * @param {string} url
     * @returns {string}
     */
    Embed.findGroupIdFromEmbedUrl = function (url) {
        var groupIdRegEx = /groupId="?([^&]+)"?/;
        var groupIdMatch = url.match(groupIdRegEx);
        var groupId;
        if (groupIdMatch) {
            groupId = groupIdMatch[1];
        }
        return groupId;
    };
    /**
     * Sends the config for front load calls, after 'ready' message is received from the iframe
     * @hidden
     */
    Embed.prototype.frontLoadSendConfig = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var errors, response, response_7;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!config.accessToken) {
                            return [2 /*return*/];
                        }
                        errors = this.validate(config);
                        if (errors) {
                            throw errors;
                        }
                        // contentWindow must be initialized
                        if (this.iframe.contentWindow == null)
                            return [2 /*return*/];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/frontload/config", config, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_7 = _a.sent();
                        throw response_7.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /** @hidden */
    Embed.allowedEvents = ["loaded", "saved", "rendered", "saveAsTriggered", "error", "dataSelected", "buttonClicked"];
    /** @hidden */
    Embed.accessTokenAttribute = 'powerbi-access-token';
    /** @hidden */
    Embed.embedUrlAttribute = 'powerbi-embed-url';
    /** @hidden */
    Embed.nameAttribute = 'powerbi-name';
    /** @hidden */
    Embed.typeAttribute = 'powerbi-type';
    /** @hidden */
    Embed.defaultEmbedHostName = "https://app.powerbi.com";
    /** @hidden */
    Embed.maxFrontLoadTimes = 2;
    return Embed;
}());
exports.Embed = Embed;


/***/ }),

/***/ "./src/errors.ts":
/*!***********************!*\
  !*** ./src/errors.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.EmbedUrlNotSupported = exports.APINotSupportedForRDLError = void 0;
exports.APINotSupportedForRDLError = "This API is currently not supported for RDL reports";
exports.EmbedUrlNotSupported = "Embed URL is invalid for this scenario. Please use Power BI REST APIs to get the valid URL";


/***/ }),

/***/ "./src/factories.ts":
/*!**************************!*\
  !*** ./src/factories.ts ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.routerFactory = exports.wpmpFactory = exports.hpmFactory = void 0;
var config_1 = __webpack_require__(/*! ./config */ "./src/config.ts");
var wpmp = __webpack_require__(/*! window-post-message-proxy */ "./node_modules/window-post-message-proxy/dist/windowPostMessageProxy.js");
var hpm = __webpack_require__(/*! http-post-message */ "./node_modules/http-post-message/dist/httpPostMessage.js");
var router = __webpack_require__(/*! powerbi-router */ "./node_modules/powerbi-router/dist/router.js");
exports.hpmFactory = function (wpmp, defaultTargetWindow, sdkVersion, sdkType) {
    if (sdkVersion === void 0) { sdkVersion = config_1.default.version; }
    if (sdkType === void 0) { sdkType = config_1.default.type; }
    return new hpm.HttpPostMessage(wpmp, {
        'x-sdk-type': sdkType,
        'x-sdk-version': sdkVersion
    }, defaultTargetWindow);
};
exports.wpmpFactory = function (name, logMessages, eventSourceOverrideWindow) {
    return new wpmp.WindowPostMessageProxy({
        processTrackingProperties: {
            addTrackingProperties: hpm.HttpPostMessage.addTrackingProperties,
            getTrackingProperties: hpm.HttpPostMessage.getTrackingProperties,
        },
        isErrorMessage: hpm.HttpPostMessage.isErrorMessage,
        suppressWarnings: true,
        name: name,
        logMessages: logMessages,
        eventSourceOverrideWindow: eventSourceOverrideWindow
    });
};
exports.routerFactory = function (wpmp) {
    return new router.Router(wpmp);
};


/***/ }),

/***/ "./src/page.ts":
/*!*********************!*\
  !*** ./src/page.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Page = void 0;
var visualDescriptor_1 = __webpack_require__(/*! ./visualDescriptor */ "./src/visualDescriptor.ts");
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
var errors = __webpack_require__(/*! ./errors */ "./src/errors.ts");
/**
 * A Power BI report page
 *
 * @export
 * @class Page
 * @implements {IPageNode}
 * @implements {IFilterable}
 */
var Page = /** @class */ (function () {
    /**
     * Creates an instance of a Power BI report page.
     *
     * @param {IReportNode} report
     * @param {string} name
     * @param {string} [displayName]
     * @param {boolean} [isActivePage]
     * @param {models.SectionVisibility} [visibility]
     * @hidden
     */
    function Page(report, name, displayName, isActivePage, visibility, defaultSize, defaultDisplayOption) {
        this.report = report;
        this.name = name;
        this.displayName = displayName;
        this.isActive = isActivePage;
        this.visibility = visibility;
        this.defaultSize = defaultSize;
        this.defaultDisplayOption = defaultDisplayOption;
    }
    /**
     * Gets all page level filters within the report.
     *
     * ```javascript
     * page.getFilters()
     *  .then(filters => { ... });
     * ```
     *
     * @returns {(Promise<models.IFilter[]>)}
     */
    Page.prototype.getFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.report.service.hpm.get("/report/pages/" + this.name + "/filters", { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Delete the page from the report
     *
     * ```javascript
     * // Delete the page from the report
     * page.delete();
     * ```
     *
     * @returns {Promise<void>}
     */
    Page.prototype.delete = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.report.service.hpm.delete("/report/pages/" + this.name, {}, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Removes all filters from this page of the report.
     *
     * ```javascript
     * page.removeFilters();
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Page.prototype.removeFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.setFilters([])];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Makes the current page the active page of the report.
     *
     * ```javascript
     * page.setActive();
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Page.prototype.setActive = function () {
        return __awaiter(this, void 0, void 0, function () {
            var page, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        page = {
                            name: this.name,
                            displayName: null,
                            isActive: true
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.report.service.hpm.put('/report/pages/active', page, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sets all filters on the current page.
     *
     * ```javascript
     * page.setFilters(filters);
     *   .catch(errors => { ... });
     * ```
     *
     * @param {(models.IFilter[])} filters
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Page.prototype.setFilters = function (filters) {
        return __awaiter(this, void 0, void 0, function () {
            var response_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.report.service.hpm.put("/report/pages/" + this.name + "/filters", filters, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_4 = _a.sent();
                        throw response_4.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Set displayName to the current page.
     *
     * ```javascript
     * page.setName(displayName);
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Page.prototype.setDisplayName = function (displayName) {
        return __awaiter(this, void 0, void 0, function () {
            var page, response_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        page = {
                            name: this.name,
                            displayName: displayName,
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.report.service.hpm.put("/report/pages/" + this.name + "/name", page, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_5 = _a.sent();
                        throw response_5.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets all the visuals on the page.
     *
     * ```javascript
     * page.getVisuals()
     *   .then(visuals => { ... });
     * ```
     *
     * @returns {Promise<VisualDescriptor[]>}
     */
    Page.prototype.getVisuals = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_6;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.report.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.report.service.hpm.get("/report/pages/" + this.name + "/visuals", { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body
                                .map(function (visual) {
                                return new visualDescriptor_1.VisualDescriptor(_this, visual.name, visual.title, visual.type, visual.layout);
                            })];
                    case 3:
                        response_6 = _a.sent();
                        throw response_6.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Checks if page has layout.
     *
     * ```javascript
     * page.hasLayout(layoutType)
     *  .then(hasLayout: boolean => { ... });
     * ```
     *
     * @returns {(Promise<boolean>)}
     */
    Page.prototype.hasLayout = function (layoutType) {
        return __awaiter(this, void 0, void 0, function () {
            var layoutTypeEnum, response, response_7;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.report.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        layoutTypeEnum = models.LayoutType[layoutType];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.report.service.hpm.get("/report/pages/" + this.name + "/layoutTypes/" + layoutTypeEnum, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_7 = _a.sent();
                        throw response_7.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    return Page;
}());
exports.Page = Page;


/***/ }),

/***/ "./src/powerbi-client.ts":
/*!*******************************!*\
  !*** ./src/powerbi-client.ts ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.models = exports.factories = exports.service = void 0;
/**
 * @hidden
 */
var service = __webpack_require__(/*! ./service */ "./src/service.ts");
exports.service = service;
var factories = __webpack_require__(/*! ./factories */ "./src/factories.ts");
exports.factories = factories;
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
exports.models = models;
var report_1 = __webpack_require__(/*! ./report */ "./src/report.ts");
Object.defineProperty(exports, "Report", { enumerable: true, get: function () { return report_1.Report; } });
var dashboard_1 = __webpack_require__(/*! ./dashboard */ "./src/dashboard.ts");
Object.defineProperty(exports, "Dashboard", { enumerable: true, get: function () { return dashboard_1.Dashboard; } });
var tile_1 = __webpack_require__(/*! ./tile */ "./src/tile.ts");
Object.defineProperty(exports, "Tile", { enumerable: true, get: function () { return tile_1.Tile; } });
var embed_1 = __webpack_require__(/*! ./embed */ "./src/embed.ts");
Object.defineProperty(exports, "Embed", { enumerable: true, get: function () { return embed_1.Embed; } });
var page_1 = __webpack_require__(/*! ./page */ "./src/page.ts");
Object.defineProperty(exports, "Page", { enumerable: true, get: function () { return page_1.Page; } });
var qna_1 = __webpack_require__(/*! ./qna */ "./src/qna.ts");
Object.defineProperty(exports, "Qna", { enumerable: true, get: function () { return qna_1.Qna; } });
var visual_1 = __webpack_require__(/*! ./visual */ "./src/visual.ts");
Object.defineProperty(exports, "Visual", { enumerable: true, get: function () { return visual_1.Visual; } });
var visualDescriptor_1 = __webpack_require__(/*! ./visualDescriptor */ "./src/visualDescriptor.ts");
Object.defineProperty(exports, "VisualDescriptor", { enumerable: true, get: function () { return visualDescriptor_1.VisualDescriptor; } });
/**
 * Makes Power BI available to the global object for use in applications that don't have module loading support.
 *
 * Note: create an instance of the class with the default configuration for normal usage, or save the class so that you can create an instance of the service.
 */
var powerbi = new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory);
window.powerbi = powerbi;


/***/ }),

/***/ "./src/qna.ts":
/*!********************!*\
  !*** ./src/qna.ts ***!
  \********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Qna = void 0;
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
/**
 * The Power BI Q&A embed component
 *
 * @export
 * @class Qna
 * @extends {Embed}
 */
var Qna = /** @class */ (function (_super) {
    __extends(Qna, _super);
    /**
     * @hidden
     */
    function Qna(service, element, config, phasedRender, isBootstrap) {
        var _this = _super.call(this, service, element, config, /* iframe */ undefined, phasedRender, isBootstrap) || this;
        _this.loadPath = "/qna/load";
        _this.phasedLoadPath = "/qna/prepare";
        Array.prototype.push.apply(_this.allowedEvents, Qna.allowedEvents);
        return _this;
    }
    /**
     * The ID of the Q&A embed component
     *
     * @returns {string}
     */
    Qna.prototype.getId = function () {
        return null;
    };
    /**
     * Change the question of the Q&A embed component
     *
     * @param {string} question - question which will render Q&A data
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Qna.prototype.setQuestion = function (question) {
        return __awaiter(this, void 0, void 0, function () {
            var qnaData, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        qnaData = {
                            question: question
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post('/qna/interpret', qnaData, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Handle config changes.
     *
     * @returns {void}
     */
    Qna.prototype.configChanged = function (isBootstrap) {
        // Nothing to do in Q&A embed.
    };
    /**
     * @hidden
     * @returns {string}
     */
    Qna.prototype.getDefaultEmbedUrlEndpoint = function () {
        return "qnaEmbed";
    };
    /**
     * Validate load configuration.
     */
    Qna.prototype.validate = function (config) {
        return models.validateLoadQnaConfiguration(config);
    };
    /** @hidden */
    Qna.type = "Qna";
    /** @hidden */
    Qna.allowedEvents = ["loaded", "visualRendered"];
    return Qna;
}(embed.Embed));
exports.Qna = Qna;


/***/ }),

/***/ "./src/report.ts":
/*!***********************!*\
  !*** ./src/report.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Report = void 0;
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
var errors = __webpack_require__(/*! ./errors */ "./src/errors.ts");
var page_1 = __webpack_require__(/*! ./page */ "./src/page.ts");
var bookmarksManager_1 = __webpack_require__(/*! ./bookmarksManager */ "./src/bookmarksManager.ts");
/**
 * The Power BI Report embed component
 *
 * @export
 * @class Report
 * @extends {embed.Embed}
 * @implements {IReportNode}
 * @implements {IFilterable}
 */
var Report = /** @class */ (function (_super) {
    __extends(Report, _super);
    /**
     * Creates an instance of a Power BI Report.
     *
     * @param {service.Service} service
     * @param {HTMLElement} element
     * @param {embed.IEmbedConfiguration} config
     * @hidden
     */
    function Report(service, element, baseConfig, phasedRender, isBootstrap, iframe) {
        var _this = this;
        var config = baseConfig;
        _this = _super.call(this, service, element, config, iframe, phasedRender, isBootstrap) || this;
        _this.loadPath = "/report/load";
        _this.phasedLoadPath = "/report/prepare";
        Array.prototype.push.apply(_this.allowedEvents, Report.allowedEvents);
        _this.bookmarksManager = new bookmarksManager_1.BookmarksManager(service, config, _this.iframe);
        return _this;
    }
    /**
     * Adds backwards compatibility for the previous load configuration, which used the reportId query parameter to specify the report ID
     * (e.g. http://embedded.powerbi.com/appTokenReportEmbed?reportId=854846ed-2106-4dc2-bc58-eb77533bf2f1).
     *
     * By extracting the ID we can ensure that the ID is always explicitly provided as part of the load configuration.
     * @hidden
     * @static
     * @param {string} url
     * @returns {string}
     */
    Report.findIdFromEmbedUrl = function (url) {
        var reportIdRegEx = /reportId="?([^&]+)"?/;
        var reportIdMatch = url.match(reportIdRegEx);
        var reportId;
        if (reportIdMatch) {
            reportId = reportIdMatch[1];
        }
        return reportId;
    };
    /**
     * Render a preloaded report, using phased embedding API
     *
     * ```javascript
     * // Load report
     * var report = powerbi.load(element, config);
     *
     * ...
     *
     * // Render report
     * report.render()
     * ```
     *
     * @returns {Promise<void>}
     */
    Report.prototype.render = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.post("/report/render", config, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Add an empty page to the report
     *
     * ```javascript
     * // Add a page to the report with "Sales" as the page display name
     * report.addPage("Sales");
     * ```
     *
     * @returns {Promise<Page>}
     */
    Report.prototype.addPage = function (displayName) {
        return __awaiter(this, void 0, void 0, function () {
            var request, response, page, response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        request = {
                            displayName: displayName
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post("/report/addPage", request, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        page = response.body;
                        return [2 /*return*/, new page_1.Page(this, page.name, page.displayName, page.isActive, page.visibility, page.defaultSize, page.defaultDisplayOption)];
                    case 3:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Delete a page from a report
     *
     * ```javascript
     * // Delete a page from a report by pageName (PageName is different than the display name and can be acquired from the getPages API)
     * report.deletePage("ReportSection145");
     * ```
     *
     * @returns {Promise<void>}
     */
    Report.prototype.deletePage = function (pageName) {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.delete("/report/pages/" + pageName, {}, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Rename a page from a report
     *
     * ```javascript
     * // Rename a page from a report by changing displayName (pageName is different from the display name and can be acquired from the getPages API)
     * report.renamePage("ReportSection145", "Sales");
     * ```
     *
     * @returns {Promise<void>}
     */
    Report.prototype.renamePage = function (pageName, displayName) {
        return __awaiter(this, void 0, void 0, function () {
            var page, response, response_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        page = {
                            name: pageName,
                            displayName: displayName,
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.put("/report/pages/" + pageName + "/name", page, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_4 = _a.sent();
                        throw response_4.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets filters that are applied at the report level.
     *
     * ```javascript
     * // Get filters applied at report level
     * report.getFilters()
     *   .then(filters => {
     *     ...
     *   });
     * ```
     *
     * @returns {Promise<models.IFilter[]>}
     */
    Report.prototype.getFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.get("/report/filters", { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_5 = _a.sent();
                        throw response_5.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets the report ID from the first available location: options, attribute, embed url.
     *
     * @returns {string}
     */
    Report.prototype.getId = function () {
        var config = this.config;
        var reportId = config.id || this.element.getAttribute(Report.reportIdAttribute) || Report.findIdFromEmbedUrl(config.embedUrl);
        if (typeof reportId !== 'string' || reportId.length === 0) {
            throw new Error("Report id is required, but it was not found. You must provide an id either as part of embed configuration or as attribute '" + Report.reportIdAttribute + "'.");
        }
        return reportId;
    };
    /**
     * Gets the list of pages within the report.
     *
     * ```javascript
     * report.getPages()
     *  .then(pages => {
     *      ...
     *  });
     * ```
     *
     * @returns {Promise<Page[]>}
     */
    Report.prototype.getPages = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_6;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.get('/report/pages', { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body
                                .map(function (page) {
                                return new page_1.Page(_this, page.name, page.displayName, page.isActive, page.visibility, page.defaultSize, page.defaultDisplayOption);
                            })];
                    case 3:
                        response_6 = _a.sent();
                        throw response_6.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Creates an instance of a Page.
     *
     * Normally you would get Page objects by calling `report.getPages()`, but in the case
     * that the page name is known and you want to perform an action on a page without having to retrieve it
     * you can create it directly.
     *
     * Note: Because you are creating the page manually there is no guarantee that the page actually exists in the report, and subsequent requests could fail.
     *
     * @param {string} name
     * @param {string} [displayName]
     * @param {boolean} [isActive]
     * @returns {Page}
     * @hidden
     */
    Report.prototype.page = function (name, displayName, isActive, visibility) {
        return new page_1.Page(this, name, displayName, isActive, visibility);
    };
    /**
     * Prints the active page of the report by invoking `window.print()` on the embed iframe component.
     */
    Report.prototype.print = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_7;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post('/report/print', null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_7 = _a.sent();
                        throw response_7.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Removes all filters at the report level.
     *
     * ```javascript
     * report.removeFilters();
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Report.prototype.removeFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        return [4 /*yield*/, this.setFilters([])];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Sets the active page of the report.
     *
     * ```javascript
     * report.setPage("page2")
     *  .catch(error => { ... });
     * ```
     *
     * @param {string} pageName
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Report.prototype.setPage = function (pageName) {
        return __awaiter(this, void 0, void 0, function () {
            var page, response_8;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        page = {
                            name: pageName,
                            displayName: null,
                            isActive: true
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.put('/report/pages/active', page, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_8 = _a.sent();
                        throw response_8.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sets filters at the report level.
     *
     * ```javascript
     * const filters: [
     *    ...
     * ];
     *
     * report.setFilters(filters)
     *  .catch(errors => {
     *    ...
     *  });
     * ```
     *
     * @param {(models.IFilter[])} filters
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Report.prototype.setFilters = function (filters) {
        return __awaiter(this, void 0, void 0, function () {
            var response_9;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.put("/report/filters", filters, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_9 = _a.sent();
                        throw response_9.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Updates visibility settings for the filter pane and the page navigation pane.
     *
     * ```javascript
     * const newSettings = {
     *   navContentPaneEnabled: true,
     *   filterPaneEnabled: false
     * };
     *
     * report.updateSettings(newSettings)
     *   .catch(error => { ... });
     * ```
     *
     * @param {models.ISettings} settings
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Report.prototype.updateSettings = function (settings) {
        return __awaiter(this, void 0, void 0, function () {
            var response_10;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl) && settings.customLayout != null) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.patch('/report/settings', settings, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_10 = _a.sent();
                        throw response_10.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Validate load configuration.
     *
     * @hidden
     */
    Report.prototype.validate = function (config) {
        return models.validateReportLoad(config);
    };
    /**
     * Handle config changes.
     *
     * @returns {void}
     */
    Report.prototype.configChanged = function (isBootstrap) {
        var config = this.config;
        if (this.isMobileSettings(config.settings))
            config.embedUrl = utils.addParamToUrl(config.embedUrl, "isMobile", "true");
        // Calculate settings from HTML element attributes if available.
        var filterPaneEnabledAttribute = this.element.getAttribute(Report.filterPaneEnabledAttribute);
        var navContentPaneEnabledAttribute = this.element.getAttribute(Report.navContentPaneEnabledAttribute);
        var elementAttrSettings = {
            filterPaneEnabled: (filterPaneEnabledAttribute == null) ? undefined : (filterPaneEnabledAttribute !== "false"),
            navContentPaneEnabled: (navContentPaneEnabledAttribute == null) ? undefined : (navContentPaneEnabledAttribute !== "false")
        };
        // Set the settings back into the config.
        this.config.settings = utils.assign({}, elementAttrSettings, config.settings);
        if (isBootstrap) {
            return;
        }
        config.id = this.getId();
    };
    /**
     * @hidden
     * @returns {string}
     */
    Report.prototype.getDefaultEmbedUrlEndpoint = function () {
        return "reportEmbed";
    };
    /**
     * Switch Report view mode.
     *
     * @returns {Promise<void>}
     */
    Report.prototype.switchMode = function (viewMode) {
        return __awaiter(this, void 0, void 0, function () {
            var newMode, url, response, response_11;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (typeof viewMode === "string") {
                            newMode = viewMode;
                        }
                        else {
                            newMode = this.viewModeToString(viewMode);
                        }
                        url = '/report/switchMode/' + newMode;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.post(url, null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_11 = _a.sent();
                        throw response_11.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
    * Refreshes data sources for the report.
    *
    * ```javascript
    * report.refresh();
    * ```
    */
    Report.prototype.refresh = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_12;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.post('/report/refresh', null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_12 = _a.sent();
                        throw response_12.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * checks if the report is saved.
     *
     * ```javascript
     * report.isSaved()
     * ```
     *
     * @returns {Promise<boolean>}
     */
    Report.prototype.isSaved = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        return [4 /*yield*/, utils.isSavedInternal(this.service.hpm, this.config.uniqueId, this.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Apply a theme to the report
     *
     * ```javascript
     * report.applyTheme(theme);
     * ```
     */
    Report.prototype.applyTheme = function (theme) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        return [4 /*yield*/, this.applyThemeInternal(theme)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
    * Reset and apply the default theme of the report
    *
    * ```javascript
    * report.resetTheme();
    * ```
    */
    Report.prototype.resetTheme = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (utils.isRDLEmbed(this.config.embedUrl)) {
                            return [2 /*return*/, Promise.reject(errors.APINotSupportedForRDLError)];
                        }
                        return [4 /*yield*/, this.applyThemeInternal({})];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
    * Reset user's filters, slicers, and other data view changes to the default state of the report
    *
    * ```javascript
    * report.resetPersistentFilters();
    * ```
    */
    Report.prototype.resetPersistentFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response_13;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.delete("/report/userState", null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_13 = _a.sent();
                        throw response_13.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
    * Save user's filters, slicers, and other data view changes of the report
    *
    * ```javascript
    * report.savePersistentFilters();
    * ```
    */
    Report.prototype.savePersistentFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response_14;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.post("/report/userState", null, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_14 = _a.sent();
                        throw response_14.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
      * Returns if there are user's filters, slicers, or other data view changes applied on the report.
      * If persistent filters is disable, returns false.
      *
      * ```javascript
      * report.arePersistentFiltersApplied();
      * ```
      *
      * @returns {Promise<boolean>}
      */
    Report.prototype.arePersistentFiltersApplied = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_15;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.get("/report/isUserStateApplied", { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_15 = _a.sent();
                        throw response_15.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @hidden
     */
    Report.prototype.applyThemeInternal = function (theme) {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_16;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.service.hpm.put('/report/theme', theme, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_16 = _a.sent();
                        throw response_16.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @hidden
     */
    Report.prototype.viewModeToString = function (viewMode) {
        var mode;
        switch (viewMode) {
            case models.ViewMode.Edit:
                mode = "edit";
                break;
            case models.ViewMode.View:
                mode = "view";
                break;
        }
        return mode;
    };
    /**
     * @hidden
     */
    Report.prototype.isMobileSettings = function (settings) {
        return settings && (settings.layoutType === models.LayoutType.MobileLandscape || settings.layoutType === models.LayoutType.MobilePortrait);
    };
    /** @hidden */
    Report.allowedEvents = ["filtersApplied", "pageChanged", "commandTriggered", "swipeStart", "swipeEnd", "bookmarkApplied", "dataHyperlinkClicked", "visualRendered", "visualClicked", "selectionChanged"];
    /** @hidden */
    Report.reportIdAttribute = 'powerbi-report-id';
    /** @hidden */
    Report.filterPaneEnabledAttribute = 'powerbi-settings-filter-pane-enabled';
    /** @hidden */
    Report.navContentPaneEnabledAttribute = 'powerbi-settings-nav-content-pane-enabled';
    /** @hidden */
    Report.typeAttribute = 'powerbi-type';
    /** @hidden */
    Report.type = "Report";
    return Report;
}(embed.Embed));
exports.Report = Report;


/***/ }),

/***/ "./src/service.ts":
/*!************************!*\
  !*** ./src/service.ts ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.Service = void 0;
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
var report_1 = __webpack_require__(/*! ./report */ "./src/report.ts");
var create_1 = __webpack_require__(/*! ./create */ "./src/create.ts");
var dashboard_1 = __webpack_require__(/*! ./dashboard */ "./src/dashboard.ts");
var tile_1 = __webpack_require__(/*! ./tile */ "./src/tile.ts");
var page_1 = __webpack_require__(/*! ./page */ "./src/page.ts");
var qna_1 = __webpack_require__(/*! ./qna */ "./src/qna.ts");
var visual_1 = __webpack_require__(/*! ./visual */ "./src/visual.ts");
var utils = __webpack_require__(/*! ./util */ "./src/util.ts");
/**
 * The Power BI Service embed component, which is the entry point to embed all other Power BI components into your application
 *
 * @export
 * @class Service
 * @implements {IService}
 */
var Service = /** @class */ (function () {
    /**
     * Creates an instance of a Power BI Service.
     *
     * @param {IHpmFactory} hpmFactory The http post message factory used in the postMessage communication layer
     * @param {IWpmpFactory} wpmpFactory The window post message factory used in the postMessage communication layer
     * @param {IRouterFactory} routerFactory The router factory used in the postMessage communication layer
     * @param {IServiceConfiguration} [config={}]
     * @hidden
     */
    function Service(hpmFactory, wpmpFactory, routerFactory, config) {
        var _this = this;
        if (config === void 0) { config = {}; }
        this.wpmp = wpmpFactory(config.wpmpName, config.logMessages);
        this.hpm = hpmFactory(this.wpmp, null, config.version, config.type);
        this.router = routerFactory(this.wpmp);
        this.uniqueSessionId = utils.generateUUID();
        /**
         * Adds handler for report events.
         */
        this.router.post("/reports/:uniqueId/events/:eventName", function (req, res) {
            var event = {
                type: 'report',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        this.router.post("/reports/:uniqueId/pages/:pageName/events/:eventName", function (req, res) {
            var event = {
                type: 'report',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        this.router.post("/reports/:uniqueId/pages/:pageName/visuals/:visualName/events/:eventName", function (req, res) {
            var event = {
                type: 'report',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        this.router.post("/dashboards/:uniqueId/events/:eventName", function (req, res) {
            var event = {
                type: 'dashboard',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        this.router.post("/tile/:uniqueId/events/:eventName", function (req, res) {
            var event = {
                type: 'tile',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        /**
         * Adds handler for Q&A events.
         */
        this.router.post("/qna/:uniqueId/events/:eventName", function (req, res) {
            var event = {
                type: 'qna',
                id: req.params.uniqueId,
                name: req.params.eventName,
                value: req.body
            };
            _this.handleEvent(event);
        });
        /**
         * Adds handler for front load 'ready' message.
         */
        this.router.post("/ready/:uniqueId", function (req, res) {
            var event = {
                type: 'report',
                id: req.params.uniqueId,
                name: 'ready',
                value: req.body
            };
            _this.handleEvent(event);
        });
        this.embeds = [];
        // TODO: Change when Object.assign is available.
        this.config = utils.assign({}, Service.defaultConfig, config);
        if (this.config.autoEmbedOnContentLoaded) {
            this.enableAutoEmbed();
        }
    }
    /**
     * Creates new report
     * @param {HTMLElement} element
     * @param {embed.IEmbedConfiguration} [config={}]
     * @returns {embed.Embed}
     */
    Service.prototype.createReport = function (element, config) {
        config.type = 'create';
        var powerBiElement = element;
        var component = new create_1.Create(this, powerBiElement, config);
        powerBiElement.powerBiEmbed = component;
        this.addOrOverwriteEmbed(component, element);
        return component;
    };
    /**
     * TODO: Add a description here
     *
     * @param {HTMLElement} [container]
     * @param {embed.IEmbedConfiguration} [config=undefined]
     * @returns {embed.Embed[]}
     * @hidden
     */
    Service.prototype.init = function (container, config) {
        var _this = this;
        if (config === void 0) { config = undefined; }
        container = (container && container instanceof HTMLElement) ? container : document.body;
        var elements = Array.prototype.slice.call(container.querySelectorAll("[" + embed.Embed.embedUrlAttribute + "]"));
        return elements.map(function (element) { return _this.embed(element, config); });
    };
    /**
     * Given a configuration based on an HTML element,
     * if the component has already been created and attached to the element, reuses the component instance and existing iframe,
     * otherwise creates a new component instance.
     *
     * @param {HTMLElement} element
     * @param {embed.IEmbedConfigurationBase} [config={}]
     * @returns {embed.Embed}
     */
    Service.prototype.embed = function (element, config) {
        if (config === void 0) { config = {}; }
        return this.embedInternal(element, config);
    };
    /**
     * Given a configuration based on an HTML element,
     * if the component has already been created and attached to the element, reuses the component instance and existing iframe,
     * otherwise creates a new component instance.
     * This is used for the phased embedding API, once element is loaded successfully, one can call 'render' on it.
     *
     * @param {HTMLElement} element
     * @param {embed.IEmbedConfigurationBase} [config={}]
     * @returns {embed.Embed}
     */
    Service.prototype.load = function (element, config) {
        if (config === void 0) { config = {}; }
        return this.embedInternal(element, config, /* phasedRender */ true, /* isBootstrap */ false);
    };
    /**
     * Given an HTML element and entityType, creates a new component instance, and bootstrap the iframe for embedding.
     *
     * @param {HTMLElement} element
     * @param {embed.IBootstrapEmbedConfiguration} config: a bootstrap config which is an embed config without access token.
     */
    Service.prototype.bootstrap = function (element, config) {
        return this.embedInternal(element, config, /* phasedRender */ false, /* isBootstrap */ true);
    };
    /** @hidden */
    Service.prototype.embedInternal = function (element, config, phasedRender, isBootstrap) {
        if (config === void 0) { config = {}; }
        var component;
        var powerBiElement = element;
        if (powerBiElement.powerBiEmbed) {
            if (isBootstrap) {
                throw new Error("Attempted to bootstrap element " + element.outerHTML + ", but the element is already a powerbi element.");
            }
            component = this.embedExisting(powerBiElement, config, phasedRender);
        }
        else {
            component = this.embedNew(powerBiElement, config, phasedRender, isBootstrap);
        }
        return component;
    };
    /** @hidden */
    Service.prototype.getNumberOfComponents = function () {
        if (!this.embeds) {
            return 0;
        }
        return this.embeds.length;
    };
    /** @hidden */
    Service.prototype.getSdkSessionId = function () {
        return this.uniqueSessionId;
    };
    /**
     * Given a configuration based on a Power BI element, saves the component instance that reference the element for later lookup.
     *
     * @private
     * @param {IPowerBiElement} element
     * @param {embed.IEmbedConfigurationBase} config
     * @returns {embed.Embed}
     * @hidden
     */
    Service.prototype.embedNew = function (element, config, phasedRender, isBootstrap) {
        var componentType = config.type || element.getAttribute(embed.Embed.typeAttribute);
        if (!componentType) {
            throw new Error("Attempted to embed using config " + JSON.stringify(config) + " on element " + element.outerHTML + ", but could not determine what type of component to embed. You must specify a type in the configuration or as an attribute such as '" + embed.Embed.typeAttribute + "=\"" + report_1.Report.type.toLowerCase() + "\"'.");
        }
        // Saves the type as part of the configuration so that it can be referenced later at a known location.
        config.type = componentType;
        var Component = utils.find(function (component) { return componentType === component.type.toLowerCase(); }, Service.components);
        if (!Component) {
            throw new Error("Attempted to embed component of type: " + componentType + " but did not find any matching component.  Please verify the type you specified is intended.");
        }
        var component = new Component(this, element, config, phasedRender, isBootstrap);
        element.powerBiEmbed = component;
        this.addOrOverwriteEmbed(component, element);
        return component;
    };
    /**
     * Given an element that already contains an embed component, load with a new configuration.
     *
     * @private
     * @param {IPowerBiElement} element
     * @param {embed.IEmbedConfigurationBase} config
     * @returns {embed.Embed}
     * @hidden
     */
    Service.prototype.embedExisting = function (element, config, phasedRender) {
        var component = utils.find(function (x) { return x.element === element; }, this.embeds);
        if (!component) {
            throw new Error("Attempted to embed using config " + JSON.stringify(config) + " on element " + element.outerHTML + " which already has embedded component associated, but could not find the existing component in the list of active components. This could indicate the embeds list is out of sync with the DOM, or the component is referencing the incorrect HTML element.");
        }
        // TODO: Multiple embedding to the same iframe is not supported in QnA
        if (config.type && config.type.toLowerCase() === "qna") {
            return this.embedNew(element, config);
        }
        /**
         * TODO: Dynamic embed type switching could be supported but there is work needed to prepare the service state and DOM cleanup.
         * remove all event handlers from the DOM, then reset the element to initial state which removes iframe, and removes from list of embeds
         * then we can call the embedNew function which would allow setting the proper embedUrl and construction of object based on the new type.
         */
        if (typeof config.type === "string" && config.type !== component.config.type) {
            /**
             * When loading report after create we want to use existing Iframe to optimize load period
             */
            if (config.type === "report" && component.config.type === "create") {
                var report = new report_1.Report(this, element, config, /* phasedRender */ false, /* isBootstrap */ false, element.powerBiEmbed.iframe);
                component.populateConfig(config, /* isBootstrap */ false);
                report.load();
                element.powerBiEmbed = report;
                this.addOrOverwriteEmbed(component, element);
                return report;
            }
            throw new Error("Embedding on an existing element with a different type than the previous embed object is not supported.  Attempted to embed using config " + JSON.stringify(config) + " on element " + element.outerHTML + ", but the existing element contains an embed of type: " + this.config.type + " which does not match the new type: " + config.type);
        }
        component.populateConfig(config, /* isBootstrap */ false);
        component.load(phasedRender);
        return component;
    };
    /**
     * Adds an event handler for DOMContentLoaded, which searches the DOM for elements that have the 'powerbi-embed-url' attribute,
     * and automatically attempts to embed a powerbi component based on information from other powerbi-* attributes.
     *
     * Note: Only runs if `config.autoEmbedOnContentLoaded` is true when the service is created.
     * This handler is typically useful only for applications that are rendered on the server so that all required data is available when the handler is called.
     *
     * @hidden
     */
    Service.prototype.enableAutoEmbed = function () {
        var _this = this;
        window.addEventListener('DOMContentLoaded', function (event) { return _this.init(document.body); }, false);
    };
    /**
     * Returns an instance of the component associated with the element.
     *
     * @param {HTMLElement} element
     * @returns {(Report | Tile)}
     */
    Service.prototype.get = function (element) {
        var powerBiElement = element;
        if (!powerBiElement.powerBiEmbed) {
            throw new Error("You attempted to get an instance of powerbi component associated with element: " + element.outerHTML + " but there was no associated instance.");
        }
        return powerBiElement.powerBiEmbed;
    };
    /**
     * Finds an embed instance by the name or unique ID that is provided.
     *
     * @param {string} uniqueId
     * @returns {(Report | Tile)}
     * @hidden
     */
    Service.prototype.find = function (uniqueId) {
        return utils.find(function (x) { return x.config.uniqueId === uniqueId; }, this.embeds);
    };
    /**
     * Removes embed components whose container element is same as the given element
     *
     * @param {Embed} component
     * @param {HTMLElement} element
     * @returns {void}
     * @hidden
     */
    Service.prototype.addOrOverwriteEmbed = function (component, element) {
        // remove embeds over the same div element.
        this.embeds = this.embeds.filter(function (embed) {
            return embed.element !== element;
        });
        this.embeds.push(component);
    };
    /**
     * Given an HTML element that has a component embedded within it, removes the component from the list of embedded components, removes the association between the element and the component, and removes the iframe.
     *
     * @param {HTMLElement} element
     * @returns {void}
     */
    Service.prototype.reset = function (element) {
        var powerBiElement = element;
        if (!powerBiElement.powerBiEmbed) {
            return;
        }
        /** Removes the element frontLoad listener if exists. */
        var embedElement = powerBiElement.powerBiEmbed;
        if (embedElement.frontLoadHandler) {
            embedElement.element.removeEventListener('ready', embedElement.frontLoadHandler, false);
        }
        /** Removes the component from an internal list of components. */
        utils.remove(function (x) { return x === powerBiElement.powerBiEmbed; }, this.embeds);
        /** Deletes a property from the HTML element. */
        delete powerBiElement.powerBiEmbed;
        /** Removes the iframe from the element. */
        var iframe = element.querySelector('iframe');
        if (iframe) {
            if (iframe.remove !== undefined) {
                iframe.remove();
            }
            else {
                /** Workaround for IE: unhandled rejection TypeError: object doesn't support property or method 'remove' */
                iframe.parentElement.removeChild(iframe);
            }
        }
    };
    /**
     * handles tile events
     *
     * @param {IEvent<any>} event
     * @hidden
     */
    Service.prototype.handleTileEvents = function (event) {
        if (event.type === 'tile') {
            this.handleEvent(event);
        }
    };
    /**
     * Given an event object, finds the embed component with the matching type and ID, and invokes its handleEvent method with the event object.
     *
     * @private
     * @param {IEvent<any>} event
     * @hidden
     */
    Service.prototype.handleEvent = function (event) {
        var embed = utils.find(function (embed) {
            return (embed.config.uniqueId === event.id);
        }, this.embeds);
        if (embed) {
            var value = event.value;
            if (event.name === 'pageChanged') {
                var pageKey = 'newPage';
                var page = value[pageKey];
                if (!page) {
                    throw new Error("Page model not found at 'event.value." + pageKey + "'.");
                }
                value[pageKey] = new page_1.Page(embed, page.name, page.displayName, true /* isActive */);
            }
            utils.raiseCustomEvent(embed.element, event.name, value);
        }
    };
    /**
     * API for warm starting powerbi embedded endpoints.
     * Use this API to preload Power BI Embedded in the background.
     *
     * @public
     * @param {embed.IEmbedConfigurationBase} [config={}]
     * @param {HTMLElement} [element=undefined]
     */
    Service.prototype.preload = function (config, element) {
        var iframeContent = document.createElement("iframe");
        iframeContent.setAttribute("style", "display:none;");
        iframeContent.setAttribute("src", config.embedUrl);
        iframeContent.setAttribute("scrolling", "no");
        iframeContent.setAttribute("allowfullscreen", "false");
        var node = element;
        if (!node) {
            node = document.getElementsByTagName("body")[0];
        }
        node.appendChild(iframeContent);
        iframeContent.onload = function () {
            utils.raiseCustomEvent(iframeContent, "preloaded", {});
        };
        return iframeContent;
    };
    /**
     * A list of components that this service can embed
     */
    Service.components = [
        tile_1.Tile,
        report_1.Report,
        dashboard_1.Dashboard,
        qna_1.Qna,
        visual_1.Visual
    ];
    /**
     * The default configuration for the service
     */
    Service.defaultConfig = {
        autoEmbedOnContentLoaded: false,
        onError: function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return console.log(args[0], args.slice(1));
        }
    };
    return Service;
}());
exports.Service = Service;


/***/ }),

/***/ "./src/tile.ts":
/*!*********************!*\
  !*** ./src/tile.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tile = void 0;
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var embed = __webpack_require__(/*! ./embed */ "./src/embed.ts");
/**
 * The Power BI tile embed component
 *
 * @export
 * @class Tile
 * @extends {Embed}
 */
var Tile = /** @class */ (function (_super) {
    __extends(Tile, _super);
    /**
     * @hidden
     */
    function Tile(service, element, baseConfig, phasedRender, isBootstrap) {
        var _this = this;
        var config = baseConfig;
        _this = _super.call(this, service, element, config, /* iframe */ undefined, phasedRender, isBootstrap) || this;
        _this.loadPath = "/tile/load";
        Array.prototype.push.apply(_this.allowedEvents, Tile.allowedEvents);
        return _this;
    }
    /**
     * The ID of the tile
     *
     * @returns {string}
     */
    Tile.prototype.getId = function () {
        var config = this.config;
        var tileId = config.id || Tile.findIdFromEmbedUrl(this.config.embedUrl);
        if (typeof tileId !== 'string' || tileId.length === 0) {
            throw new Error("Tile id is required, but it was not found. You must provide an id either as part of embed configuration.");
        }
        return tileId;
    };
    /**
     * Validate load configuration.
     */
    Tile.prototype.validate = function (config) {
        var embedConfig = config;
        return models.validateTileLoad(embedConfig);
    };
    /**
     * Handle config changes.
     *
     * @returns {void}
     */
    Tile.prototype.configChanged = function (isBootstrap) {
        if (isBootstrap) {
            return;
        }
        // Populate tile id into config object.
        this.config.id = this.getId();
    };
    /**
     * @hidden
     * @returns {string}
     */
    Tile.prototype.getDefaultEmbedUrlEndpoint = function () {
        return "tileEmbed";
    };
    /**
     * Adds the ability to get tileId from url.
     * By extracting the ID we can ensure that the ID is always explicitly provided as part of the load configuration.
     *
     * @hidden
     * @static
     * @param {string} url
     * @returns {string}
     */
    Tile.findIdFromEmbedUrl = function (url) {
        var tileIdRegEx = /tileId="?([^&]+)"?/;
        var tileIdMatch = url.match(tileIdRegEx);
        var tileId;
        if (tileIdMatch) {
            tileId = tileIdMatch[1];
        }
        return tileId;
    };
    /** @hidden */
    Tile.type = "Tile";
    /** @hidden */
    Tile.allowedEvents = ["tileClicked", "tileLoaded"];
    return Tile;
}(embed.Embed));
exports.Tile = Tile;


/***/ }),

/***/ "./src/util.ts":
/*!*********************!*\
  !*** ./src/util.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTimeDiffInMilliseconds = exports.getRandomValue = exports.autoAuthInEmbedUrl = exports.isRDLEmbed = exports.isSavedInternal = exports.addParamToUrl = exports.generateUUID = exports.createRandomString = exports.assign = exports.remove = exports.find = exports.findIndex = exports.raiseCustomEvent = void 0;
/**
 * Raises a custom event with event data on the specified HTML element.
 *
 * @export
 * @param {HTMLElement} element
 * @param {string} eventName
 * @param {*} eventData
 */
function raiseCustomEvent(element, eventName, eventData) {
    var customEvent;
    if (typeof CustomEvent === 'function') {
        customEvent = new CustomEvent(eventName, {
            detail: eventData,
            bubbles: true,
            cancelable: true
        });
    }
    else {
        customEvent = document.createEvent('CustomEvent');
        customEvent.initCustomEvent(eventName, true, true, eventData);
    }
    element.dispatchEvent(customEvent);
}
exports.raiseCustomEvent = raiseCustomEvent;
/**
 * Finds the index of the first value in an array that matches the specified predicate.
 *
 * @export
 * @template T
 * @param {(x: T) => boolean} predicate
 * @param {T[]} xs
 * @returns {number}
 */
function findIndex(predicate, xs) {
    if (!Array.isArray(xs)) {
        throw new Error("You attempted to call find with second parameter that was not an array. You passed: " + xs);
    }
    var index;
    xs.some(function (x, i) {
        if (predicate(x)) {
            index = i;
            return true;
        }
    });
    return index;
}
exports.findIndex = findIndex;
/**
 * Finds the first value in an array that matches the specified predicate.
 *
 * @export
 * @template T
 * @param {(x: T) => boolean} predicate
 * @param {T[]} xs
 * @returns {T}
 */
function find(predicate, xs) {
    var index = findIndex(predicate, xs);
    return xs[index];
}
exports.find = find;
function remove(predicate, xs) {
    var index = findIndex(predicate, xs);
    xs.splice(index, 1);
}
exports.remove = remove;
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
// TODO: replace in favor of using polyfill
/**
 * Copies the values of all enumerable properties from one or more source objects to a target object, and returns the target object.
 *
 * @export
 * @param {any} args
 * @returns
 */
function assign() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var target = args[0];
    'use strict';
    if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
    }
    var output = Object(target);
    for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source !== undefined && source !== null) {
            for (var nextKey in source) {
                if (source.hasOwnProperty(nextKey)) {
                    output[nextKey] = source[nextKey];
                }
            }
        }
    }
    return output;
}
exports.assign = assign;
/**
 * Generates a random 5 to 6 character string.
 *
 * @export
 * @returns {string}
 */
function createRandomString() {
    return getRandomValue().toString(36).substring(1);
}
exports.createRandomString = createRandomString;
/**
 * Generates a 20 character uuid.
 *
 * @export
 * @returns {string}
 */
function generateUUID() {
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
        d += performance.now();
    }
    return 'xxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        // Generate a random number, scaled from 0 to 15.
        var r = (getRandomValue() % 16);
        // Shift 4 times to divide by 16
        d >>= 4;
        return r.toString(16);
    });
}
exports.generateUUID = generateUUID;
/**
 * Adds a parameter to the given url
 *
 * @export
 * @param {string} url
 * @param {string} paramName
 * @param {string} value
 * @returns {string}
 */
function addParamToUrl(url, paramName, value) {
    var parameterPrefix = url.indexOf('?') > 0 ? '&' : '?';
    url += parameterPrefix + paramName + '=' + value;
    return url;
}
exports.addParamToUrl = addParamToUrl;
/**
 * Checks if the report is saved.
 *
 * @export
 * @param {HttpPostMessage} hpm
 * @param {string} uid
 * @param {Window} contentWindow
 * @returns {Promise<boolean>}
 */
function isSavedInternal(hpm, uid, contentWindow) {
    return __awaiter(this, void 0, void 0, function () {
        var response, response_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, hpm.get('/report/hasUnsavedChanges', { uid: uid }, contentWindow)];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, !response.body];
                case 2:
                    response_1 = _a.sent();
                    throw response_1.body;
                case 3: return [2 /*return*/];
            }
        });
    });
}
exports.isSavedInternal = isSavedInternal;
/**
 * Checks if the embed url is for RDL report.
 *
 * @export
 * @param {string} embedUrl
 * @returns {boolean}
 */
function isRDLEmbed(embedUrl) {
    return embedUrl.toLowerCase().indexOf("/rdlembed?") >= 0;
}
exports.isRDLEmbed = isRDLEmbed;
/**
 * Checks if the embed url contains autoAuth=true.
 *
 * @export
 * @param {string} embedUrl
 * @returns {boolean}
 */
function autoAuthInEmbedUrl(embedUrl) {
    return embedUrl && decodeURIComponent(embedUrl).toLowerCase().indexOf("autoauth=true") >= 0;
}
exports.autoAuthInEmbedUrl = autoAuthInEmbedUrl;
/**
 * Returns random number
 */
function getRandomValue() {
    // window.msCrypto for IE
    var cryptoObj = window.crypto || window.msCrypto;
    var randomValueArray = new Uint32Array(1);
    cryptoObj.getRandomValues(randomValueArray);
    return randomValueArray[0];
}
exports.getRandomValue = getRandomValue;
/**
 * Returns the time interval between two dates in milliseconds
 * @export
 * @param {Date} start
 * @param {Date} end
 * @returns {number}
 */
function getTimeDiffInMilliseconds(start, end) {
    return Math.abs(start.getTime() - end.getTime());
}
exports.getTimeDiffInMilliseconds = getTimeDiffInMilliseconds;


/***/ }),

/***/ "./src/visual.ts":
/*!***********************!*\
  !*** ./src/visual.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Visual = void 0;
var models = __webpack_require__(/*! powerbi-models */ "./node_modules/powerbi-models/dist/models.js");
var report_1 = __webpack_require__(/*! ./report */ "./src/report.ts");
var visualDescriptor_1 = __webpack_require__(/*! ./visualDescriptor */ "./src/visualDescriptor.ts");
/**
 * The Power BI Visual embed component
 *
 * @export
 * @class Visual
 */
var Visual = /** @class */ (function (_super) {
    __extends(Visual, _super);
    /**
     * Creates an instance of a Power BI Single Visual.
     *
     * @param {service.Service} service
     * @param {HTMLElement} element
     * @param {embed.IEmbedConfiguration} config
     * @hidden
     */
    function Visual(service, element, baseConfig, phasedRender, isBootstrap, iframe) {
        return _super.call(this, service, element, baseConfig, phasedRender, isBootstrap, iframe) || this;
    }
    /**
     * @hidden
     */
    Visual.prototype.load = function (phasedRender) {
        var config = this.config;
        if (!config.accessToken) {
            // bootstrap flow.
            return;
        }
        if (typeof config.pageName !== 'string' || config.pageName.length === 0) {
            throw new Error("Page name is required when embedding a visual.");
        }
        if (typeof config.visualName !== 'string' || config.visualName.length === 0) {
            throw new Error("Visual name is required, but it was not found. You must provide a visual name as part of embed configuration.");
        }
        // calculate custom layout settings and override config.
        var width = config.width ? config.width : this.iframe.offsetWidth;
        var height = config.height ? config.height : this.iframe.offsetHeight;
        var pageSize = {
            type: models.PageSizeType.Custom,
            width: width,
            height: height,
        };
        var pagesLayout = {};
        pagesLayout[config.pageName] = {
            defaultLayout: {
                displayState: {
                    mode: models.VisualContainerDisplayMode.Hidden
                }
            },
            visualsLayout: {}
        };
        pagesLayout[config.pageName].visualsLayout[config.visualName] = {
            displayState: {
                mode: models.VisualContainerDisplayMode.Visible
            },
            x: 1,
            y: 1,
            z: 1,
            width: pageSize.width,
            height: pageSize.height
        };
        config.settings = config.settings || {};
        config.settings.filterPaneEnabled = false;
        config.settings.navContentPaneEnabled = false;
        config.settings.layoutType = models.LayoutType.Custom;
        config.settings.customLayout = {
            displayOption: models.DisplayOption.FitToPage,
            pageSize: pageSize,
            pagesLayout: pagesLayout
        };
        this.config = config;
        return _super.prototype.load.call(this, phasedRender);
    };
    /**
     * Gets the list of pages within the report - not supported in visual embed.
     *
     * @returns {Promise<Page[]>}
     */
    Visual.prototype.getPages = function () {
        throw Visual.GetPagesNotSupportedError;
    };
    /**
     * Sets the active page of the report - not supported in visual embed.
     *
     * @param {string} pageName
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Visual.prototype.setPage = function (pageName) {
        throw Visual.SetPageNotSupportedError;
    };
    /**
     * Render a preloaded report, using phased embedding API
     *
     * @hidden
     * @returns {Promise<void>}
     */
    Visual.prototype.render = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                throw Visual.RenderNotSupportedError;
            });
        });
    };
    /**
     * Gets the embedded visual descriptor object that contains the visual name, type, etc.
     *
     * ```javascript
     * visual.getVisualDescriptor()
     *   .then(visualDetails => { ... });
     * ```
     *
     * @returns {Promise<VisualDescriptor>}
     */
    Visual.prototype.getVisualDescriptor = function () {
        return __awaiter(this, void 0, void 0, function () {
            var config, response, embeddedVisuals, visualNotFoundError, embeddedVisual, currentPage, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        config = this.config;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.get("/report/pages/" + config.pageName + "/visuals", { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        embeddedVisuals = response.body.filter(function (pageVisual) { return pageVisual.name === config.visualName; });
                        if (embeddedVisuals.length === 0) {
                            visualNotFoundError = {
                                message: "visualNotFound",
                                detailedMessage: "Visual not found"
                            };
                            throw visualNotFoundError;
                        }
                        embeddedVisual = embeddedVisuals[0];
                        currentPage = this.page(config.pageName);
                        return [2 /*return*/, new visualDescriptor_1.VisualDescriptor(currentPage, embeddedVisual.name, embeddedVisual.title, embeddedVisual.type, embeddedVisual.layout)];
                    case 3:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets filters that are applied to the filter level.
     * Default filter level is visual level.
     *
     * ```javascript
     * visual.getFilters(filtersLevel)
     *   .then(filters => {
     *     ...
     *   });
     * ```
     *
     * @returns {Promise<models.IFilter[]>}
     */
    Visual.prototype.getFilters = function (filtersLevel) {
        return __awaiter(this, void 0, void 0, function () {
            var url, response, response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = this.getFiltersLevelUrl(filtersLevel);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.get(url, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sets filters at the filter level.
     * Default filter level is visual level.
     *
     * ```javascript
     * const filters: [
     *    ...
     * ];
     *
     * visual.setFilters(filters, filtersLevel)
     *  .catch(errors => {
     *    ...
     *  });
     * ```
     *
     * @param {(models.IFilter[])} filters
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Visual.prototype.setFilters = function (filters, filtersLevel) {
        return __awaiter(this, void 0, void 0, function () {
            var url, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = this.getFiltersLevelUrl(filtersLevel);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.service.hpm.put(url, filters, { uid: this.config.uniqueId }, this.iframe.contentWindow)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Removes all filters from the current filter level.
     * Default filter level is visual level.
     *
     * ```javascript
     * visual.removeFilters(filtersLevel);
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    Visual.prototype.removeFilters = function (filtersLevel) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.setFilters([], filtersLevel)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * @hidden
     */
    Visual.prototype.getFiltersLevelUrl = function (filtersLevel) {
        var config = this.config;
        switch (filtersLevel) {
            case models.FiltersLevel.Report:
                return "/report/filters";
            case models.FiltersLevel.Page:
                return "/report/pages/" + config.pageName + "/filters";
            default:
                return "/report/pages/" + config.pageName + "/visuals/" + config.visualName + "/filters";
        }
    };
    /** @hidden */
    Visual.type = "visual";
    /** @hidden */
    Visual.GetPagesNotSupportedError = "Get pages is not supported while embedding a visual.";
    /** @hidden */
    Visual.SetPageNotSupportedError = "Set page is not supported while embedding a visual.";
    /** @hidden */
    Visual.RenderNotSupportedError = "render is not supported while embedding a visual.";
    return Visual;
}(report_1.Report));
exports.Visual = Visual;


/***/ }),

/***/ "./src/visualDescriptor.ts":
/*!*********************************!*\
  !*** ./src/visualDescriptor.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports) {

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VisualDescriptor = void 0;
/**
 * A Power BI visual within a page
 *
 * @export
 * @class VisualDescriptor
 * @implements {IVisualNode}
 */
var VisualDescriptor = /** @class */ (function () {
    /**
     * @hidden
     */
    function VisualDescriptor(page, name, title, type, layout) {
        this.name = name;
        this.title = title;
        this.type = type;
        this.layout = layout;
        this.page = page;
    }
    /**
     * Gets all visual level filters of the current visual.
     *
     * ```javascript
     * visual.getFilters()
     *  .then(filters => { ... });
     * ```
     *
     * @returns {(Promise<models.IFilter[]>)}
     */
    VisualDescriptor.prototype.getFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.get("/report/pages/" + this.page.name + "/visuals/" + this.name + "/filters", { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_1 = _a.sent();
                        throw response_1.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Removes all filters from the current visual.
     *
     * ```javascript
     * visual.removeFilters();
     * ```
     *
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    VisualDescriptor.prototype.removeFilters = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.setFilters([])];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Sets the filters on the current visual to 'filters'.
     *
     * ```javascript
     * visual.setFilters(filters);
     *   .catch(errors => { ... });
     * ```
     *
     * @param {(models.IFilter[])} filters
     * @returns {Promise<IHttpPostMessageResponse<void>>}
     */
    VisualDescriptor.prototype.setFilters = function (filters) {
        return __awaiter(this, void 0, void 0, function () {
            var response_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.put("/report/pages/" + this.page.name + "/visuals/" + this.name + "/filters", filters, { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_2 = _a.sent();
                        throw response_2.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Exports Visual data.
     * Can export up to 30K rows.
     * @param rows: Optional. Default value is 30K, maximum value is 30K as well.
     * @param exportDataType: Optional. Default is models.ExportDataType.Summarized.
     * ```javascript
     * visual.exportData()
     *  .then(data => { ... });
     * ```
     *
     * @returns {(Promise<models.ExportDataType>)}
     */
    VisualDescriptor.prototype.exportData = function (exportDataType, rows) {
        return __awaiter(this, void 0, void 0, function () {
            var exportDataRequestBody, response, response_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        exportDataRequestBody = {
                            rows: rows,
                            exportDataType: exportDataType
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.page.report.service.hpm.post("/report/pages/" + this.page.name + "/visuals/" + this.name + "/exportData", exportDataRequestBody, { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 3:
                        response_3 = _a.sent();
                        throw response_3.body;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Set slicer state.
     * Works only for visuals of type slicer.
     * @param state: A new state which contains the slicer filters.
     * ```javascript
     * visual.setSlicerState()
     *  .then(() => { ... });
     * ```
     */
    VisualDescriptor.prototype.setSlicerState = function (state) {
        return __awaiter(this, void 0, void 0, function () {
            var response_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.put("/report/pages/" + this.page.name + "/visuals/" + this.name + "/slicer", state, { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_4 = _a.sent();
                        throw response_4.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Get slicer state.
     * Works only for visuals of type slicer.
     *
     * ```javascript
     * visual.getSlicerState()
     *  .then(state => { ... });
     * ```
     *
     * @returns {(Promise<models.ISlicerState>)}
     */
    VisualDescriptor.prototype.getSlicerState = function () {
        return __awaiter(this, void 0, void 0, function () {
            var response, response_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.get("/report/pages/" + this.page.name + "/visuals/" + this.name + "/slicer", { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_5 = _a.sent();
                        throw response_5.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Clone existing visual to a new instance.
     *
     * @returns {(Promise<models.ICloneVisualResponse>)}
     */
    VisualDescriptor.prototype.clone = function (request) {
        if (request === void 0) { request = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var response, response_6;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.post("/report/pages/" + this.page.name + "/visuals/" + this.name + "/clone", request, { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, response.body];
                    case 2:
                        response_6 = _a.sent();
                        throw response_6.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sort a visual by dataField and direction.
     *
     * @param request: Sort by visual request.
     *
     * ```javascript
     * visual.sortBy(request)
     *  .then(() => { ... });
     * ```
     */
    VisualDescriptor.prototype.sortBy = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var response_7;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.page.report.service.hpm.put("/report/pages/" + this.page.name + "/visuals/" + this.name + "/sortBy", request, { uid: this.page.report.config.uniqueId }, this.page.report.iframe.contentWindow)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        response_7 = _a.sent();
                        throw response_7.body;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    return VisualDescriptor;
}());
exports.VisualDescriptor = VisualDescriptor;


/***/ })

/******/ });
});
//# sourceMappingURL=/assets/powerbi-2.16.2/powerbi.js-36035d63bdae949625f77ee7149ad7c290ea39fdedc6b550bf806a6d96382fd9.map
//!
;
// Things we should require site-wide:


























;
